My Delphi 7 with Firebird 1.5.6 application is freezing itself after some time of inactivity on Windows 7

I have developed a Delphi 7 application that is using Firebird 1.5.6 database in client
server environment.

The application is running on Windows 7 32 bit on notebook computer an the database is running
on Windows XP 32-bit machine that is used as a server.
The problem is the application is freezing itself when it is left idle for some time.
This problem never occured on Windows XP only when we installed it on Windows 7.

Everything was working fine for 5 years but now on Windows 7 the application is totaly unstable.

Sometimes the wake up time is 10-30 sec with success but sometimes never with messages "application not responding" or "application crashes".

I have no idea where to search or what to try to find a solution.
I tried to make a timer with 10 secconds resolution to make it constantly active
but with no success.

BTW I am running in Administrator mode with XP Compatibility mode active.
I have not tried the virtual XP Mode yet but I think it will not solve the problem.


TypeError: 'module' object is not callable in Spacy Python

I want to print Parse Tree using Spacy. But the code below is giving the error

en_nlp = spacy.language('English')
  TypeError: 'module' object is not callable

The error is on this en_nlp = spacy.loads('en') line. I tried to shake off as en_nlp = spacy.language(English) by importing from spacy.en import English But still it is not working. Can someone help?

Code:

import spacy
from nltk import Tree

en_nlp = spacy.loads('en')

doc = en_nlp("The quick brown fox jumps over the lazy dog.")

def to_nltk_tree(node):
    if node.n_lefts + node.n_rights > 0:
        return Tree(node.orth_, [to_nltk_tree(child) for child in node.children])
    else:
        return node.orth_

[to_nltk_tree(sent.root).pretty_print() for sent in doc.sents]


How to update data on server via AJAX when ng-model input value is changed

I'm new to Angular and I have one problem I cannot find a solution for. Any help is appreciated.

I'm fetching all the data from a server to a controller using $http.get("/admin/getGraphData"). When user edits <input> element, a data in controller is updated by Angular. When that occurs, I would want the data on the server (MySQL) to be updated instantly. Is there an easy way to achieve this? If I could do something like this:

$scope.onDayValueChange(month, year, day, newValue){
    $http.post("/admin/updateDayValue", {...})
}

But how to intercept Controllers data change and how to know exact index of object being changed or something like this? Thanks a lot!

Data model is fairly simple. Months (jan, feb, mar...) containing some value for each of a day in a month:

{month: 1, year: 2013, data:[{day:1, val:11}, {day:2, val:14}, ..., {day:31, val:80}]}
{month: 2, year: 2013, data:[{day:1, val:22}, {day:2, val:124}, ..., {day:30, val:2}]}
...

In HTML it looks something like this:

The code:

<div ng-app="graph" ng-controller="GraphCtrl">
    <ul>
        <li class="monthItem" ng-repeat="monthItem in months">
            <span>
                {{monthNames[monthItem.month-1]}}
                ({{monthItem.month}}.
                {{monthItem.year}}.)</span>

            <ul class="monthDays">
                <li ng-repeat="dayItem in monthItem.data">
                    <label>{{dayItem.day}}.
                    <input type="number"
                        ng-model="dayItem.val"
                        value="{{dayItem.val}}"
                        min="0" required>
                    </label>
                </li>
            </ul>

        </li>
    </ul>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.5/angular.min.js"></script>
<script>
    var app = angular.module('graph');
    app.controller('GraphCtrl', function($scope, $http) {

    getData(); // load all data to the model

    function getData(){
        $http.get("/admin/getGraphData").success(function(data){
            $scope.months = data;
        })
    };

    $scope.monthNames = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
});
</script>


if mysql query is null or doesn't exist?

I have a mysql query which gets 5 stars if a user rating is set to 5, like a star rating system. Another 4 of the same script which get 1, 2, 3 or 4 stars according to the rating 1-5.

What i want is for an image to be echoed if their are no results in the mysql table. I have tried the below but nothing is echoed. can someone show me what i would need to do please?

I've tried adding this bit of code but i just get an array error.

<?php
if (is_null($get_star_rating_set))
{
    echo "HELLO";
}
?>

Here's the code normally:

<?php
$get_star_rating_set = get_star_rating();
while ($rating = mysql_fetch_array($get_star_rating_set))
    if ($rating['rating'] == '0') { echo '
      <div class="star-rate">
        <table width="40%" border="0" cellspacing="5" cellpadding="0">
          <tr>
            <td width="17%" align="left" valign="middle" scope="col"><img src="../PTB1/assets/img/icons/favorites.png" id="R1" alt="0" style="cursor:pointer" title="Not at All" width="27" height="25" /></td>
            <td width="17%" align="left" valign="middle" scope="col"><img src="../PTB1/assets/img/icons/favorites.png" id="R2" alt="1" style="cursor:pointer" title="Somewhat"   width="27" height="25" /></td>
            <td width="17%" align="left" valign="middle" scope="col"><img src="../PTB1/assets/img/icons/favorites.png" id="R3" alt="2" style="cursor:pointer" title="Average"    width="27" height="25" /></td>
            <td width="17%" align="left" valign="middle" scope="col"><img src="../PTB1/assets/img/icons/favorites.png" id="R4" alt="3" style="cursor:pointer" title="Good"       width="27" height="25" /></td>
            <td width="24%" align="left" valign="middle" scope="col"><img src="../PTB1/assets/img/icons/favorites.png" id="R5" alt="4" style="cursor:pointer" title="Very Good"  width="27" height="25" /></td>
          </tr>
        </table>
      </div>';
    }
?>


Is there any advantage of joining on an indexed and non-indexed columns at the same time?

If i have a join on a non-indexed column, will adding another criteria in the join on an indexed column help?

For eg - Two tables Table1 and Table2 exist. the column tran_date is indexed, but tran_id is not. Will the second code run faster than the first? If so, how does SQL exactly operate on such joins? Table1 is unique on tran_id, while table2 is unique at tran_id - sku level.
Also, tran_id is a varchar(50) type of column

SELECT a.tran_id, a.tran_date, b.sku
from table1 a
inner join table2 b
on a.tran_id = b.tran_id;

vs

SELECT a.tran_id, a.tran_date, b.sku
from table1 a
inner join table2 b
on a.tran_id = b.tran_id and a.tran_date = b.tran_date;

I'm using Oracle environment


php script randomly hangs up

I install php 5 (more precisely 5.3.1) as apache module.

After this one of my application becomes randomly hang up on mysql_connect - sometimes works, sometimes no, sometimes reload of page helps.

How can this be fixed?

I use Windows Vista, Apache/2.2.14 (Win32) PHP/5.3.1 with php module, MySql 5.0.67-community-nt.

After a minute I obtain the error message:

Fatal error: Maximum execution time of 60 seconds exceeded in path\to\mysqlcon.php on line 9

I run MySql locally and heavy load could not be a reason:

SHOW PROCESSLIST shows about 3 process

SHOW VARIABLES LIKE 'MAX_CONNECTIONS' is 100.

UPDATE:

At first I thought that this is connected with mysql_connect.
But now I can't say for certain.

More difficult thing is when I insert the line to debug:

$fh = fopen("E://_debugLog", 'a'); fwrite($fh, __FILE__ . " : " . __LINE__ . "\n"); fclose($fh);

script start working near that location as a rule.

Restart of apache resolve the issue.


How to override component default property values

I am using the Kendo UI NumericTextBox component for Angular 2 throughout my app. There are a number of properties that I keep setting to the same value. Is there a way to change the default property values at either the app and/or component level?

Here is a simplified example of my current code:

@Component({
  selector: 'my-app',
  template: `
    <kendo-numerictextbox
      [autoCorrect]="ns.autoCorrect"
      [min]="ns.min"
      [max]="ns.max"
      [value]="value1"
    ></kendo-numerictextbox>
    <kendo-numerictextbox
      [autoCorrect]="ns.autoCorrect"
      [min]="ns.min"
      [max]="ns.max"
      [value]="value2"
    ></kendo-numerictextbox>
  `
})

class AppComponent {
  public ns: {
    autoCorrect: true,
    min: 0,
    max: 99
  };

  public value1 = 5;
  public value2 = 10;
}

I'm hoping to have something like this:

@Component({
  selector: 'my-app',
  template: `
    <kendo-numerictextbox
      [value]="value1"
    ></kendo-numerictextbox>
    <kendo-numerictextbox
      [value]="value2"
    ></kendo-numerictextbox>
  `
})

class AppComponent {
  // Override existing NumericTextBoxComponent default values
  NumericTextBoxComponent.autoCorrect = true;
  NumericTextBoxComponent.min = 0;
  NumericTextBoxComponent.max = 99;

  public value1 = 5;
  public value2 = 10;
}


Providing multiple formats (ogg,mp3) while creating Audio dynamically

When using html5 audio you can provide multiple formats/codecs with:

<audio controls>
   <source src="horse.ogg" type="audio/ogg">
   <source src="horse.mp3" type="audio/mpeg"> <-- secondary format here
   Your browser does not support the audio element.
</audio>

I create Audio with

var audio = new Audio('pathtomyaudio/myaudio.mp3');
audio.load();

Is there a way to dynamically provide another extension such as ogg?

Any help appreciated :)


Can't open a .jar file on my mac

I'm trying to download jsoup on my mac (Mountain Lion). I've downloaded the jsoup.jar file and installed the last java 7 from the site. But here is the problem, when I double click the .jar file it tells to me:

The Java JAR file “jsoup-1.7.2.jar” could not be launched. Check the
  console.

I can't find even the console! Someone can help me? I read a lot of answers about this topic, but they all talk about Java 6 and it has different settings that can't find.

EDIT

i also tried from the terminal with this command:

java -jar /Users/Ben/Downloads/jsoup-1.7.2.jar

but it tells me:

Failed to load Main-Class manifest attribute from
  /Users/Ben/Downloads/jsoup-1.7.2.jar


Is there an operation Step Back in NetBeans during debug process?

In NetBeans when you insert Breakpoint and Debug project, it runs code until the Breakpoint and stop right in a line where we put Breakpoint. And afterwards we can execute our code step by step. If we Press F8 which is Step Over operation, NetBeans executes next line. Sometimes we want to go back to the previous executed line because we want to change that line and see how it will work.

So, the question is how can I say NetBeans to Step Back (if we can call this like this), so instead of executing next line code it executes previous line code? I remember in Visual Basic 6.0 (now I don't know because don' t use it anymore) we could manage current execution line, i.e. we could just drag and drop debug pointer to the line we want during the debugging and it would start to execute code right from the place we put it. Is it possible in NetBeans?

Update 1

I use NetBeans for debugging PHP application. PHP uses php_xdebug-2.1.0RC1-5.3-vc9-nts.dll  to to debug PHP code.


How to redirect a domain to a web page?

I have a Wordpress website => www.mywebsite.com
where I can create pages such as : www.mywebsite.com/page-hello.html

I also have a domain : hello.com

I would like to redirect the website hello.com to the page www.mywebsite.com/page-hello.html while keeping hello.com in the URL.

Basically hello.com stays in the UTL but users will see this page > www.mywebsite.com/page-hello.html


Android error cannot acess AbstractSafeParcelable

I'm tryind add firebase remote config to my project, but it is conflicting with the version of my gms, the error code:

Error:(674, 25) error: cannot access AbstractSafeParcelable
  class file for com.google.android.gms.common.internal.safeparcel.AbstractSafeParcelable not found

And when i click its send me for this method of my project:

    protected void RequestLocation() {
    locationRequest = new LocationRequest();
    locationRequest.setInterval(10000); // for this line
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

I tried some suggestions that I found in the stackoverflow itself, like changing the version of gms to 10.0.1 but ends up generating another error:

Error:Execution failed for task ':app:processDebugGoogleServices'.
  Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.2.

My original build.gradle can be checked here:`apply plugin:

'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '25.0.0'
    defaultConfig {
        applicationId "my.editable.project"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 28
        versionName "1.4.4"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
    lintOptions {
        disable 'MissingTranslation'
        checkReleaseBuilds false
    }

    dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile files('libs/ksoap2-android-assembly-3.5.0-jar-with-dependencies.jar')
    //compile files('libs/gcm.jar')
    //compile files('libs/gcm-src.jar')
    compile project(':firebase_plugin')
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:support-v4:23.1.1'
    compile 'com.google.android.gms:play-services:9.0.2'
    compile 'com.google.android.gms:play-services-ads:9.0.2'
    compile 'com.google.android.gms:play-services-auth:9.0.2'
    compile 'com.google.android.gms:play-services-gcm:9.0.2'
    compile 'com.android.support:multidex:1.0.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.google.firebase:firebase-config:10.0.1'
}

apply plugin: 'com.google.gms.google-services'`


Gulp cwd to project root

My current code:

gulp.task('_sass', function() {
    var files = [
        './vendor/bower_components/bootstrap-sass/assets/stylesheets/_bootstrap.scss',
        './resources/assets/sass/main.scss',
        './vendor/bower_components/bootstrap-rating/bootstrap-rating.css',
        './vendor/bower_components/select2/select2.css'
    ];
    return gulp.src(files)
    //return gulp.src(files)
        .pipe(concat('all.css'))
        .pipe(sass())
        .on('error', notify.onError(function (error) {
            return "Error: " + error.message;
        }))
        .pipe(gulp.dest('./public/css/'))
        .pipe(reload({stream: true}));
});

As you can see, I have a files array where I store all the paths to the .scss files I want to concat into all.css. But I get this error:

Error: file to import not found or unreadable: base/normalize
Current dir: /Users/**/Code/Laravel/vendor/bower_components/bootstrap-sass/assets/stylesheets/

which is obvious, because gulp uses the first path of the array as it's base directory. So I tried settings the base or the cwd to './', so I could specify my Laravel root directory. But that doesn't work. How can I solve this problem, so I can use all these .scss files without copying files to other directories?


background color not changing on hover css

I used this for styling navigation bar of my webpage but the color is not changing on hover

.nav {
    list-style-type:none;
    margin:0;
    padding:0;
    overflow:hidden;
}

.nav li {
    float: left;
}

.nav li a:hover,.nav li a:active {
    background-color:#7A991A;
}

.nav li a:link,.nav li a:visited {
    display:block;
    width:9em;
    font-weight:bold;
    color:#FFFFFF;
    background-color:#98bf21;
    text-align:center;
    padding:4px;
    text-decoration:none;
    text-transform:uppercase;
}

HTML code:

<ul class = "nav">
        <li><a href="index.html">Home</a></li>
        <li><a href="products.html">Our Products</a></li>
        <li><a href="aboutus.html">Contact us</a></li>
</ul>

can someone suggest what I did wrong?


emacs like fill-paragraph option in textmate?

Is there an option to reformat lines/paragraphs/selected text to 80 cols in TextMate like in emacs (fill-paragraph bound to M-q)?  If not, do you know of any option to add this to TextMate - a known plugin/macro?  any help in writing such a macro is most welcome too. :)


multiple conditions inside click function not working

With this code and chk1 and chk2 as 0, is impossible to me to guess what is wrong with this simple code function.

As i know, there are many js ways to use click, like ".click()", ".on('click')" or ".onClick" but none of them works at all. Take a look of this example:

            regbtn.click(function() {
                            if(chk1 == 0){
                                if(chk2 == 1){
                                    box2.reverse();
                                    chk2 = 0;
                                }
                                box1.restart();
                                chk1 = 1;
                                }
                            });

        logbtn.click(function() {
                            if(chk2 == 0){
                                if(chk1 == 1){
                                    box1.reverse();
                                    chk1 = 0;
                                }
                                box2.restart();
                                chk2 = 1;
                                }
                            });

Is there any reason why this doesnt work properly? and which way is the newest and best to use of this 3 ways of click js functions.

EDIT

regbtn and logbtn are 2 buttons that open 2 diferent boxes, box1 and box2 respectively, chk1 and chk2 is to check if the other box is open and reverse it first if so.

Alert doesnt work at all in any place.

This is the initial code variables to work with:

    var regbox = document.getElementById("regbox"),
        logbox = document.getElementById("logbox"),
        regbtn = document.getElementById("regbtn"),
        logbtn = document.getElementById("logbtn");
    var chk1 = 0,
        chk2 = 0;


Work with a global variable initialized via BehaviorSubject / Angular2

I've got Catalog Component and Cart Service in my app. And I want to add products from my Catalog (array of objects stored in JSON) to the Cart.

So, I need my Cart to be changed dynamically when I add / remove a product.
For that reason I am trying to use { BehaviorSubject }.

Cart Service:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';

@Injectable()
export class CartService {
  public cart = new BehaviorSubject(null);//my globally available Cart

}

Catalog Component:

import { Component, OnInit } from '@angular/core';
import { CatalogService } from './catalog.service';
import { CartService } from '../cart/cart.service';//my globally available Cart imported to the current component

@Component({
  selector: 'catalog',
  templateUrl: './catalog.component.html',
  styleUrls: ['./catalog.component.scss']
})

export class CatalogComponent implements OnInit {
  catalog: any;
  image: any;
  title: string;
  description: string;
  prod: any;
  visible: boolean;

constructor(public catalogService: CatalogService, public cartService: CartService){ }

ngOnInit(){

    this.catalogService.getCatalogItems().subscribe(
        (data) => this.catalog = data
    );
}

  toCart(prod){
      this.cartService.cart.subscribe((val) => {
            console.log(val);
      });

    this.cartService.cart.push(prod);//I want to add new product to the Cart by this
  }

}

But Console throws the following error:

So, what should I do to use my Cart globally via BehaviorSubject?


PHP: Extracting numbers from a page

Im extracting data from a page with multiple userinput ratings, which means the syntax is a bit sloppy.
The text goes something like this:

<span date="12/10/2014">4.957/10</span>
<span date="12/10/2014">11/10</span>
<span date="12/10/2014">5 / 10</span>
<span date="12/10/2014">i say: 9 /10</span>
<span date="12/10/2014">10/ 10</span>
<span date="12/10/2014">0.1/10, no more</span>

how would you go about fetching these ratings?
the ratings will go from 0 to 1000000, and have a maximum of 3 decimals.

The resulting array of the above should be:

4.957
11
5
9
10
0.1

So basically the rules should go like this:

* Match any number with "/10" behind it.

* The number can be followed by a dot and up to 3 additional numbers.

* There might be a space between the / and the rating, also between the / and 10.

* There should not be another / after the /10.


How to take Database backup without using phpmyadmin in Mysql Xampp

I am trying to take database backup from my phpmyadmin. Because of some issue, I am not able to start my Xampp control panel. That's why I am not able to open phpmyadmin panel.

Please give me an idea to take backup.


How to change line spacing in ggplot xlab?

My X axis label is too long, so I used xlab(expression(atop(paste("Hello world"^"TM ", ":Hi"),paste("hello again"^"TM",": Hi")))) to split it into two lines. The line spacing is too big, and I applied the method axis.title.x=element_text(lineheight=0.2) to change line spacing, but it did not change anything. The method was adapted from here. My question is how to change line spacing for xlab. Thank you in advance!


Convert timestamp ISO to datetime in Python?

I am trying to convert an ISO timestamp column in my dataset to datetime. I'm able to successfully convert certain rows but others fail without a noticeable pattern.

Here is what my raw data looks like:

911     2015-10-15T12:39:36
2520    2015-10-02T14:54:58
2545    2015-09-18T21:07:40
805     2015-10-28T17:17:22

I try to run this code on it:

datetime.strptime(orders['Timestamp'][58], "%Y-%m-%dT%H:%M:%S")

Sometimes it works and turns into datetime:

2015-05-16 08:46:10
2015-05-15 17:02:04
2015-05-15 16:43:42
2015-05-15 16:40:16

Every 50 rows or so it throws up an error:

KeyError                                  Traceback (most recent call last)
<ipython-input-130-2db5a7ab5914> in <module>()
      1 for i in range(116, len(orders['Timestamp'])):
----> 2     df_dt=datetime.strptime(orders['Timestamp'][i],"%Y-%m-%dT%H:%M:%S")
      3     print df_dt

c:\python27\lib\site-packages\pandas\core\series.pyc in __getitem__(self, key)
    549     def __getitem__(self, key):
    550         try:
--> 551             result = self.index.get_value(self, key)
    552
    553             if not np.isscalar(result):

c:\python27\lib\site-packages\pandas\core\index.pyc in get_value(self, series, key)
   1721
   1722         try:
-> 1723             return self._engine.get_value(s, k)
   1724         except KeyError as e1:
   1725             if len(self) > 0 and self.inferred_type in ['integer','boolean']:

pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:3204)()

pandas\index.pyx in pandas.index.IndexEngine.get_value (pandas\index.c:2903)()

pandas\index.pyx in pandas.index.IndexEngine.get_loc (pandas\index.c:3843)()

pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6525)()

pandas\hashtable.pyx in pandas.hashtable.Int64HashTable.get_item (pandas\hashtable.c:6463)()

KeyError: 268L

Can't tell why the other dates are successfully converted but not these (can't see a pattern):

2015-05-30T22:25:52
2015-03-04T03:57:51
2013-11-22T22:28:23

Thanks.


Google Drive API / SDK, change owner using service account fails

I try to update the owner permission of some files in google drive using google drive api v2 programmatically.(like Google Admin Console does on "Drive / Transfer Ownership" form)
I created a service account and use its ID combined with a super-admin account to create credentials and "DriveService" object.
I able to list all files shared with me and enumerate the "Owners" collection of "File". Adding a new permission to a file (role="writer") works fine. If I try to change the new permission to role ="owner" I get an INTERNAL ERROR 500.

Had anyone seen that error before and how can I work around?

This is my code:

// ---------------------- BUILD CREDENTIALS -------------------------------
Google.Apis.Auth.OAuth2.ServiceAccountCredential m_Creds = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(<MY_SERVICE_ACCOUNT>)
                    {
                        Scopes = new[]
                                     {
                                         DriveService.Scope.Drive,
                                         DriveService.Scope.DriveFile,
                                         DriveService.Scope.DriveAppdata
                                     }
                        ,
                        User = <MY_ADMIN_ACCOUNT>
                    }.FromCertificate(certificate));

// ---------------------- BUILD CLIENTINIT -------------------------------
var myCInit = new BaseClientService.Initializer
            {
                ApplicationName = "Testapplication",
                HttpClientInitializer = m_Creds
            };

string myAccountname = "Test User1"; // accountname to look for
string myNewAccountEmail = "Test.User2@mydomain.com"; // email of new owner account

// ---------------------- DRIVE SERVIVE CREATION -------------------------------
var myDService = new DriveService(myCInit);

// ----------------------- GET THE FILE LIST------------------------------------
var myFList = myDService.Files.List().Execute();

         foreach (Google.Apis.Drive.v2.Data.File currF in myFList.Items)
            {

             foreach (Google.Apis.Drive.v2.Data.User currUser in currF.Owners)
                {
                    if (currUser.DisplayName.StartsWith(myAccountname))
                    {
                        // create new permission for new owner
                        Permission p = new Permission();
                        p.Role = "writer";
                        p.Type = "user";
                        p.Value = myNewAccountEmail;
                        myDService.Permissions.Insert(p, currF.Id).Execute(); // works fine, creates new permission

                        // get permission id
                        var myNewID = myDService.Permissions.GetIdForEmail(myNewAccountEmail).Execute();

                        // get my newly created permission
                        p = myDService.Permissions.Get(currF.Id, myNewID.Id).Execute();
                        p.Role = "owner";

                        // create update request
                        var myUpdR = myDService.Permissions.Update(p, currF.Id,myNewID.Id);
                        myUpdR.TransferOwnership = true; // yes, we want to be an owner

                        myUpdR.Execute();  // this call gets an "internal error 500"
                    }
                }
            }

Any help is appreciated.

Thx. TL


How to change password reset messages in laravel 5?

How to change laravel's "The email field is required." on password reset page to my custom message? Cant find rules and messages for it


Controller action not found

I am using web api in my application. Web api 2 routing is working fine but the controller action routing is not found.

this is my global cs

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        FluentValidationModelValidatorProvider.Configure();
    }
}

Route Config

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}",
            defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
        );
    }
}

Web api config

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultDataApi",
            routeTemplate: "Api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Controller

public class LoginController : Controller
{
    public ActionResult Index()
    {
        return View("~/Views/Default/Login.cshtml");
    }

    public ActionResult LogOut()
    {
        var ctx = Request.GetOwinContext();
        var authManager = ctx.Authentication;

        authManager.SignOut("ApplicationCookie");
        return RedirectToAction("index", "home");
    }
}


What does the "J" in JApplet mean?

What does the "J" in JApplet mean?


Attaching listener to dialog

I need to be notified when there are changes on the screen. Currently I am using

this.getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
        {
            @Override
            public void onGlobalLayout()
            {
                Log.d("TAG", "GLOBAL LAYOUT");
            }
        });

But it doesn't work when dialog(custom, alert, progress, etc.) is shown or dismissed. I understand that dialogs are shown on another overlay so listener isn't attached to them. How can I get my desired functionality?


Counting rows by the different date

I have a column of dates and a column of items.

Hi Everyone
I want to count the number of items for a certain date, how many of them are per day.
Column 1 Date - Column 2 - Items

01.09.2009  IT004
01.09.2009  IT004
01.09.2009  IT005
01.09.2009  IT006
01.09.2009  IT006
01.09.2009  IT006
06.09.2009  IT004
06.09.2009  IT004
06.09.2009  IT005
07.09.2009  IT004
07.09.2009  IT005
07.09.2009  IT005
07.09.2009  IT006

              01.09.2009   06.09.2009   07.09.2009
For It004         2            2             1
For It005         1            1             2
For It006         3            0             1

Any help would be greatly appreciated and many thanks in advance.

Atanas


Create 2D array with the same size as another array and initialize with zero in python

I have a 2D array in python, like the following:

2d_array_1 =[[0,1],[1,0]]

And want to create a second array of the same size, with all values initialized to zero.

How can I do that in python, if the size of the initial array can vary?


Qt designer - how to create QDialog?

It is possibility to create QDialog in Qt-creator like for example QForm (by clicking)? I've found several samples, but QDialog is created programmatically.
I want to drag and drop buttons, listview and others components on QDialog.
Now I can add new components only by modifying code.

Thanks


ios objective -c variables

The following sample program, when using the variable working. When using more variables, the program mixed. Can you solve it without a variable?
The sample code ;

tableView - didSelectRowAtIndexPath

int indexpath_row = 0;
UITableView *table1;

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (tableView == self.searchDisplayController.searchResultsTableView) {
        indexpath_row = indexPath.row + 5;
        table1 = self.searchDisplayController.searchResultsTableView;
    }else{
        if (indexPath.section == 1) {
            indexpath_row = indexPath.row +1;
            table1 = self.tableView;
        }
    }

    myActionSheet.tag = tableView == self.tableView ? 10 : 11;
    [myActionSheet showFromTabBar:self.tabBarController.tabBar];

    // this example. normally you have more variables
    // ActionSheet or Alertview
}

ActionSheet or Alertview

- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex; {

    switch (buttonIndex) {
        case 1:{
            if (actionSheet.tag == 10)
                [self tableView:self.tableView accessoryButtonTappedForRowWithIndexPath:[NSIndexPath indexPathForRow:indexpath_row inSection:1]];
            else
                [self tableView:self.searchDisplayController.searchResultsTableView accessoryButtonTappedForRowWithIndexPath:[NSIndexPath indexPathForRow:indexpath_row inSection:1]];
            break;
        }
        case 2:{
            if (actionSheet.tag == 10)
                [self Run_Sub:table1 Satir_No:indexpath_row];
            else
                [self Run_Sub_Search:table1 Satir_No:indexpath_row];
            break;
        }
            //etc.

        default:
            break;
    }
}

Can we do without them? int indexpath_row and UITableView *table1.
nsnotification as well as, Defining whether a location to another location would like to run. Is this possible?


ASP.NET: I'm having trouble getting file path's to work on my Cluster manager Page

I have a cluster manager page I made with a navigational menu.  I use this cluster manager page on my file default.aspx and also pro/page.aspx. The image and link references don't match up depending on which page I'm on.  I attempted something like ~/page.aspx?function=a && ~/Images/menu/a.gif. However these don't work. I can get the paths to work in certain cases, but then they never work on the other page.  Can anyone point me in the direction of a fix for this? Thanks!


Service detection for .NET Core

Could you please suggest a method for .NET Core which is able to detect in runtime whether the code is executed within a service or not?

I have the working code for .NET Framework but I think it is impossible to port it because it is based on properties unavailable in .NET Core 1.1.


Getting the offset to .text section code PE file format? VirtualAddress, PointerToRawData?

I've been trying to do this for about two days, with no success. I have been reading over many PE file format tutorials to no avail.

I map a 32 bit executable into memory via CreateFileMapping which works perfectly. My program then loops through the section headers, and checks the characteristics against my default characteristics (to make sure the section is executable and is code). If it is true the program returns the (PIMAGE_SECTION_HEADER) pointer to that section header (program works perfectly so far).

Now that I have the pointer, there are two specific entries to the structure that have baffled me, and that is PointerToRawData and VirtualAddress, when I cout the entries;
VirtualSize = 4096, PointerToRawData = 1536.

From what I have read in PE documentation, is that PointerToRawData is a supposed offset (RVA???) to the first byte of data in the section on disk (am I correct?), and is a multiple of a alignment value (512). The question is what do I set this value to, to obtain a pointer which I can use to access the section's data. On a memory-mapped file would it be better to use (VirtualAddress value + the imagebase value) to find the first byte of the section?

Another point of confusion is VirtualSize vs SizeOfRawData. This has confused me because in this article - http://msdn.microsoft.com/en-us/library/ms809762.aspx, it says "The SizeOfRawData field (seems a bit of a misnomer) later on in the structure holds the rounded up value" yet my VirtualSize is greater than my SizeOfRawData value which has led to confusion on which one I should use.

The object of this program is to find the executable section (.text section) and perform a bitwise operation on all the bits in the section, and end the operation before the next section.

I don't want it to seem like I expect a spoonfeed, I just want some clarifications.

Thank you for your time/help, it is appreciated.


When to use deleteOnExit and not delete?

First of all I am not asking for difference between the two. I am wondering what     will be a scenario where one will choose to use deleteOnExit() over delete().


Android Supporting Multiple Screens

Hi I created my own Android App. It worked well but when I tested it in multiple devices I noticed that it is not supporting Multiple Screens although my app call HTML files from assets directory  .

Activity XML

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    tools:context=".ElarabyGroup" />

 <LinearLayout
          android:layout_width="match_parent"
          android:layout_height="match_parent">

     <WebView android:id="@+id/web_engine"
         android:layout_width="match_parent"
         android:layout_height="match_parent">
     </WebView>
 </LinearLayout>

Manifest

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".ElarabyGroup"
        android:label="@string/title_activity_elaraby_group" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


counting the number of items in an array

I have a string as shown bellow:

SIM types:Azadi|Validity:2 Nights|Expirable:yes

I have the following code to seperate them by | and then show them line by line

$other = "SIM types:Azadi|Validity:2 Nights|Expirable:yes";

$others['items'][] = explode("|",$other);
for($i = 0; $i < count($others['items']); $i++){
    echo $others['items'][$i];
}

but the for loop is iterated only once and prints only the first value. This is what i am getting now:

SIM types:Azadi


C++ : Using void to create variables

I am learning C++ on my own from the internet. I was wondering if you can create a variable of the void type. If so , how can you? Also what will be these variables used for?

This does not work:

void b;
cout<<b;

Error:

Size of b is unknown or zero

Thanks :)


rails updating a user's record by their email

I have an app with an account model and an account manager (user).

I would like the account manager to be able to add other users to the account by typing in their email.

The account id of the account manager should be added to the new user's record.

My model looks like

class Account < ActiveRecord::Base
  has_many users
  ...
end

class User < ActiveRecord::Base
  belongs_to account
  ...
end

In the console it's fairly simple.

u = User.find(2)
u.update_attributes(account_id: 1)

But I'm not sure how to do this on the site.

I have the below partial which renders fine but when I put an email in the box nothing happens.

I get the message, user not added.

<h4>Add User</h4>
<div class = "row">
    <div class="col-md-6 col-md-offset-3">
        <%= form_for(:add_user, url: add_users_path) do |f| %>
      <%= f.hidden_field @account = Account.find(params[:id]) %>
      <%= f.label :email %>
      <%= f.email_field :email, class:'form-control' %>
      <%= f.submit "Submit", class: "btn btn-primary" %>
  <% end %>
    </div>
</div>

I don't necessarily want/need to route to another page for example "url: add_users_path" but without that line the code breaks and won't render.

I added this to user.rb

def add_user_to_account
  update_attribute(:account_id)
end

I also created this controller

class AddUsersController < ApplicationController
    before_action :get_user,   only: [:edit, :update]

  def new
  end

  def edit
  end

  def create
    @user = User.find_by(email: params[:email])
    if @user
        @user.add_user_to_account
        flash[:info] =  "Added User to Account"
        redirect_to accounts_url
    else
        flash[:danger] = "User NOT Added"
        redirect_to accounts_url
    end
  end

  def update
    if params[:user][:account_id].empty?
      @user.errors.add(:account_id, "can't be empty")
      render 'edit'
    elsif @user.update_attributes(user_params)
      log_in @user
      flash[:success] = "Account Updated"
      redirect_to @user
    else
      render 'edit'
    end
  end

  private

    def user_params
      params.require(:user).permit(:account_id, :user_id)
    end

    def get_user
      @user = User.find_by(email: params[:email])
    end
end

Am I on the right track?  Is there a better way to do this?

UPDATE: Added schema

create_table "accounts", force: :cascade do |t|
    t.string   "name"
    t.integer  "account_manager_id"
    t.integer  "subscription_id"
    t.datetime "created_at",         null: false
    t.datetime "updated_at",         null: false
  end

create_table "users", force: :cascade do |t|
   t.string   "name"
    t.string   "password_digest",   null: false
    t.string   "remember_digest"
    t.string   "email",             null: false
    t.string   "activation_digest"
    t.boolean  "activated"
    t.datetime "activated_at"
    t.string   "reset_digest"
    t.datetime "reset_sent_at"
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
    t.boolean  "access_granted"
    t.boolean  "requested_access"
    t.string   "slug"
    t.integer  "account_id"
  end


http access to a specific folder in a full https enabled directory through .htaccess

I have enforced https access to the www directory and all subdirectories by rewrite rule in .htaccess -

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{SERVER_NAME}/%$1 [R,L]

However, I need http access to one specific folder /specific/folder/ which is under www directory. How can I do that with rewriting rule in .htaccess?


c# WPF Tree View Item conditional styling

How do you conditionally style treeviewitemson binded properties

I'm running into an issue where I want to style items in a Tree View, those that are valid selections vs hierarchy items.

I've tried to move my style tag into a TreeView.Resources and a TreeView.ItemContainerStyle tag but it still doesn't cause any formatting.

<TabItem Name="Queries" Header="Queries"
         d:DataContext="{d:DesignInstance views:QuerySettingsView}">
  <Grid>
    <TreeView ItemsSource="{Binding QueryTreeModels}"
              Width="500" Height="200" VerticalAlignment="Top"
              HorizontalAlignment="Center" Margin="0,0,175,0">
      <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
          <HierarchicalDataTemplate.ItemContainerStyle>
            <Style >
              <Setter Property="TreeViewItem.IsExpanded"
                      Value="{Binding IsExpanded, Mode=TwoWay}" />
              <Setter Property="TreeViewItem.IsSelected"
                      Value="{Binding IsSelected, Mode=TwoWay}" />
              <Style.Triggers>
                <DataTrigger Binding="{Binding IsQuery}">
                  <Setter Property="TextBlock.Foreground" Value="Chartreuse" />
               </DataTrigger>
               <DataTrigger Binding="{Binding IsFolder}">
                 <Setter Property="TextBlock.Foreground" Value="Crimson" />
               </DataTrigger>
             </Style.Triggers>
           </Style>
         </HierarchicalDataTemplate.ItemContainerStyle>
         <TextBlock Text="{Binding Name}"/>
       </HierarchicalDataTemplate>
     </TreeView.ItemTemplate>
   </TreeView>
 </Grid>
</TabItem>


Efficient way to get email name

I had a task of extracting the email name from fullname as below ( and my code to deal with it)

list_=['peter mary','peter mary david ','pop david','peter pop ronaldo bulma']
sr=pd.Series(list_,range(4))
sr_split=sr.str.split()
first_name=sr_split.str[-1]
other_name=sr_split.str[0:-1]
other_name=other_name.str.join(' ')
other_=other_name.str.split(expand=True)
other_.fillna(' ',inplace=True)
add_name=other_[0].str[0]+other_[1].str[0]+other_[2].str[0]
email_name=pd.concat([first_name,add_name],axis=1)
email_name[2]=email_name[0]+email_name[1]

My code returned:

maryp, davidpm,davidp,bulmappr

It worked as my expectation.However,there are 2 problems with my code:
  1) Use a lot of split and join
  2) Can not work with long name, say : name with 10 words

Is it a way to make it better?


Copy changed SVN Files in Jenkins to another Directory

I've asked two questions before, but none of them were answered. Thats why I try another approach of my problem.

How can I copy only the changed source files to another directory after updating my Workspace with the SVN-Plugin?


How to write data to a specific shard in Kinesis

How do I write data to a specific shard in Kinesis?

The Boto docs say

Partition keys are Unicode strings, with a maximum length limit of 256 characters for each key. An MD5 hash function is used to map partition keys to 128-bit integer values and to map associated data records to shards using the hash key ranges of the shards. You can override hashing the partition key to determine the shard by explicitly specifying a hash value using the ExplicitHashKey parameter.

However how do I actually do this?


Create a custom file extenstion in VB 2008

I have been doing a lot of searching on the web and cant seem to find a clear way of creating a custom file extentsion. I know to associate the file extension to a certain program, but how do create a format for the custom file extension?


Heroku/angular2 deploy pathlocation issue

I am trying to deploy an angular app to heroku. In angular I am using pathLocationStrategy.
After pushing the app satisfactorily, I receive 404 response at "/".
I tried
__dirname + '/../dist'
 as well as
__dirname + '/dist'
 without any success. I would be very grateful to anyone could help me unstuck.
The path is app-folder/dist/index.html

Logs from heroku:

2017-02-02T22:29:43.050820+00:00 heroku[router]: at=info method=GET
path="/" host=pure-cliffs-63499.herokuapp.com
request_id=4c1a1eb8-3cc0-45e7-8ce1-c283478811ca fwd="94.254.144.97"
dyno=web.1 connect=0ms service=20ms status=404 bytes=240

2017-02-02T22:29:43.051351+00:00 app[web.1]: Error: ENOENT: no such file
or directory, stat '/app/dist/index.html'

My server/express:

const forceSSL = function() {
  return function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
  return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
    next();
  }
}

app.use(forceSSL());
app.use(express.static(__dirname + '/dist'));
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname + '/dist/index.html'));
});

App-tree:
App-tree


Django same name multiple input insert to DB

I have multiple same name inputs. html created with jquery and json.

HTML

<input type="text" name="product_id" value="xyz" />
<p class="left">
    <label class="name">General</label>
    <input type="hidden" value="2" name="location_id">
    <input type="text" name="location_stock" placeholder="Quantity" class="text small right" value="5">
</p>
<p class="left">
    <label class="name">warehouse 1</label>
    <input type="hidden" value="5" name="location_id">
    <input class="text small right" type="text" name="location_stock" placeholder="Quantity" value="7">
</p>
<p class="left">
    <label class="name">warehouse 2</label>
    <input type="hidden" value="6" name="location_id">
    <input class="text small right" type="text" name="location_stock" placeholder="Quantity" value="8">
</p>

Json

$.getJSON(url, function(models) {
    var options = '';
    for (var i = 0; i < models.length; i++) {
        options += '<p class="left"><label class="name">' + models[i].fields['name'] + '</label></span> <input type="hidden" name="location_id" value="' + models[i].pk + '" /><input type="text" class="text small right" placeholder="Quantity" name="location_stock" /></p>'
    }
    $(".widget.stock_details").append(options);
    $("#stock_locations option:first").attr('selected', 'selected');
});

I want insert this to mysql table like this

product_id = xyz , location_id=2, stock=5
product_id = xyz , location_id=5, stock=7
product_id = xyz , location_id=6, stock=8

What is the method?

def add_new(request):
    product_id = request.POST.get('product_id')
    location_id = request.POST.get('location_id')
    stock = request.POST.get('location_stock')
    p = Products_stock(product_id=product_id,location_id=location_id,stock=stock)
    p.save()
    response_data = {}
    response_data['status'] = 'true'
    response_data['message'] = 'success'
    return HttpResponse(json.dumps(response_data), mimetype='application/javascript')


How to Compare two DataTables and Return another DataTable3 with the rows that only exist in the second DataTable?

I have two DataTables DT1 y DT2. DT1 has two rows and DT2 has three rows. In both DataTables row1 and row 2 have the same columns and values. But row3 not exist in the DT1, it will be my result.

DT1: row1, row2

DT2: row1, row2, row3

Res: DT3: row3


Spring: Error with Bean Aliasing

I got the following exception while Running my Spring Application:

Jan 09, 2015 2:47:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/amscoder/ba/common/application-context.xml]
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'agent' is defined
      at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:570)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1114)
      at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:279)
      at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
      at com.amscoder.ba.test.RobotTest.main(RobotTest.java:15)

My Spring Bean Configuration File is :"application-context.xml"

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="robot" class="com.amscoder.ba.beans.Robot">
    <property name="id" value="101" />
    <property name="name" value="Robot-1" />
</bean>

<alias name="agent" alias="robot" />

Actually i want to give multiple names to my bean.

Can anyone help me in resolve the error.


iOS 5 return to initial nib view resembling a sign out button

this if my first post so please be gentle.

I have an iOS 5 app (using storyboards) where I want the user to have the ability to sign out, and with that reset all settings in the app, and also return the user to the very first nib view.

I have already used this code:

[self.navigationController popViewControllerAnimated:YES];

and the problem with this is that it only sends the user back 1 view and not several.
The issue with this is that I have multiple table views that derive from each other and I want the Sign Out button to remain visible in every single one of these detailed views.
Also, this has to work on both iPhone and iPad (Universal)

Any suggestions?
Thanx.


How to configure SSL Certificates in Postman App for Windows 7 64 bit?

How to configure SSL Certificates in Postman App for Windows. I have installed Postman App for Windows 7 64bit. I have certificate format of P12 and PEM.  If i supply that in Postman Settings --> Certificates tab in CRT file. But, did not get the certificate by postman. what is wrong ?


Using a dash in a xpath does not work in py-dom-xpath

I'm curreny using py-dom-xpath with python 2.7.2 under Debian 4.1.1-21.

Everything works pretty well, instead of one XML element.

Whenever I try to check a XML document for a xpath like //AAA/BBB/CCC-DDD the path is not found. It's the only node with a dash - in it. I already tried to escape the dash, but that didn't work.

I also tried //*[name()='CCC-DDD'] and the starts-with and contains statement. The element is definately in the XML and the spelling is also correct.

I tried an online xpath validation site, and it works flawless there, even with the dash.

Any help is appreciated.


Angular2 - How to bind radio buttons to boolean object properties

I have a pretty simple model that looks like this:

export class Answer {

  constructor(public text: string, public isCorrect: boolean = false) {
  }

}

and I want to bind it to a radio button in such a way that if the radio button is selected, the isCorrect property is true, otherwise it is false. What is the proper way to go about this?

To be clear, I would have an array of Answers, and each Answer would have a single radio button.

Plnkr Example

My template so far looks like this:

<label *ngFor="let answer of answers">
  <input #rad type="radio" name="answer-{{questionIndex}}" [(ngModel)]="answer.isCorrect" [value]="rad.checked">
  {{answer.text}}
</label>


How do I force-delete a file on my computer?

I am using Mac OS X El Capitan Public Beta 2.

There is somehow a permission problem with my Desktop (and only this directory) because I can not delete any file.

The classic delete to bin does not work, even though I am prompted a window asking for my password and permission. (I am the administrator).

I also tried a few command lines like sudo rm - R *file* and it tells me that the operation is not permitted even after I enter my password.

Going without the rootless feature of El Capitan did not help either :

sudo nvram boot-args="rootless=0"
sudo reboot

Should I change the permissions of the Desktop directory? If so what are the original ones?

Thank you!


Javascript loading an image on hover over a link

i am new to java script and i am designing my web site but i want to load a new image on a particular place of my web page when a user hover over the home,here is the code.

        <html>
        <head>
        </head>
        <body>
        <img src="yourImage.jpg" alt="Home" id="image1" onmouseover="image1.src='home.jpg';" onmouseout="image1.src='myImage.jpg';" /> <br />
        <a href="#" onmouseover=image1.src='home.jpg';" onmouseout="image1.src='yourImage.jpg';">Hoover Me!</a>
        </body>
        </html>

This code is not working.Please Help me to find out the error in code.


Factory returning same value

I am trying to get songs from soundcloud, I am using some input to set value and send it to my factory to get all the related list of songs and display it.
The issue is the the first time all works correctly, but when I am trying to input new values I am getting same results as first time.

My code looks like:

.controller('DashCtrl', function ($scope, SongsService) {
        $scope.formData = {};
        $scope.searchSong = function () {
            SongsService.setData($scope.formData.songName);
        };

UPDATE

the factory :

.factory('SongsService', function ($rootScope) {
        var List = {};
        List.setData = function (tracks) {

            var page_size = 6;
            SC.get('/tracks', {limit: page_size, linked_partitioning: 1}, function (tracks) {
                // page through results, 100 at a time
                List = tracks;
                $rootScope.$broadcast('event:ItemsReceived');
            });
        };
        List.getItems = function () {
            return List;
        };
        return List;
    }).value('version', '0.1');

Thanks for help!


Sort by group in a table that join with another

I have 2 tables, where one is lookup table while the other is a transaction log.

Lookup table User: UserId, Name and Department.
Transaction log table EntryLog:  LogID, UserId, TimeIn, TimeOut

I am trying to retrieve a report to view the last seen time (TimeIn or TimeOut) of ALL the User (which is unique) in the User table.

I tried the follow query but doesn't seen to work:

SELECT DISTINCT (A.UserID), TimeIn, TimeOut, B.Name, B.Department FROM EntryLog A
  INNER JOIN User B ON B.UserId = A.UserId
  ORDER BY TimeOut DESC, TimeIn DESC

Somehow the result seem to retrieve all the records from the transaction Log (including repeated UserId). I am not good in SQL statement and being searching for similar issue without avail.
Any advise is much appreciated. Thank You in advance.


API Key Error in Facebook Connect (javascript sdk)

I am trying to implement Facebook Connect on a website. I am trying to work with Javascript SDK of Facebok. I am new to it and unfortunately most of links provided in Facebook WIKI are out of date... Returning 404 not found. Anyway I added this code before the ending </body>:

<script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script>
 <div id="fb-root"></div>
 <script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"> </script>
 <script src="http://connect.facebook.net/en_US/all.js"></script>
 <script>
   FB.init({
     appId  : '12344', // my real app id is here
     status : true, // check login status
     cookie : true, // enable cookies to allow the server to access the session
     xfbml  : false  // parse XFBML
   });

   FB.login(function(response) {
  if (response.session) {
    if (response.perms) {
        alert('user is logged in and granted some permissions');
      // user is logged in and granted some permissions.
      // perms is a comma separated list of granted permissions
    } else {
        alert('user is logged in, but did not grant any permissions');
      // user is logged in, but did not grant any permissions
    }
  } else {
        alert('user is not logged in');
    // user is not logged in
  }
}, {perms:'email'});
 </script>

And I have a login button at some other place (much before the above scripts) in the same page rendered with:

<fb:login-button v="2">Connect with Facebook</fb:login-button>

This button renders as a normal fb connect button and clicking it opens a new popup window as it normally should. Problem is that it shows 'invalid api key specified' error. On inspecting address bar of popup, I see that api_key=undefined is passed to it :(

Any idea about this? I am trying to fix this for last 5 hours now... Please help me found out why correct API key is not being passed to popup window.

Thanks in advance.


Strange way of printing Binary Search Tree C++ with pointers

I was going through a lecture and it showed some code that prints out a binary search tree recursively like this

void printTree(node *t){
    if(t!=NULL){
        printTree(t->left);
        cout<<t->key<<endl;
        printTree(t->right);
     }
 }

I understand what it is doing but I don't understand the pointers.  The function is passing a pointer to a node yet in the 'cout' line, it is trying to access the key value in the node struct without dereferencing it first.  What I mean is, shouldn't it be something like

cout<<(*t)->key<<endl;

instead?


DATETIME plus Minutes from table

How do you add minutes to a DATETIME field?

08/12/2013 11:00:00 PM + 120 minutes


EF getting the current ObjectContext

I need to get the current context given an entity

I found this old article from 2009

http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx

given that we're now firmly in 2012, is there another way ?

UPDATE - here are some details on where this is reqd

Table1 - at the heart of the star shaped schema
      Tags nvarchar(300)
      Idx identity int

Table2 - Tags reference
      TagID identity int
      TagText nvarchar(50)

Table3 - Rel between Table1 & Table2
     IDX FK
     TagID FK

In the Context.SavingChanges() event for Table1
    the tags are parsed and saved to Table2 with the relationships added to Table3 using context from Table1

Any guidance on how to improve this are welcome


Prevent UIs interaction in Sparkle

I am trying to use Sparkle to update an app (not the current app). I start with something simple which is creating the updater object:

var updater = SUUpdater(forBundle: appBundle)

The problem I'm having is that that line of code can open UI dialogs if something go wrong. For example:

I can solve that problem, but my concern is that this code is running on a screensaver and popping a dialog like that blocks it to the point where a hard reboot is the only way to move forward.

Is there a way to prevent Sparkle from ever opening any kind of UI?


Newbe: ajax form not working

I'm new in ajax/js/php.
I have a small contact form

<form id="contact-form" method="post" action="process.php" role="form">
    <div class="messages"></div>
    <div class="form-group">
        <label for="form_name">First name *</label>
        <input id="form_firstname" type="text" name="name" class="form-control" placeholder="Please enter your first name *" required="required" data-error="Firstname is required.">
        <div class="help-block with-errors"></div>
    </div>
    <div class="form-group">
        <label for="form_lastname">Last name *</label>
        <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your last name *" required="required" data-error="Lastname is required.">
        <div class="help-block with-errors"></div>
    </div>
    <div class="form-group">
        <label for="form_email">Email *</label>
        <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *" required="required" data-error="Valid email is required.">
        <div class="help-block with-errors"></div>
    </div>
    <div class="form-group">
        <label for="form_phone">Phone</label>
        <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
        <div class="help-block with-errors"></div>
    </div>
    <p><strong>*</strong> These fields are required.</p>
</form>
<button type="submit" class="btn btn-info" value="Create Account">Create Account</button>

with small js and php

script.js

$("#contact-form").submit(function(event) {
    // cancels the form submission
    "use strict";
    event.preventDefault();
    submitForm();
});

function submitForm() {
    // Initiate Variables With Form Content
    "use strict";
    var firstname = $("#form_firstname").val();
    var lastname = $("#form_lastname").val();
    var email = $("#email").val();
    var phone = $("#phone").val();

    $.ajax({
        type: "POST",
        url: "process.php",
        data: "name=" + firstname + lastname + "&email=" + email + "&phone=" + phone,
    });
}

process.php

<?php
    $name = $_POST["name"];
    $email = $_POST["email"];
    $phone = $_POST["phone"];

    $EmailTo = "name@email.com";
    $Subject = "New Message Received";

    // prepare email body text
    $Body .= "Name: ";
    $Body .= $name;
    $Body .= "\n";

    $Body .= "Email: ";
    $Body .= $email;
    $Body .= "\n";

    $Body .= "Phone: ";
    $Body .= $phone;
    $Body .= "\n";

    // send email
    $success = mail($EmailTo, $Subject, $Body, "From:".$email);

    // redirect to success page
    if ($success){
        echo "success";
    } else {
        echo "invalid";
    }
?>

for some reason it's not working on way I would like to, not sending me emails (i know to put my email in $Emailto).
Often I was using only php form but I would like to avoid reloading page. I try to understand where I'm making error.


Write Opus Data to playable Opus File (Java)

I'm trying to write opus audio packets from a stream to a file using Java so that the file can be successfuly played (via VLC or what have you). I'm currently using the VorbisJava library to no available. Currently, I buffer all the received audio packets and then write the file once I know I am not going to receive any more audio. Here is my sample code so far:

    public static void writeWithLibrary(List<OpusAudioData> opusAudioData, OutputStream outputStream)
{
    OpusInfo opusInfo = new OpusInfo();
    opusInfo.setNumChannels(1);
    opusInfo.setOutputGain(0);
    opusInfo.setPreSkip(0);
    opusInfo.setSampleRate(48000);

    OpusTags opusTags = new OpusTags();

    OpusFile opusFile = new OpusFile(outputStream,opusInfo,opusTags);

    for (OpusAudioData o : opusAudioData)
    {
        opusFile.writeAudioData(o);
    }

    try
    {
        opusFile.close();
    }
    catch (IOException e)
    {
        logger.error("OpusFileWriter -- Could not write data to OpusFile, aborting");
    }

}

Any help would be  appreciated. Am I overlooking something here?


cron jobs dow and mon exception

Today 2017-25-09 and monday and I have seen a entry cron job in syslog. My crontab:

# m  h  dom mon dow   user    command
  30 05 18  9   1     root    /bin/bash [--job route--]

If today is 25th, why cron start job with dom to 18 ?


Can a SHOW FIELDS query use ORDER BY?

The docs don't mention ORDER BY and I have had no luck phrasing this query:

SHOW FIELDS FROM `TB_Main`  WHERE Type = 'mediumtext' OR Type = 'bit(1)' ORDER BY Field;

Do I have to do my ordering in my scripting?


How to use custom UserProvider or maybe it must be AuthenticatedProvider?

I need to request user info from URFAClient (NetUP UTM5 billing system), but custom UserProvider's docs says that i need load user bu username without password.

I can't do this, because all request to URFAClient must contain both username and password, i can't load userinfo without password.

I totally confiused about how to add my very custom UserProvider, and docs says nothing about what i need.

Any suggestion?


How to find duplicate files with same name but in different case that exist in same directory in Linux?

How can I return a list of files that are named duplicates i.e. have same name but in different case that exist in the same directory?

I don't care about the contents of the files. I just need to know the location and name of any files that have a duplicate of the same name.

Example duplicates:

/www/images/taxi.jpg
/www/images/Taxi.jpg

Ideally I need to search all files recursively from a base directory. In above example it was /www/


Difference between $window.location.reload() and $route.reload() in angularjs

What is the difference between $window.location.reload() and $route.reload() in Angular.js?

I have used these two things, but both are working same progress.

Can anyone explain the differences?


SqlCommand ExecuteNonQuery throws OutOfMemoryException

I have problem with executing Sql that in fact is simple call of stored procedure on SqlServer.

Consider below Sql Stored Procedure:

    CREATE PROCEDURE InfiniteLoop
    AS
    BEGIN
        DECLARE @ixi NUMERIC(38) = 0
        DECLARE @i NUMERIC(38) = 0
        WHILE 1 = 1
        BEGIN
           SET @i = @i + 1
           SET @ixi = @ixi * @i
           PRINT N'some text'
        END
    END;

Now I'am calling this procedure from C# in this manner:

public void CallProcedure()
{
   SqlCommand cmd = this._connection.CreateCommand();
   cmd.CommandType = CommandType.StoredProcedure;
   command.CommandText = 'InfiniteLoop';

   //Line below throws OutOfMemoryException
   cmd.ExecuteNonQuery();

   cmd.Dispose();
}

Memory starts growing realy fast. After few seconds exception is thrown.
Normaly all this code is using 'try/catch' and 'using' sections, but I have simplified this snippet to show that problem comes from SqlClient library not from my code directly.


How to search a column in sqlite by a string

I would like to return a true / false value when the string match with the column of sqlite. How can I implement the search function?

How to use cursor to do searching?

public boolean searchLuggage(String code) {

 ArrayList<String> luggageCheck = new ArrayList<String>();
 SQLiteDatabase db = this.getReadableDatabase();

 try {
     Cursor cursor = db.query(true, TABLE_LUGGAGES, new String[] { your field list }, SearchColumnname + "='" + code + "'", null, null, null, null, null);

     if (cursor != null) {
         cursor.moveToFirst();
         for (int i = 0; i < cursor.getCount(); i++) {
            luggageCheck.add(cursor.getString(0));
            cursor.moveToNext();
         }
         cursor.close();
         return true;
     }
     return false;
} catch (Exception e) {
    e.printStackTrace();
}
   return true;
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_LUGGAGE_TABLE = "CREATE TABLE " + TABLE_LUGGAGES + "(" + KEY_NAME + " TEXT NOT NULL," + KEY_CODE + " TEXT NOT NULL," + KEY_NUMBER + " TEXT NOT NULL );";
    db.execSQL(CREATE_LUGGAGE_TABLE);
}


Delete engine for deeply nested linked structure

The background is the question at Nested shared_ptr destruction causes stack overflow. To summarize, for a data structure that looks like:

// A node in a singly linked list.
struct Node {
    int head;
    std::shared_ptr<Node> tail;
};

If the list grows too long, a stack overflow might occur in the destructor of Node due to recursive destructions of the shared_ptrs. I'm implementing a thread-safe version of the delete engine proposed in https://stackoverflow.com/a/36635668/3234803.

There are three simple classes involved: SpinLock, ConcurrentQueue, and DeleteEngine.

The SpinLock class implements the C++ Lockable interface with a std::atomic_flag:

class SpinLock {
public:
    void lock()
    { while (lock_.test_and_set(std::memory_order_acquire) {} }

    bool try_lock() // Not camel-case to be compatible with C++ Lockable interface
    { return !lock_.test_and_set(std::memory_order_acquire); }

    void unlock()
    { lock_.clear(std::memory_order_release); }

private:
    std::atomic_flag lock_ = ATOMIC_FLAG_INIT;
};

The ConcurrentQueue class implements a multiple-producer-single-consumer queue that supports thread-safe enqueue and tryDequeue:

template<typename T>
class ConcurrentQueue {
public:
    void enqueue(T item)
    {
        std::lock_guard<SpinLock> lk(lock_);
        queue_.emplace_back(std::move(item));
    }

    bool tryDequeue(T &item)
    {
        std::lock_guard<SpinLock> lk(lock_);
        if (queue_.empty()) {
            return false;
        }
        item = std::move(queue_.front());
        queue_.pop_front();
        return true;
    }

private:
    std::deque<T> queue_;
    SpinLock lock_;
};

The DeleteEngine class implements the delete engine proposed in the answer aforementioned:

template<typename T>
class DeleteEngine {
public:
    ~DeleteEngine()
    {
        std::lock_guard<SpinLock> lk(deleting_);
        deleteAll();
    }

    void enqueue(T *p)
    {
        queue_.enqueue(p);
        if (deleting_.try_lock()) {
            std::lock_guard<SpinLock> lk(deleting_, std::adopt_lock);
            deleteAll();
        }
    }

private:
    void deleteAll()
    {
        T *p = nullptr;
        while (queue_.tryDequeue(p)) {
            delete p;
        }
    }

    ConcurrentQueue<T *> queue_;
    SpinLock deleting_;
};

Now in the deleter of a shared_ptr<Node>, we will hand the raw pointer to a DeleteEngine<Node> instead of directly deleteing it. A recursive delete can handle up to about 10000 nodes, while this method can handle an arbitrarily large number of nodes.

The above code is only a prototype, but I'm particularly concerned about the performance of this implementation: (1) Most of the time the Node class would be used in a single-threaded environment; (2) Occasionally it might be used in highly concurrent applications, e.g. a web server that constantly creates and destroys objects.

This implementation is significantly slower than a naive recursive destruction (micro-benchmark with 64 threads and 10000 nodes per thread shows about 10 times slowdown). What can I do to improve it?


Moving two div elements at once

Not sure if I'm being too clear with the title. Sorry, it's late and I don't think I have a cleared mind.

Anyway what I want this to do is..

When the div(manager) is clicked, the div(managerp) appears.

The div(manager) moves to the area the same time managerp moves there. Almost as though they move as one div element.

On the next click managerp Fades out, and manager moves back to its original position.

I'm able to do all of that, but it won't return to it's original position. I am a novice when it comes to jQuery, so this is where I ask for your help.

EDIT: The div manager doesn't seem to return to the old position. I've tried editing the css through jQuery to get it to, but it doesn't seem to work.

HTML :

    <div id="manager">
        <span>&raquo;</span>
</div>
<div id="managerp" style="">

</div>

No, I can't put managerp within manager, it doesn't seem to position itself as good as it should.

jQuery :

            $(document).ready(function() {
            $("#manager").click(function() {
                $("#manager").css({'margin-left' : '270px', 'border-left' : '0'});
                $("#managerp").toggle("slow", function() {
                    if ($("#managerp").is(':visible'))
                        $("span").html("&laquo;");
                    else
                        $("span").html("&raquo;");
                });
            });
        });

This should help you get the picture of what it's supposed to look like. (Sorry if I am giving way too much information)

Thank you for your help. If you need me to be more specific as to what it should be doing, just ask.


GORM not bootstrapping from JAR

Replacing a persistence layer in legacy app with a JAR file using Spring, Hibernate and GORM.  Methods like person.save() work fine when running agains project with Gradle etc. in project.  However, after I build the fat jar and reference it with -cp my-big-fat-gorm.jar I get:

java.lang.IllegalStateException: Method on class [blah.Person] was
  used outside of a Grails application. If running in the context of a
  test using the mocking API or bootstrap Grails correctly.

Using Spring boot for Spring, Hibernate4 and GORM and build.gradle file show below...

apply plugin: 'java'
apply plugin: 'groovy'
apply plugin: 'application'

mainClassName = "blah.App"

jar {
    baseName = 'blah-gorm'
    version =  '1.0-SNAPSHOT'
    from {
        configurations.compile.collect {
            it.isDirectory() ? it : zipTree(it)
        }
        configurations.runtime.collect {
            it.isDirectory() ? it : zipTree(it)
        }
    }
}

repositories {
    mavenLocal()
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.8.2'
    compile 'org.grails:gorm-hibernate4-spring-boot:1.1.0.RELEASE'
    compile 'org.slf4j:slf4j-simple:1.7.7'
    runtime 'com.h2database:h2:1.4.181'
}

Am I missing something in the JAR file creation that causes Spring boot to honor @Entity etc.?

Here is a GitHub project that illustrates this and should allow you to execute and see the same stuff I'm seeing.

https://github.com/twcrone/spring-gorm-jar


I defined a function such as:

def ucos(a):
    temp=[umath.cos(i) for i in a]
    return unumpy.uarray([unumpy.nominal_values(i) for i in temp], [unumpy.std_devs(i) for i in temp])

But when I try to iterate over it with a for loop:

for j in range(len(Beta)):
    if Beta[j]<pi/2.:
       Radius.append((Diam_meas[j]/2.)*(ucos((pi/2)-Beta[j]))**(-1)*10**(-9))
    else:
       Radius.append((Diam_meas[j]/2.)*10**(-9))

it gives me the error:

TypeError: 'AffineScalarFunc' object is not iterable

Do you have any idea on why ucos function is not iterable? How to make it iterable?
thx!


What framework of Android can be used to connect PC to Android and Android to other PC?

I have this scenario. Where i am writing one apps in Android usging bash/python. So that via PC i can connect to the Android and from Android using USB i can connect the destination PC/Server.

But what API is available to send all my Android requests to USB, so that i can remotely have assistance for the Server PC via Android? Is there any other available open-source framework for doing such?

or

Follow up:

There is already "Tethering and portable hotspot" option in my mobile. Without installing any third party apps.

So once i enabled it, i have new interface called usb0 with ip address in the same subnet of Android + Laptop.

Then i installed simply SSHDroid server in Android, now from 3G i can connect to the Android. Now PC and Android both has usb0 interface with same subnet for sharing data that solves all the remote access problem.

On my laptop:

$ ip addr

    2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
        link/ether d4:be:d9:55:91:4a brd ff:ff:ff:ff:ff:ff
        inet 192.168.0.219/24 brd 192.168.0.255 scope global eth0
        inet6 fe80::d6be:d9ff:fe55:914a/64 scope link
           valid_lft forever preferred_lft forever

    7: usb0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UNKNOWN qlen 1000
        link/ether c6:8a:95:bf:fa:2b brd ff:ff:ff:ff:ff:ff
        inet 192.168.42.202/24 brd 192.168.42.255 scope global usb0
        inet6 fe80::c48a:95ff:febf:fa2b/64 scope link
           valid_lft forever preferred_lft forever

On my Android mobile:

/data/data/berserker.android.apps.sshdroid/home # ip addr

11: usb0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 6e:54:53:29:68:8c brd ff:ff:ff:ff:ff:ff
    inet 192.168.42.129/24 brd 192.168.42.255 scope global usb0
    inet6 fe80::6c54:53ff:fe29:688c/64 scope link
       valid_lft forever preferred_lft forever

15: wlan0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 50:01:bb:e3:fb:d7 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.163/24 brd 192.168.0.255 scope global wlan0
    inet6 fe80::5201:bbff:fee3:fbd7/64 scope link
       valid_lft forever preferred_lft forever


PHP RIGHT JOIN query not considering null?

When I run the query it returns all the correct values except it doesn't return any values where a.Correct = null (i.e a quiz question hasn't been answered at all), but it does return values for a.Correct = 0.

 /***Configure the retest***/
    public function CreateRetest($topicID) {
    $retestData = array();
    $count = 0;

    $createSQL = "SELECT q.QuestionID,q.Question,q.Answer,q.TopicID From quizanswered a RIGHT JOIN question q ON a.QuestionID = q.QuestionID where (a.Correct=null OR a.Correct = 0) AND q.TopicID = '$topicID'";
    $create = mysqli_query($this->db,$createSQL) or die(mysqli_connect_errno()."Cannot create tables");
    while($row = mysqli_fetch_array($create)){
    $rQuestionID = $row['QuestionID'];
    $rQuestion = $row['Question'];
    $rAnswer = $row['Answer'];
    $retestData[$count] = array($rQuestionID,$rQuestion,$rAnswer);
    $count +=1;
    }
    return $retestData;

 }


Using malloc and free in C/C++ and getting error HEAP CORRUPTION DETECTED

I am having a problem when free(position) is run.

void printTree(nodeT node, int hieght)
{
    int *position;
    position = (int*)malloc(hieght * sizeof(int*));
    for (int i = 0; i <= hieght; i++)
    {
        position[i] = 0;
    }
    BOOLEAN DONE = FALSE;
    while (DONE == FALSE)
    {
        printMoveDown(&node, position);
        printLEAFNode(&node, position);
        DONE = printMoveUp(&node, position);
        printSingleKey(&node, position);
    }
    free(position);
    position = NULL;
}

The full error message I get from VS2010 is HEAP CORRUPTION DETECTED: after normal block (#64) at 0x00031390. CRT detected that the application wrote to memory after end of heap.

The debugger says the problem occurs while at in: dbgheap.c

extern "C" void __cdecl _free_dbg_nolock
line 1376:  if (!CheckBytes(pbData(pHead) + pHead->nDataSize, _bNoMansLandFill, nNoMansLandSize))
                if (pHead->szFileName) {..}
                else { this is where the program stops }

I tried setting up the same situation with less stuff going on to see if I could narrow the problem down.

void function (int y)
{
    int *x;
    x = (int*)malloc(y * sizeof(int*));
    free(x);
    x = NULL;
}

This is the same thing as above without the for loop and while loop. This works. Removing the for loop is what made it work. I don't know why. I looked up what the CRT was but it was all pretty new concepts to me and I assume that I can solve this problem without knowing about these CRTs.

The for loop assigns values to the memory allocated for position, beyond that I can't think of why this causes a problem.... actually now that I think about it. I changed the loop to be height + 1 which fixed the problem.


Deque Implementation

I have question regarding the code I found on Internet which uses a deque for finding the max of the element --

 #include <iostream>
 #include <deque>

 using namespace std;

 void test(int arr[], int n)
 {
   std::deque<int>  Qi(n);
   int i;
   for (i = 0; i < n; ++i)
   {
      while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
        Qi.pop_back();  // Remove from rear

      Qi.push_back(i);
   }
  cout << arr[Qi.front()];
}

// Driver program to test above functions
int main()
{
   int arr[] = {12, 1, 78, 90, 57, 89, 56};
   int n = sizeof(arr)/sizeof(arr[0]);
   test(arr, n);
   return 0;
}

My Question is how is Qi.front() giving the right index when I have not done any Qi.push_front() ?

But the following code gives me a 0

  void test(int arr[], int n)
 {
   std::deque<int>  Qi(n);
   int i;
   for (i = 0; i < n; ++i)
   {
      Qi.push_back(i);
   }
   cout << arr[Qi.front()];
}

Sorry If I am sounding stupid .. New to deques ...

Thanks


Regex to remove p tags within li tags and td tags

I have this html content:

<p>This is a paragraph:</p>
<ul>
<li>
<p>point 1</p>
</li>
<li>
<p>point 2</p>
<ul>
<li>
<p>point 3</p>
</li>
<li>
<p>point 4</p>
</li>
</ul>
</li>
<li>
<p>point 5</p>
</li>
</ul>
<ul>
<li>
<p><strong>sub-head : </strong>This is a para followed by heading, This is a para followed by heading, This is a para followed by heading, This is a para followed by heading</p>
</li>
<li>
<p><strong>sub-head 2: </strong></p>
<p>This is a para followed by heading, This is a para followed by heading, This is a para followed by heading, This is a para followed by heading</p>
</li>
</ul>

I want to remove all the <p>&</p> tags between <li>&</li> irrespective of its position between <li>&</li>. similarly i need to remove p tags between td tags inside a table.

This is my controller code so far:

nogo={"<li>\n<p>" =>'<li>', "</p>\n</li>" => '</li>', "<td>\n<p>" => '<td>', "</p>\n</td>" => '</td>',
  '<p> </p>' => '','<ul>' => "\n<ul>",'</ul>' => "</ul>\n", '</ol>' => "</ol>\n"   ,
  '<table>' => "\n<table width='100%' border='0' cellspacing='0' cellpadding='0' class='table table-curved'>",
 '&lt;' => '<', '&gt;'=>'>','<br>' => '','<p></p>' => '', ' rel="nofollow"' => ''

c=params[:content]
       bundle_out=Sanitize.fragment(c,Sanitize::Config.merge(Sanitize::Config::BASIC,
       :elements=> Sanitize::Config::BASIC[:elements]+['table', 'tbody', 'tr', 'td', 'h1', 'h2', 'h3'],
       :attributes=>{'a' => ['href']}) )#.split(" ").join(" ")

      re = Regexp.new(nogo.keys.map { |x| Regexp.escape(x) }.join('|'))

      @bundle_out=bundle_out.gsub(re, nogo)

im passing the above html content to this code through params[:content] which ive assigned to a variable c.

Following is the o/p which is not as expected. Some close p tags and open p tags are still between li and close li tags

<p>This is a paragraph:</p>

<ul>
<li>point 1</li>
<li>point 2</p>
<ul>
<li>point 3</li>
<li>point 4</li>
</ul>
</li>
<li>point 5</li>
</ul>

<ul>
<li><strong>sub-head : </strong>This is a para followed by heading, This is a para followed by heading, This is a para followed by heading, This is a para followed by heading</li>
<li><strong>sub-head 2: </strong></p>
<p>This is a para followed by heading, This is a para followed by heading, This is a para followed by heading, This is a para followed by heading</li>
</ul>

My aim is simple i just want to remove all the p tags inside li and td tags, which im not able to do correctly. Any help is appreciated.

I would like to use regex to do this. and i know using regex is not the correct way to parse html content.


Forcing a PI scan for teradata table

I have a table (say T1) which has a PI defined on column c1, c2 and c3.

In one query, the need is to have filter only on c1, and for a given unknown reason, I cant create a secondary index on the column c1.

I tried writing a query like this -

select *
from T1
where C1 = <some Value>
and c2 = c2
and c3 = c3

given that conditions for c2 and c3 are tautologies, the result set will not be impacted. However, I am "expecting" to fool Teradata into invoking the PI for this query, which does not happen.

any explanation ?


How can I set a severity level per log source with Boost log?

I am new to Boost Log, and having troubles doing some pretty simple stuff.
I'm trying to create a logger and assign a level to it (such as Warning, Info, Trace, etc.), and filter out(for performance reasons) any logs sent to this logger with a lower level of that assigned to the logger, at the Logging core level, rather than at the sink level.
For example (pseudo code):

logger lg;
lg.setLevel(Warn);
BOOST_LOG_TRIVIAL(trace) << "A trace severity message"; // Will be filtered
BOOST_LOG_TRIVIAL(warn) << "A warning severity message"; // Won't be filtered

I'm pretty sure this can be achieved with Boost Log, but for some reason I was not able to do this.

Thanks,

Omer.


Creating an array with an unknown size?

If I have

class example {
int x;
int data[] = new int[x]
}

If I wanted to create a new method that creates a new array whose size is one greater than data's length how would I proceed? I don't understand how I can create a new array when I don't know the initial length and adding one to that?


Is there a URI scheme for opening a QR code app?

I have a project that requires the browser to open a qr code reader app from a link. Is that possible? I know URI schemes are useful for this kind of situation, but I don't know where to look.


How to install Android SDK with offline files on macOS?

In China I cannot access https://dl.google.com with speedy connection so I use mirror site to download a bunch of installation files including 3534162-studio.sdk-patcher.zip.bak which is patch v4. You can't simply unzip this file and place it under ~/Library/Android/sdk/patcher/v4 to install (patcher.jar and source.properties). So is Intel HAXM (haxm-macosx_r6_2_1), installing the pkg file inside will not actually trigger the process to complete. Unlike linux, there is no temp file under sdk, so I wonder where the temp folder go (that I can put these downloaded files to it to complete the installation process).


Automate first time password reset using powershell

I am creating a VM on the fly with powershell (on ESX with Windows Server 2012 R2). I have most of the automation pieces in place, but when it comes to resetting the Administrator password the first time we login to the VM after provisioning (as a part of windows security policy), I am having a hard time.

I have tried stuff like the following (which didn't work):

[ADSI]$vmAccount="WinNT://$vmName/$vmUserName"
$vmAccount.ChangePassword($current, $new)

It fails by saying:

Exception calling "ChangePassword" with "2" argument(s):
"The specified network password is not correct.

Any help in pointing me in the right direction is much appreciated.


How to Insert long html, images and long String in Oracle (long data) as a Single Column?

I want to insert a long data into one column, that data containing html, images binary data and string. What data type need to use to insert the data into column [ big data].
I am written a query to insert into oracle database but at the time of insertion Oracle says
ORA-01704: string literal too long. I am inserting more than 1mb data into DB ( combination of text,html and binarydata). Any suggestions with example please.


cant add ImageView in a subclass

I can add an ImageView programatically from the main class. But I can't do it from a subclass.
When I try ImageView iv = new ImageView(this) I am getting an error
ImageView (android.content.Contex) in ImageView can not be applied to (...MainActivity.MySubclass)

Code:

public class MainActivity extends Activity {
...
class MySubclass
{
    ImageView iv;
    MySubclass(View v) // create an object from onClick method
    {
        iv = new ImageView(this);
    }
} // end of subclass

} // end of main


Eclipse C++ Warnings

I've recently formatted my computer and re-installed Ubuntu and Eclipse.
Afterwards, when I opened a C++ project that was both warning and error free, Eclipse now shows me some warnings I've never seen before, such as:

Macro definition can be replaced with constexpr expression

and

Un- or ill-initialized variable found

Screenshot:

What do these warnings mean and why are they listed? They weren't there before I re-installed Ubuntu and Eclipse...

Thanks!


Python Tornado file upload gives KeyError

I'm trying to write a very simple python script based on tornado web server to upload a file. But I'm getting 'KeyError' though the key is in the html form is OK.

Here is the python code just to see the uploaded file name.

import tornado.ioloop
import tornado.web

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Bismillahir Rahmanir Raheem")
        self.render('form.html')

class UploadHandler(tornado.web.RequestHandler):
    def post(self):
        self.write("Alhamdulillah, here")
        if  self.request.files is not None:
            self.write("Inside the if")
            uploadFile = self.request.files['my_file'][0]
            self.write(uploadFile['filename'])

def make_app():
    return tornado.web.Application([
      (r"/", IndexHandler),
      (r"/upload", UploadHandler)
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

And the html form is as below:

<html>
    <head>
        <title>Testing file upload</title>
    </head>
    <body>
        <h1>Testing file upload</h1>
        <form enctype="multipart/formdata" method="post" action="/upload">
            <input type="file" name="my_file"/>
            <input type="Submit" name="upload" value="Upload"/>
        </form>
    </body>
</html>

But each time I select a file and press Upload button I get the

500: Internal Server Error

And at the PyCharm editor I get the following error:
    File "C:/Users/Mushfique/Desktop/file-upload/upload.py", line 14, in post
    uploadFile = self.request.files['my_file'][0]

KeyError: 'my_file' ERROR:tornado.access:500 POST /upload (::1) 1.00ms

Though in the html form I've used 'my_file' as the file input field name.


Is my implementation of multi-threading okay?

I built an application class that should be runnable as a Thread and it would be nice to hear opinions of Java developers to improve my coding style.

Main class.

package com.ozankurt;

public class Main {

    public static void main(String[] args) {

        Application application = new Application();

        application.start();

    }
}

Application class:

package com.ozankurt;

import com.ozankurt.utilities.Input;

public class Application implements Runnable {

    private CommandHandler commandHandler;

    private boolean running;

    private volatile Thread thread;
    private String threadName = "ApplicationThread";

    public Application() {

        Handler handler = new Handler(this);

        this.commandHandler = new CommandHandler(handler);

        this.running = true;
    }

    public void start() {

        if (thread != null) {
            System.out.println(threadName + "is already running.");

            if (!isRunning())
            {
                System.out.println("Resuming " + threadName + "...");
                setRunning(true);
            }
        } else {
            System.out.println("Starting " + threadName + "...");

            thread = new Thread(this, threadName);
            thread.start();

            System.out.println("Started " + threadName + ".");
        }
    }

    public void stop() {
        System.out.println("Halting " + threadName + "...");

        setRunning(false);

        System.out.println("Halted " + threadName + ".");
    }

    @Override
    public void run() {

        while (isRunning()) {
            String userInput = Input.readLine();

            commandHandler.handle(userInput);
        }
    }

    public boolean isRunning() {

        return running;
    }

    public void setRunning(boolean running) {

        this.running = running;
    }
}

I read this Java documentation about how to stop threads in Java without using stop method that has become deprecated because it might throw some exceptions.

As far as I understand we shouldn't try to stop a thread and instead we should define a property corresponding to the state of the thread.

In my case I defined a boolean running in my Application class and as you can read from my code in the run method I basicly check if the application is running. Which mean that I actually never stop the thread, I only remove its functionality by using a while statement. Is this the correct approach explained in the Java documentation?


User Identity in ASP.Net modelling

I have a table with Listings and I want users to be able to mark their favourite listings. To do that I would have a new table with User ID and Listing Id data. Users should be only able to see their favourite listings.

I am using ASP.NET default authentication. The way to get the User Id would be

User.Identity.Name;

??

Is that the userId I should store? Is that the common approach?


Display strongly typed binded data dataSource in webForm Grid

I am working in ASP.NET 3.5 and I am trying to display data in a grid. I have a model class and data is stored as a strongly typed list. I have a Repeater control to show all the data but for reason is not working in the grid

Model class

 public class RolesModel
{
    public RolesModel() { }

    public long RoleID { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public DateTime CreatedDate { get; set; }
}

aspx.cs class

protected void Page_Load(object sender, EventArgs e)
    {

        if(!Page.IsPostBack)
        {
            List<RolesModel> roleList = new List<RolesModel>();

            roleList = RoleDefinationRelay.GetAllRoles(null);

            rptRoles.DataSource = roleList;
            rptRoles.DataBind();
        }

    }

ASP:Repeater (is working!)

  <asp:Repeater ID="rptRoles" runat="server">
                     <HeaderTemplate>
                         <table class="tableStyle1">
                             <tr>
                               <td>Role ID</td>
                               <td>Title</td>
                               <td>Description</td>
                               <td>Created Date</td>
                           </tr>

                     </HeaderTemplate>
                     <ItemTemplate>
                         <tr>
                                <td><%#Eval("RoleID")%></td>
                                <td><%#Eval("Title")%></td>
                                <td><%#Eval("Description")%></td>
                                <td><%#Eval("CreatedDate")%></td>
                         </tr>
                     </ItemTemplate>
                     <FooterTemplate>
                         </table>
                     </FooterTemplate>
                 </asp:Repeater>

Need to make Grid work here but is not working

  <cc0:Grid ID="ItemList" runat="server" FolderStyle="~/Styles/Grid" AutoGenerateColumns="true"
                Width="100%" PageSizeOptions="5,10,20,50,100,-1" AllowFiltering="true" FilterType="ProgrammaticOnly"
                AllowAddingRecords="false" DataSourceID="rptRoles">
        <Columns>
              <cc0:Column DataField="RoleID" HeaderText="Role ID" Visible="true" />
             <cc0:Column DataField="Title" HeaderText="Title" Width="150" />
             <cc0:Column DataField="Description" HeaderText="Description" />
             <cc0:Column DataField="CreatedDate" HeaderText="Created Date" Width="150" />
         </Columns>
 </cc0:Grid>


Get rows data from base with php

Here I have an dataRange loop, but for this case its not important, more important than dateRange is $i:

So I have:

  $dateString = '09.03.2014';
$startDate = new DateTime($dateString);

$period = new DateInterval('P1M');
$endDate = clone $startDate;
$endDate->add($period);

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($startDate, $interval ,$endDate);
$i=1;
foreach($daterange as $date){
        $temp = array();
        // the following line will be used to slice the Pie chart
        $temp['ID'] = $i;
        $temp['datum'] = $date->format("d/m") . PHP_EOL;

        $rs1 = $db->prepare('SELECT naziv FROM aktivnosti WHERE user_id=:idd');
              $rs1->bindParam(':idd', $i);

              $rs1->execute();
              $naz = $rs1->fetchColumn();
                      if ($naz != false) {
              $temp['vrsta'] =  $naz;
                      } else {
                         $temp['vrsta'] =  '';
                      }

        $output['data'][] = $temp;
        $i++;
    }
    $jsonTable = json_encode($output);

As you can see I have for loop and with $temp['vrsta'] I want to get data from table aktivnosti .

I also have JS UI layer on frontend which make a html from data:

 $('#example').dataTable( {
        "ajax": "table1.php",
        "columns": [
            { "data": "ID" },
            { "data": "datum" },
            { "data": "naziv" },
            { "data": "vrsta" },

        ],
        "lengthMenu": [ 31 ],
        "columnDefs": [ {
    "targets": 3,
    "data": "download_link",
    "render": function ( data, type, full, meta ) {
      if (data != '') {
      return '<button class="btn btn-success">'+data+'</button>';
      }else {
          return data;
      }
    }
  } , etc...

Now my code fetch only first row data so problem is becouse I have many rows on table aktivnosti with the same user_id so when I have many the same user_id on aktivnosti I also need to create ''+data+''; for every row from table aktivnosti but I have NO idea how to do that?

Some ideas? How I can do that?


SQL / MySQL - how to get a unique week number (independent of the year)?

I'd like to get the number of a week from a DATE starting with Monday as the first day of the week.  While WEEK() can partially accomplish this, I would like each week to be uniquely identified.  I.e., rather than rolling over at 52 or 53 to 0 or 1, to continue counting to week 54, 55, etc.

What is the best way to accomplish this in SQL?