问:
Python flask rest api
i like to add a rest api to my project and therefore I need a selective mysql statement bt I always get back

{
    "error": "(1054, u\"Unknown column 'None' in 'where clause'\")"
}

Whats wrong with the code? how do i need to escape id correctly in the mysql select syntax??

```<code>#!/usr/bin/python

from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'pi'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_DB'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)

api = Api(app)

class test(Resource):
    def post(self):
        try:
        # Parse the arguments

        parser = reqparse.RequestParser()
        parser.add_argument('ID', type=str, help='Id of Item')
        args = parser.parse_args()

        id = str(args['ID'])
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=$(id)")

        data = cursor.fetchall()

        items_list=[];
        for item in data:
            i = {
                'ID':str(item[0]),
                'Timestamp':str(item[1]),
                'batteryVoltage':str(item[2]),
                'batteryCurrent':str(item[3]),
                'solarVoltage':str(item[4]),
                'solarCurrent':str(item[5]),
                'loadVoltage':str(item[6]),
                'loadCurrent':str(item[7]),
                'batteryPower':str(item[8]),
                'solarPower':str(item[9]),
                'loadPower':str(item[10]),
                'batteryCharge':str(item[11])
            }
            items_list.append(i)

        return {'StatusCode':'200$(_id)','Items':items_list}

    except Exception as e:
        return {'error': str(e)}
    api.add_resource(test, '/test')

    if __name__ == '__main__':
     app.run(debug=True,host='0.0.0.0')

   app.run(debug=True,host='0.0.0.0')
</code>```

答:
The execute statement is not correct, the pattern should be like cursor.execute( <select statement string>, <tuple>), change your statement to:

```<code>cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=%s",(id,))
</code>```

Title: Python flask rest api

Body:
i like to add a rest api to my project and therefore I need a selective mysql statement bt I always get back

{
    "error": "(1054, u\"Unknown column 'None' in 'where clause'\")"
}

Whats wrong with the code? how do i need to escape id correctly in the mysql select syntax??

#!/usr/bin/python

from flask import Flask
from flask_restful import Resource, Api
from flask_restful import reqparse
from flask.ext.mysql import MySQL

mysql = MySQL()
app = Flask(__name__)

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'pi'
app.config['MYSQL_DATABASE_PASSWORD'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_DB'] = 'xxxxxxxx'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'

mysql.init_app(app)

api = Api(app)

class test(Resource):
    def post(self):
        try:
        # Parse the arguments

        parser = reqparse.RequestParser()
        parser.add_argument('ID', type=str, help='Id of Item')
        args = parser.parse_args()

        id = str(args['ID'])
        conn = mysql.connect()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=$(id)")

        data = cursor.fetchall()

        items_list=[];
        for item in data:
            i = {
                'ID':str(item[0]),
                'Timestamp':str(item[1]),
                'batteryVoltage':str(item[2]),
                'batteryCurrent':str(item[3]),
                'solarVoltage':str(item[4]),
                'solarCurrent':str(item[5]),
                'loadVoltage':str(item[6]),
                'loadCurrent':str(item[7]),
                'batteryPower':str(item[8]),
                'solarPower':str(item[9]),
                'loadPower':str(item[10]),
                'batteryCharge':str(item[11])
            }
            items_list.append(i)

        return {'StatusCode':'200$(_id)','Items':items_list}

    except Exception as e:
        return {'error': str(e)}
    api.add_resource(test, '/test')

    if __name__ == '__main__':
     app.run(debug=True,host='0.0.0.0')

   app.run(debug=True,host='0.0.0.0')

Body:
The execute statement is not correct, the pattern should be like cursor.execute( <select statement string>, <tuple>), change your statement to:

cursor.execute("SELECT * FROM `PowerSystem` WHERE ID=%s",(id,))


来源: stackexchange

问:
Find which element of the stream does not match the given predicate in allmatch
I want to find out which element is failing the predicate in case of allmatch.

```<code>List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);
</code>```

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

```<code>numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });
</code>```

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

答:
For this example:

```<code>Map<Boolean, List<Integer>> map = numbers.stream()
            .collect(Collectors.partitioningBy(x -> x % 2 == 0));

    System.out.println(map); // {false=[1, 3, 5], true=[2, 4]}
</code>```

You could simply log it for example also:

```<code>boolean isEven = numbers.stream().allMatch(n -> {
        boolean test = n % 2 == 0;
        if (!test) {
            System.out.println("Failed = " + n);
        }
        return test;
    });
</code>```

But this might introduce interesting results if you run it in parallel. The output would be un-predictable. That is isEven is still going to return the correct result, but what you see via Syso is completely un-predicatable. Could be :

```<code> Failed = 3
 Failed = 1
 Failed = 5
</code>```

And on another run could be:

```<code> Failed = 3
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to find out which element is failing the predicate in case of allmatch.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

Body:
For this example:

Map<Boolean, List<Integer>> map = numbers.stream()
            .collect(Collectors.partitioningBy(x -> x % 2 == 0));

    System.out.println(map); // {false=[1, 3, 5], true=[2, 4]}

You could simply log it for example also:

boolean isEven = numbers.stream().allMatch(n -> {
        boolean test = n % 2 == 0;
        if (!test) {
            System.out.println("Failed = " + n);
        }
        return test;
    });

But this might introduce interesting results if you run it in parallel. The output would be un-predictable. That is isEven is still going to return the correct result, but what you see via Syso is completely un-predicatable. Could be :

 Failed = 3
 Failed = 1
 Failed = 5

And on another run could be:

 Failed = 3


问:
Swift: How can I use synchronized thread for Alamofire?
I want to use synchronized thread using Alamofire.

I am using like this code for synchronization.

```<code>    let queue1 = DispatchQueue(label: "queue1")
    let queue2 = DispatchQueue(label: "queue2")
    queue1.async {
        self.dataFromServer.getData()
    }
    queue2.async {
        //check if success to get the data from server
        while(!self.dataFromServer.resultData){}

        DispatchQueue.main.async {
            // do something on screen
        }
    }
</code>```

...

```<code>   func getData() {
        Alamofire.request(url).responseJSON { response in
           if response.error == nil {
            // get data
            self.resultData = true
           }else{
            // error
           }
        }
   }
</code>```

I want to do something after get data from server using Alamofire.
Is this correct?
If this is not good, please tell me about the synchronization please.
Kind regards.

答:
you can call

```<code>dispatch_sync
</code>```

instead of async  or you can call other API in the success block of first API

Body:
I want to use synchronized thread using Alamofire.

I am using like this code for synchronization.

    let queue1 = DispatchQueue(label: "queue1")
    let queue2 = DispatchQueue(label: "queue2")
    queue1.async {
        self.dataFromServer.getData()
    }
    queue2.async {
        //check if success to get the data from server
        while(!self.dataFromServer.resultData){}

        DispatchQueue.main.async {
            // do something on screen
        }
    }

...

   func getData() {
        Alamofire.request(url).responseJSON { response in
           if response.error == nil {
            // get data
            self.resultData = true
           }else{
            // error
           }
        }
   }

I want to do something after get data from server using Alamofire.
Is this correct?
If this is not good, please tell me about the synchronization please.
Kind regards.

Body:
you can call

dispatch_sync

instead of async  or you can call other API in the success block of first API


问:
only allow specific URL to access my sites
i need a code written in any language, which is secure and only allow a specific url to be mypage's refferer url. you can use passwords, cookies and anything you want but at last, the page only viewable when coming from a specific URL.(edited:)i-want-the-complete-code-to-copy-and-paste, then i will learn it slowly in the future by modifying and improving your provided code.</p>

答:
in PHP you can use the $_SERVER is a PHP super global variable which holds information about headers.</p>

```<code><?php
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];

$url = $_SERVER['HTTP_REFERER'];
$urlParse = parse_url($url);
if($urlParse['host'] !== 'test.com')
{
   die("you have not permission to access");
}
?>
</code>```

Body:
in PHP you can use the $_SERVER is a PHP super global variable which holds information about headers.

<?php
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];

$url = $_SERVER['HTTP_REFERER'];
$urlParse = parse_url($url);
if($urlParse['host'] !== 'test.com')
{
   die("you have not permission to access");
}
?>


问:
Can't append child to clicked element
I'm trying to attach div to an element when it is clicked however when I use .appendChild(div), the element I'm trying to attach to is undefined. I'm pretty confused because it's clearly in the DOM as I'm able to detect the click on it, I just can't append to it.</p>

```<code>var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function () {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       pcells[i].appendChild(div);
  };
}
</code>```

答:
I think the  problem is here like：

```<code>var a = [1, 2, 3, 4, 5];
for(var i=0; i < a.length; i++) {
    setTimeout(function() {
        console.log(i); //5
        console.log(a[i]) //undefined;
    }, 1000)
}
</code>```

If you want to solve, you need closures：

```<code>   var a = [1, 2, 3, 4, 5];
    for(var i=0; i < a.length; i++) {
        (function(index) {
            setTimeout(function() {
                console.log(index); //1,2,3,4,5
                console.log(a[index]) //1,2,3,4,5;
            }, 1000)
        })(i);
    }
</code>```

This is the essence of the problem！

For your code：

```<code>for (var i=0; i < pcells.length; i++) {
    (function(index) {
        pcells[index].onclick = function () {
            var div = document.createElement('div');
            div.style.backgroundColor = "red";
            div.style.height = "10px";
            div.style.width = "10px";

            pcells[index].appendChild(div);
        };
    })(i);
}
</code>```

by the way,the bast is use 'this' or 'event' like：

```<code>element.onclick = function(event) {
    console.log(this);
    console.log(event);
    //use 'this' or 'event' do something
}
</code>```

Title: Can't append child to clicked element

Body:
I'm trying to attach div to an element when it is clicked however when I use .appendChild(div), the element I'm trying to attach to is undefined. I'm pretty confused because it's clearly in the DOM as I'm able to detect the click on it, I just can't append to it.

var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function () {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       pcells[i].appendChild(div);
  };
}

Body:
I think the  problem is here like：

var a = [1, 2, 3, 4, 5];
for(var i=0; i < a.length; i++) {
    setTimeout(function() {
        console.log(i); //5
        console.log(a[i]) //undefined;
    }, 1000)
}

If you want to solve, you need closures：

   var a = [1, 2, 3, 4, 5];
    for(var i=0; i < a.length; i++) {
        (function(index) {
            setTimeout(function() {
                console.log(index); //1,2,3,4,5
                console.log(a[index]) //1,2,3,4,5;
            }, 1000)
        })(i);
    }

This is the essence of the problem！

For your code：

for (var i=0; i < pcells.length; i++) {
    (function(index) {
        pcells[index].onclick = function () {
            var div = document.createElement('div');
            div.style.backgroundColor = "red";
            div.style.height = "10px";
            div.style.width = "10px";

            pcells[index].appendChild(div);
        };
    })(i);
}

by the way,the bast is use 'this' or 'event' like：

element.onclick = function(event) {
    console.log(this);
    console.log(event);
    //use 'this' or 'event' do something
}


答:
Try this :

var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function () {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       this.appendChild(div);
  };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="priority-cell">CLICK HERE</div></code>```

Title: Can't append child to clicked element

Body:
Try this :

var pcells = document.getElementsByClassName('priority-cell');

for (var i=0; i < pcells.length; i++) {
  pcells[i].onclick = function () {
    var div = document.createElement('div');
       div.style.backgroundColor = "red";
       div.style.height = "10px";
       div.style.width = "10px";

       this.appendChild(div);
  };
}

<div class="priority-cell">CLICK HERE</div>


问:
PHP fputcsv encoding
I create csv file with fputcsv. I want csv file to be in windows1251 ecnding. But can't find the solution. How can I do that?
Cheers</p>

答:
```<code>fputs( $fp, $bom = chr(0xEF) . chr(0xBB) . chr(0xBF) );
</code>```

Try this it worked for me!!!

Title: PHP fputcsv encoding

Body:
fputs( $fp, $bom = chr(0xEF) . chr(0xBB) . chr(0xBF) );

Try this it worked for me!!!


问:
Is it possible to override ResolveUrl?
I use the following my .net applications to resolve the path to an image or css file or javascript file.

```<code><%=ResolveUrl("~/Scripts/myscript.js")%>

<%=ResolveUrl("~/images/myimage.jpg")%>
</code>```

All my pages and controls inherit from a base page or base user control.

I have tried but didnt succeed in overriding the ResolveUrl method so that I could include some custom logic in the files path.

Any ideas how I might override the ResolveUrl method? Alternative is to create my own custom method that does similar but would prefer to work with ResolveUrl.

答: ResolveUrl is not virtual so you will have little success using an override and it does not internally use anything that you can override to customize the functionality. That leaves you with writting your own utility function.

ContentLicense: CC BY-SA 2.5

Title: Is it possible to override ResolveUrl?

Body:
I use the following my .net applications to resolve the path to an image or css file or javascript file.

<%=ResolveUrl("~/Scripts/myscript.js")%>

<%=ResolveUrl("~/images/myimage.jpg")%>

All my pages and controls inherit from a base page or base user control.

I have tried but didnt succeed in overriding the ResolveUrl method so that I could include some custom logic in the files path.

Any ideas how I might override the ResolveUrl method? Alternative is to create my own custom method that does similar but would prefer to work with ResolveUrl.


问:
SELECT data based on given pairs
I have little experience using SQL, and I am now using JDBC to connect to my database.
I am using sqlite, my schema looks as follows:

```<code>id1, id2, value1, value2
</code>```

I want to extract rows based on a list of given pairs of id1 and id2.
I know Postgresql can do

```<code>SELECT  *
FROM    table
WHERE   ("id1", "id2") IN (('1', '2'), ('3', '4'));
</code>```

But what about sqlite?

答:
Since version 3.15.0, SQLite supports row values:</p>

```<code>SELECT *
FROM   MyTable
WHERE  (id1, id2) IN (VALUES ('1', '2'), ('3', '4'));
</code>```

Title: SELECT data based on given pairs

Body:
I have little experience using SQL, and I am now using JDBC to connect to my database.
I am using sqlite, my schema looks as follows:

id1, id2, value1, value2

I want to extract rows based on a list of given pairs of id1 and id2.
I know Postgresql can do

SELECT  *
FROM    table
WHERE   ("id1", "id2") IN (('1', '2'), ('3', '4'));

But what about sqlite?

Body:
Since version 3.15.0, SQLite supports row values:

SELECT *
FROM   MyTable
WHERE  (id1, id2) IN (VALUES ('1', '2'), ('3', '4'));


问:
Behaviour of "#'" in lisp
As far as I understand #' <object> is an abbreviation for (function <object>).

But I noticed different behaviour while using #' in apply function.

Example

```<code>(apply '+ '(1 2)) => Works and give 3
(apply (function +) '(1 2 ) ) => 3
</code>```

However

```<code>(apply '# '(1 2)) => Err!!
</code>```

答:
As described in the reference:

The notation #'name may be used as an abbreviation for (function name).

Note that the syntax used is #',  not '#, which is just a way a quoting the symbol #, since 'a is equivalent to (quote a).

So you should use:

```<code>(apply #'+ '(1 2))
</code>```

In general the character # followed by a character has a special meaning for inputting values. For instance #\ is for reading characters (like in #\Space), #( for reading vectors, (like in #(1 2 3)), etc.

Title: Behaviour of "#'" in lisp

Body:
As far as I understand #' <object> is an abbreviation for (function <object>).

But I noticed different behaviour while using #' in apply function.

Example

(apply '+ '(1 2)) => Works and give 3
(apply (function +) '(1 2 ) ) => 3

However

(apply '# '(1 2)) => Err!!

Body:
As described in the reference:

The notation #'name may be used as an abbreviation for (function name).

Note that the syntax used is #',  not '#, which is just a way a quoting the symbol #, since 'a is equivalent to (quote a).

So you should use:

(apply #'+ '(1 2))

In general the character # followed by a character has a special meaning for inputting values. For instance #\ is for reading characters (like in #\Space), #( for reading vectors, (like in #(1 2 3)), etc.


问:
Get entire bucket or more than one objects from AWS S3 bucket through Ansible
As far as I know S3 module of Ansible, it can only get an object at once.

My question is that what if I want to download/get entire bucket or more than one object from S3 bucket at once. Is there any hack?

答:
It will be able to:</p>

```<code>- name: Get s3 objects
  s3:
    bucket: your-s3-bucket
    prefix: your-object-directory-path
    mode: list
  register: s3_object_list

- name: Create download directory
  file:
    path: "/your/destination/directory/path/{{ item | dirname }}"
    state: directory
  with_items:
      - "{{ s3_object_list.s3_keys }}"

- name: Download s3 objects
  s3:
    bucket: your-s3-bucket
    object: "{{ item }}"
    mode: get
    dest: "/your/destination/directory/path/{{ item }}"
  with_items:
    - "{{ s3_object_list.s3_keys }}"
</code>```

Body:
It will be able to:

- name: Get s3 objects
  s3:
    bucket: your-s3-bucket
    prefix: your-object-directory-path
    mode: list
  register: s3_object_list

- name: Create download directory
  file:
    path: "/your/destination/directory/path/{{ item | dirname }}"
    state: directory
  with_items:
      - "{{ s3_object_list.s3_keys }}"

- name: Download s3 objects
  s3:
    bucket: your-s3-bucket
    object: "{{ item }}"
    mode: get
    dest: "/your/destination/directory/path/{{ item }}"
  with_items:
    - "{{ s3_object_list.s3_keys }}"


问:
Laravel giving 500 internal error on centos 7 with apache and php 7
I am new to centos. I have installed apache and php 7. I have also installed all php extensions required for laravel.

I have an laravel app working fine on windows.I have just transferred my code from windows to centos 7.The problem is now it shows 500 internal error in console on every route.
I have changed .htaccess code as explained here:

https://laravel.com/docs/5.0/configuration#pretty-urls

folder rights to storage and bootstrap is set to 777, also enabled mod_rewrite.

Also when I installed fresh laravel its not working. When i am updating the main route in web.php from

```<code>Route::get('/', function () {
    return view('welcome');
});
</code>```

to

```<code>Route::get('/', function () {
    return 'welcome';
});
</code>```

It shows welcome message but for

```<code>Route::get('/', function () {
    return view('welcome');
});
</code>```

getting 500 internal error in console and blank page appears.

httpd Error log

答:
Step 1:
You have to enable .htaccess by adding this to your vhost:

```<code><Directory /var/www/html/yourfoldername/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</code>```

Step 2: And  disabled SELinux permanently.
Click here

Body:
I am new to centos. I have installed apache and php 7. I have also installed all php extensions required for laravel.

I have an laravel app working fine on windows.I have just transferred my code from windows to centos 7.The problem is now it shows 500 internal error in console on every route.
I have changed .htaccess code as explained here:

https://laravel.com/docs/5.0/configuration#pretty-urls

folder rights to storage and bootstrap is set to 777, also enabled mod_rewrite.

Also when I installed fresh laravel its not working. When i am updating the main route in web.php from

Route::get('/', function () {
    return view('welcome');
});

to

Route::get('/', function () {
    return 'welcome';
});

It shows welcome message but for

Route::get('/', function () {
    return view('welcome');
});

getting 500 internal error in console and blank page appears.

httpd Error log

Body:
Step 1:
You have to enable .htaccess by adding this to your vhost:

<Directory /var/www/html/yourfoldername/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

Step 2: And  disabled SELinux permanently.
Click here


问:
WPF: Get an item's position index within CollectionViewSource and not on the bound source
I've got a view model that exposes a CollectionViewSource built around my observable collection. I also have a command for deleting items:

```<code>public ObservableCollection<FooViewModel> Foos { get; set; }
public ICollectionView FooCollectionView { get; set; }
public ICommand DeleteFooCommand { get; set; }

private FooViewModel _SelectedFoo;
public FooViewModel SelectedFoo
{
    get { return _SelectedFoo; }
    set
    {
        if (value != _SelectedFoo)
        {
            _SelectedFoo = value;
            OnPropertyChanged();
        }
    }
}

public MyViewModel()
{
    Foos = new ObservableCollection<FooViewModel>();
    FooCollectionView = CollectionViewSource.GetDefaultView(Patches);
    FooCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
    DeleteFooCommand = new RelayCommand(DeleteFoo);
}

private void DeleteFoo(object parameter)
{
    var collection = parameter as IEnumerable;
    if (collection == null) return;

    var itemsToDelete = collection.OfType<FooViewModel>().ToList();
    if (!itemsToDelete.Any()) return;

    SelectedFoo = null;

    // TODO: Figure out what the next SelectedFoo should be after deleting)

    foreach (var item in itemsToDelete)
        Foos.Remove(item);
}
</code>```

In the spirit of MVVM, I don't want to know whether or not my CollectionViewSource was bound to a ListBox, ListView, etc. I simply expect one or more FooViewModels in my command parameter (via [control].SelectedItems). However, I want to set the new SelectedFoo to what I think would be the next logical item that should be selected. I know there is IndexOf() of my source collection, but that index won't match the index after the sort of my CollectionViewSource. Is there a way to get the index of the item on the view and not the source? I can do what I want if I pass the bound ListBox as my command parameter, but I'd rather not know about the bound control.

答:
To answer your question directly (i.e. how to obtain the resulting index of an item in a collection view) - you can take advantage of the fact that the collection view enumerates the items in sorted order and then simply utilize Linq to count items preceding the one you're interested in. Since I'm not sure how to mix it into your view-model (you're not even checking if currently selected item is among the deleted ones?), here's an extension method that will return the resulting index of an item in a collection view:

```<code>public static int IndexOf(this ICollectionView view, object item)
{
    return view.Cast<object>().TakeWhile(x => !Equals(x, item)).Count();
}
</code>```

Note though that this solution is not universal because it assumes that item is both in the source collection and is not filtered out by the collection view. Otherwise it will return the total count of items in the view (excluding the filtered ones). A universal solution would go something like this:

```<code>public static int IndexOf(this ICollectionView view, object item)
{
    var e = view.GetEnumerator();
    var idx = 0;
    while (e.MoveNext())
    {
        if (Equals(item, e.Current))
            return idx;
        else
            idx++;
    }
    //if we've got this far it means that the item is either filtered out
    //or is not in the source collection
    return -1;
}
</code>```

Then of course there's another problem, namely you cannot access items by index in a collection view. So you have to enumerate the collection second time:

```<code>var idx = view.IndexOf(item);
var nextItem = view.Cast<object>().ElementAtOrDefault(idx + 1);
</code>```

That should not be a problem for fairly small collections, but may become one for large collections (remember that the view enumerates items in sorted order, so unless the sorting result is cached, each enumeration would require to sort the whole collection).

To answer a slightly modified question ("How do I get an item following a particular one from a sorted collection view?") there's a simple solution that needs to enumerate the collection only once:

```<code>var nextItem = view.Cast<object>()
    .SkipWhile(x => !Equals(x, item)) //skip preceding items
    .Skip(1) //skip the item itself
    .FirstOrDefault();
</code>```

Note that this will return null if the item is not present in the resulting collection or is its last item.

Body:
I've got a view model that exposes a CollectionViewSource built around my observable collection. I also have a command for deleting items:

public ObservableCollection<FooViewModel> Foos { get; set; }
public ICollectionView FooCollectionView { get; set; }
public ICommand DeleteFooCommand { get; set; }

private FooViewModel _SelectedFoo;
public FooViewModel SelectedFoo
{
    get { return _SelectedFoo; }
    set
    {
        if (value != _SelectedFoo)
        {
            _SelectedFoo = value;
            OnPropertyChanged();
        }
    }
}

public MyViewModel()
{
    Foos = new ObservableCollection<FooViewModel>();
    FooCollectionView = CollectionViewSource.GetDefaultView(Patches);
    FooCollectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
    DeleteFooCommand = new RelayCommand(DeleteFoo);
}

private void DeleteFoo(object parameter)
{
    var collection = parameter as IEnumerable;
    if (collection == null) return;

    var itemsToDelete = collection.OfType<FooViewModel>().ToList();
    if (!itemsToDelete.Any()) return;

    SelectedFoo = null;

    // TODO: Figure out what the next SelectedFoo should be after deleting)

    foreach (var item in itemsToDelete)
        Foos.Remove(item);
}

In the spirit of MVVM, I don't want to know whether or not my CollectionViewSource was bound to a ListBox, ListView, etc. I simply expect one or more FooViewModels in my command parameter (via [control].SelectedItems). However, I want to set the new SelectedFoo to what I think would be the next logical item that should be selected. I know there is IndexOf() of my source collection, but that index won't match the index after the sort of my CollectionViewSource. Is there a way to get the index of the item on the view and not the source? I can do what I want if I pass the bound ListBox as my command parameter, but I'd rather not know about the bound control.

Body:
To answer your question directly (i.e. how to obtain the resulting index of an item in a collection view) - you can take advantage of the fact that the collection view enumerates the items in sorted order and then simply utilize Linq to count items preceding the one you're interested in. Since I'm not sure how to mix it into your view-model (you're not even checking if currently selected item is among the deleted ones?), here's an extension method that will return the resulting index of an item in a collection view:

public static int IndexOf(this ICollectionView view, object item)
{
    return view.Cast<object>().TakeWhile(x => !Equals(x, item)).Count();
}

Note though that this solution is not universal because it assumes that item is both in the source collection and is not filtered out by the collection view. Otherwise it will return the total count of items in the view (excluding the filtered ones). A universal solution would go something like this:

public static int IndexOf(this ICollectionView view, object item)
{
    var e = view.GetEnumerator();
    var idx = 0;
    while (e.MoveNext())
    {
        if (Equals(item, e.Current))
            return idx;
        else
            idx++;
    }
    //if we've got this far it means that the item is either filtered out
    //or is not in the source collection
    return -1;
}

Then of course there's another problem, namely you cannot access items by index in a collection view. So you have to enumerate the collection second time:

var idx = view.IndexOf(item);
var nextItem = view.Cast<object>().ElementAtOrDefault(idx + 1);

That should not be a problem for fairly small collections, but may become one for large collections (remember that the view enumerates items in sorted order, so unless the sorting result is cached, each enumeration would require to sort the whole collection).

To answer a slightly modified question ("How do I get an item following a particular one from a sorted collection view?") there's a simple solution that needs to enumerate the collection only once:

var nextItem = view.Cast<object>()
    .SkipWhile(x => !Equals(x, item)) //skip preceding items
    .Skip(1) //skip the item itself
    .FirstOrDefault();

Note that this will return null if the item is not present in the resulting collection or is its last item.


问:
ClassCastException by cast to owe type
In an implementation of org.dozer.BeanFactory.createBean(Object, Class<?>, String) I try to cast the object to type of it. If I deploy all my bundles, that is to shut down and start all bundles I got a ClassCastException:

```<code>java.lang.ClassCastException: de.xxx.Configuration cannot be cast to de.xxx.Configuration
</code>```

I suspect a problem with the ClassLoaders of karaf and/or dozer.
This class only one time exists in my jars and they isn't modified.
Configuration doesn't implement serializeable and has no serial version id.

How to avoid this Exception?

kind regards

答:
maybe too old question, but... do you use in your development something like "spring-boot-devtools" that make something with the "classloader".

In my case, debugging the dozer library do it well, and the exception throws when the library return to my own class the result of the mapping.

Title: ClassCastException by cast to owe type

Body:
In an implementation of org.dozer.BeanFactory.createBean(Object, Class<?>, String) I try to cast the object to type of it. If I deploy all my bundles, that is to shut down and start all bundles I got a ClassCastException:

java.lang.ClassCastException: de.xxx.Configuration cannot be cast to de.xxx.Configuration

I suspect a problem with the ClassLoaders of karaf and/or dozer.
This class only one time exists in my jars and they isn't modified.
Configuration doesn't implement serializeable and has no serial version id.

How to avoid this Exception?

kind regards


问:
Very complex linq
I'm having trouble rewriteing a complex sql query as linq.

```<code>-- gets the SpecificationAttributeOptionIDs that are in the FilteredSpecs list, but don't match
    SELECT * FROM #FilteredSpecs [fs]
                            WHERE [fs].SpecificationAttributeOptionID NOT IN
                            (
                                -- gets the SpecificationAttributeOptionIDs that match
                                SELECT psam.SpecificationAttributeOptionID
                                FROM dbo.Nop_Product_SpecificationAttribute_Mapping psam
                                WHERE psam.AllowFiltering = 1 AND psam.ProductID = 1
                            )
</code>```

basically what I have, is a list FilteredSpec which is C# is a List of int. I'm trying to get all products that have all the attributeoptions from the FilteredSpec list set.

What I've tried is this (which given my limited knowledge of linq obviously doesn't work):

```<code>var query = from p in Products
                        where (p.NpProductSpecificationAttributes.Select(a => filters.Contains(a.NpSpecificationAttributeOption.SpecificationAttributeOptionId)).Count() == 0)
                        select p;
</code>```

Can anybody guide me in the right direction please?

答:
This is probably the simplest:

```<code>var query = Products.Where(
    p => FilteredSpec.All(
       fs => p.NpProductSpecificationAttributes.Any(
          a => a.NpSpecificationAttributeOption.AllowFiltering &&
               a.NpSpecificationAttributeOption.SpecificationAttributeOptionId == fs)));
</code>```

It is possible that LINQ to Entities won't know how to translate this if FilteredSpec is actually a List object. If that's the case, let me know and we'll see if we can come up with some other solution.

Title: Very complex linq

Body:
I'm having trouble rewriteing a complex sql query as linq.

-- gets the SpecificationAttributeOptionIDs that are in the FilteredSpecs list, but don't match
    SELECT * FROM #FilteredSpecs [fs]
                            WHERE [fs].SpecificationAttributeOptionID NOT IN
                            (
                                -- gets the SpecificationAttributeOptionIDs that match
                                SELECT psam.SpecificationAttributeOptionID
                                FROM dbo.Nop_Product_SpecificationAttribute_Mapping psam
                                WHERE psam.AllowFiltering = 1 AND psam.ProductID = 1
                            )

basically what I have, is a list FilteredSpec which is C# is a List of int. I'm trying to get all products that have all the attributeoptions from the FilteredSpec list set.

What I've tried is this (which given my limited knowledge of linq obviously doesn't work):

var query = from p in Products
                        where (p.NpProductSpecificationAttributes.Select(a => filters.Contains(a.NpSpecificationAttributeOption.SpecificationAttributeOptionId)).Count() == 0)
                        select p;

Can anybody guide me in the right direction please?

Body:
This is probably the simplest:

var query = Products.Where(
    p => FilteredSpec.All(
       fs => p.NpProductSpecificationAttributes.Any(
          a => a.NpSpecificationAttributeOption.AllowFiltering &&
               a.NpSpecificationAttributeOption.SpecificationAttributeOptionId == fs)));

It is possible that LINQ to Entities won't know how to translate this if FilteredSpec is actually a List object. If that's the case, let me know and we'll see if we can come up with some other solution.


问:
Guard against filtering an empty JS object
I have the following code:

```<code>for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    if (obj[key].id === foo.id) {
      // do something
    }
  }
}
</code>```

I'm checking whether the object is not empty before doing any functionality, because the array is populated later on user interaction.

For better readability, I want to do something like this:

```<code>const result = obj.filter((item) => item.id === foo.id)
return result[0]
</code>```

This, however, will produce an error: obj.filter is not a function since the object is empty when the page renders and is populated later.
Question is - how do I simplify this and at the same time guard against filtering the empty object in the most simple way?

EDIT: Adding sample data structure for obj

```<code>{
    0: { id: 2, name: 'John', category: 'Repair' },
    1: { id: 3, name: 'William', category: 'Maintenance' }
}
</code>```

答:
You could use an empty array as default value.

```<code>const result = (obj || []).filter(item => item.id === foo.id);
</code>```

or use an explicit check with Array.isArray.

```<code>const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id);
</code>```

The result is either an array or false.

If you like to get an empty array, you could use an array as default value as well, like

```<code>const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id) || [];
</code>```

Now, after giving the structure of the object, you could use

var getItem = (obj, id) => obj && typeof obj === 'object' && Object
        .keys(obj)
        .filter(key => obj[key].id === id)
        .map(key => obj[key]),
    obj = {
        0: { id: 2, name: 'John', category: 'Repair' },
        1: { id: 3, name: 'William', category: 'Maintenance' }
    },
    result1 = getItem(obj, 3),
    result2 = getItem(null, 3);

console.log(result1);
console.log(result2);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have the following code:

for (var key in obj) {
  if (obj.hasOwnProperty(key)) {
    if (obj[key].id === foo.id) {
      // do something
    }
  }
}

I'm checking whether the object is not empty before doing any functionality, because the array is populated later on user interaction.

For better readability, I want to do something like this:

const result = obj.filter((item) => item.id === foo.id)
return result[0]

This, however, will produce an error: obj.filter is not a function since the object is empty when the page renders and is populated later.
Question is - how do I simplify this and at the same time guard against filtering the empty object in the most simple way?

EDIT: Adding sample data structure for obj

{
    0: { id: 2, name: 'John', category: 'Repair' },
    1: { id: 3, name: 'William', category: 'Maintenance' }
}

Body:
You could use an empty array as default value.

const result = (obj || []).filter(item => item.id === foo.id);

or use an explicit check with Array.isArray.

const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id);

The result is either an array or false.

If you like to get an empty array, you could use an array as default value as well, like

const result = Array.isArray(obj) && obj.filter(item => item.id === foo.id) || [];

Now, after giving the structure of the object, you could use

var getItem = (obj, id) => obj && typeof obj === 'object' && Object
        .keys(obj)
        .filter(key => obj[key].id === id)
        .map(key => obj[key]),
    obj = {
        0: { id: 2, name: 'John', category: 'Repair' },
        1: { id: 3, name: 'William', category: 'Maintenance' }
    },
    result1 = getItem(obj, 3),
    result2 = getItem(null, 3);

console.log(result1);
console.log(result2);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Obtaining EntityManager in Spring + Hibernate configuration
I have a Spring MVC 4.0 application, and I am learning JPA. I use Hibernate as the JPA implementation.

I can configure Hibernate as described in this tutorial. It works fine, but I have to use Hibernate's Session object:

```<code>@Autowired
SessionFactory sessionFactory;

...

Session session = sessionFactory.openSession();
</code>```

Now, I want to use JPA's EntityManager instead. I have followed this tutorial on the same web site (the configuration is very similar). And I tried to obtain an EntityManager object this way:

```<code>@PersistenceContext
EntityManager entityManager;
</code>```

I got a runtime message:

```<code>java.lang.IllegalStateException: No transactional EntityManager available
</code>```

Then, I followed the suggestion in this answer, and tried to use the following code:

```<code>@PersistenceContext
EntityManager entityManager;

...

entityManager=entityManager.getEntityManagerFactory().createEntityManager();
</code>```

It works a few times (about 9 repetitive method invocations), and then the application freezes.

What is the right way to get EntityManager in Spring + Hibernate configuration?

I do not need any Spring transaction functionality for now. I just want to get an access to EntityManager and play with JPA.

Spring/Hibernate configuration file (hibernate.xml)

```<code><?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test_db" />
        <property name="username" value="test" />
        <property name="password" value="test" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="net.myproject" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <tx:annotation-driven />

</beans>
</code>```

The class where I attempt to use EntityManager

```<code>@Repository
public class ProductsService {

    @PersistenceContext
    EntityManager entityManager;

    @Transactional
    public GridResponse<Product> getProducts(GridRequest dRequest) {

        // The following line causes the exception: "java.lang.IllegalStateException: No transactional EntityManager available"
        Session session = entityManager.unwrap(Session.class);

        //...
    }

...
</code>```

答:
It can be use with @Autowired as shown in https://stackoverflow.com/a/33742769/2028440</p>

```<code>@Autowired
private EntityManager entityManager;
</code>```

Body:
I have a Spring MVC 4.0 application, and I am learning JPA. I use Hibernate as the JPA implementation.

I can configure Hibernate as described in this tutorial. It works fine, but I have to use Hibernate's Session object:

@Autowired
SessionFactory sessionFactory;

...

Session session = sessionFactory.openSession();

Now, I want to use JPA's EntityManager instead. I have followed this tutorial on the same web site (the configuration is very similar). And I tried to obtain an EntityManager object this way:

@PersistenceContext
EntityManager entityManager;

I got a runtime message:

java.lang.IllegalStateException: No transactional EntityManager available

Then, I followed the suggestion in this answer, and tried to use the following code:

@PersistenceContext
EntityManager entityManager;

...

entityManager=entityManager.getEntityManagerFactory().createEntityManager();

It works a few times (about 9 repetitive method invocations), and then the application freezes.

What is the right way to get EntityManager in Spring + Hibernate configuration?

I do not need any Spring transaction functionality for now. I just want to get an access to EntityManager and play with JPA.

Spring/Hibernate configuration file (hibernate.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"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/test_db" />
        <property name="username" value="test" />
        <property name="password" value="test" />
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="net.myproject" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
        </property>
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <tx:annotation-driven />

</beans>

The class where I attempt to use EntityManager

@Repository
public class ProductsService {

    @PersistenceContext
    EntityManager entityManager;

    @Transactional
    public GridResponse<Product> getProducts(GridRequest dRequest) {

        // The following line causes the exception: "java.lang.IllegalStateException: No transactional EntityManager available"
        Session session = entityManager.unwrap(Session.class);

        //...
    }

...

Body:
It can be use with @Autowired as shown in https://stackoverflow.com/a/33742769/2028440

@Autowired
private EntityManager entityManager;


问:
Unity - Build runs slow while editor runs fine
In the Unity editor my game runs fine at a near constant 60fps. However, when I build my game and run it as a standalone it runs incredibly slow at around 5-10fps. I have looked up this issue and so far the only solution I could find was to disable the Player Log from within Edit>ProjectSettings>Player. Since doing this the frame rate has increased a tiny amount however the game is still unplayable. I don't think it has anything to do with my code or graphics as, like I said, the game runs fine in the editor.

If anybody knows how I can fix this problem, in any way, it would be much appreciated if you could give a reply.

Kind Regards,

Tommy Eaves

答: There was an issue with my quality settings. I had set v-sync to its highest setting which was lagging the when built as a standalone but wasn't active while in the editor. I set my quality settings to the default settings and it all works now.</p>


问:
How to vertically align an image inside a div
How can you align an image inside of a containing div?

Example

In my example, I need to vertically center the  in the
 with class ="frame":

```<code><div class="frame" style="height: 25px;">
    <img src="http://jsfiddle.net/img/logo.png" />
</div>
</code>```

.frame's height is fixed and the image's height is unknown. I can add new elements in .frame if that's the only solution. I'm trying to do this on Internet  Explorer 7  and later, WebKit, Gecko.

See the jsfiddle here.

.frame {
    height: 25px;      /* Equals maximum image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;

    text-align: center;
    margin: 1em 0;
}
img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=250 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=25 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=23 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=21 />
</div>
<div class=frame>
   <img src="http://jsfiddle.net/img/logo.png" height=19 />
</div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=17 />
</div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=15 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=13 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=11 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=9 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=7 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=5 />
 </div>
<div class=frame>
    <img src="http://jsfiddle.net/img/logo.png" height=3 />
 </div></code>```

答:
Want to align an image which have after a text / title and both are inside a div?

See on JSfiddle or Run Code Snippet.

Just be sure to have an ID or a class at all your elements (div, img, title, etc.).

For me works this solution on all browsers (for mobile devices you must to adapt your code with: @media).

h2.h2red {
    color: red;
    font-size: 14px;
}
.mydivclass {
    margin-top: 30px;
    display: block;
}
img.mydesiredclass {
    margin-right: 10px;
    display: block;
    float: left; /* If you want to allign the text with an image on the same row */
    width: 100px;
    heght: 100px;
    margin-top: -40px /* Change this value to adapt to your page */;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="mydivclass">
    <br />
    <img class="mydesiredclass" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Wikipedia-logo-v2-en.svg/2000px-Wikipedia-logo-v2-en.svg.png">
    <h2 class="h2red">Text aligned after image inside a div by negative manipulate the img position</h2>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
How can you align an image inside of a containing div?

Example

In my example, I need to vertically center the  in the
 with class ="frame":

.frame's height is fixed and the image's height is unknown. I can add new elements in .frame if that's the only solution. I'm trying to do this on Internet  Explorer 7  and later, WebKit, Gecko.

See the jsfiddle here.

.frame {
    height: 25px;      /* Equals maximum image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;

    text-align: center;
    margin: 1em 0;
}
img {
    background: #3A6F9A;
    vertical-align: middle;
    max-height: 25px;
    max-width: 160px;
}

Body:
Want to align an image which have after a text / title and both are inside a div?

See on JSfiddle or Run Code Snippet.

Just be sure to have an ID or a class at all your elements (div, img, title, etc.).

For me works this solution on all browsers (for mobile devices you must to adapt your code with: @media).

h2.h2red {
    color: red;
    font-size: 14px;
}
.mydivclass {
    margin-top: 30px;
    display: block;
}
img.mydesiredclass {
    margin-right: 10px;
    display: block;
    float: left; /* If you want to allign the text with an image on the same row */
    width: 100px;
    heght: 100px;
    margin-top: -40px /* Change this value to adapt to your page */;
}

<div class="mydivclass">
    <br />
    <img class="mydesiredclass" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Wikipedia-logo-v2-en.svg/2000px-Wikipedia-logo-v2-en.svg.png">
    <h2 class="h2red">Text aligned after image inside a div by negative manipulate the img position</h2>
</div>


问:
How to get VM type/size for the nodes in a Service Fabric Cluster?
I have a Service Fabric cluster with 5 nodes that I set initially to the type Standard_D1_v2. I wanted to know if there is a way to programmatically get the type or size (SKU information) of the nodes in a Service Fabric Cluster. I basically want to retrieve the information 'Standard_D1_v2' about my nodes by code.

答:
You can use the REST api.

https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/VirtualMachineScaleSets/{vmScaleSet}/skus?api-version={apiVersion}

Or use the ComputeManagementClient. How-to here.


问:
Best way to output ajax data from a Magento Admin Extension
I'm writing a Magento Admin extension that has some ajax callbacks in it.  Up until now I've been echoing the json I'm feeding back through the ajax call with a simple echo statement in the controller.  It "works" but I get a bunch of errors like this in my log file:

2010-12-14T15:37:05+00:00 DEBUG (7): HEADERS ALREADY SENT: ```[0] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:44
[1] /home/simplifiedsafety/www/store/lib/Zend/Controller/Response/Abstract.php:727
[2] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:75
[3] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Varien/Front.php:188
[4] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Model/App.php:304
[5] /home/simplifiedsafety/www/store/app/Mage.php:599
[6] /home/simplifiedsafety/www/store/index.php:104
```

I think to avoid this I need to push it out through some sort of block.  Can someone give me a little guidance on this?

答:
Magento uses a response object to send output back to the browser.  Even when you call renderLayout from a controller, Magento is just building up the string output in memory before outputting it.  The reason you're getting this error is there's system code after the controller dispatch that's attempting to set headers, but your unexpected controller output prevents those headers from being set.

The simplest solution is throw an

```<code>exit;
</code>```

in directly after your controller output.  This halts execution, your ajax response is sent, the world is happy. Rejoice.

Alternately, if you're looking for that always elusive "right" way, based on examples in the core, it looks like you can call the following from your controller to retrieve the response object, and then set its body directly.

```<code>$this->getResponse()->setBody('Some Response');
</code>```

If you do the above, you're bypassing the Magento layout system and setting output directly, but keeping the responsibility of sending the output with the response object.

You may want to set your own values for headers (JSON, XML, etc), which you can do with something like the following (again, from a controller action)

```<code>$this->getResponse()
->clearHeaders()
->setHeader('Content-Type', 'text/xml')
->setBody('Some Response');
</code>```

Good luck!

Body:
I'm writing a Magento Admin extension that has some ajax callbacks in it.  Up until now I've been echoing the json I'm feeding back through the ajax call with a simple echo statement in the controller.  It "works" but I get a bunch of errors like this in my log file:

2010-12-14T15:37:05+00:00 DEBUG (7): HEADERS ALREADY SENT:
[0] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:44
[1] /home/simplifiedsafety/www/store/lib/Zend/Controller/Response/Abstract.php:727
[2] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Response/Http.php:75
[3] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Controller/Varien/Front.php:188
[4] /home/simplifiedsafety/www/store/app/code/core/Mage/Core/Model/App.php:304
[5] /home/simplifiedsafety/www/store/app/Mage.php:599
[6] /home/simplifiedsafety/www/store/index.php:104

I think to avoid this I need to push it out through some sort of block.  Can someone give me a little guidance on this?

Body:
Magento uses a response object to send output back to the browser.  Even when you call renderLayout from a controller, Magento is just building up the string output in memory before outputting it.  The reason you're getting this error is there's system code after the controller dispatch that's attempting to set headers, but your unexpected controller output prevents those headers from being set.

The simplest solution is throw an

exit;

in directly after your controller output.  This halts execution, your ajax response is sent, the world is happy. Rejoice.

Alternately, if you're looking for that always elusive "right" way, based on examples in the core, it looks like you can call the following from your controller to retrieve the response object, and then set its body directly.

$this->getResponse()->setBody('Some Response');

If you do the above, you're bypassing the Magento layout system and setting output directly, but keeping the responsibility of sending the output with the response object.

You may want to set your own values for headers (JSON, XML, etc), which you can do with something like the following (again, from a controller action)

$this->getResponse()
->clearHeaders()
->setHeader('Content-Type', 'text/xml')
->setBody('Some Response');

Good luck!


问:
ProcessStartInfo hanging on "WaitForExit"? Why?
I have the following code:

```<code>info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents
</code>```

I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at WaitForExit. Note also this code does NOT hang for smaller outputs (like 3KB).

Is it possible that the internal StandardOutput in ProcessStartInfo can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?

答:
I know that this is supper old but, after reading this whole page none of the solutions was working for me, although I didn't try Muhammad Rehan as the code was a little hard to follow, although I guess he was on the right track.  When I say it didn't work that's not entirely true, sometimes it would work fine, I guess it is something to do with the length of the output before an EOF mark.

Anyway, the solution that worked for me was to use different threads to read the StandardOutput and StandardError and write the messages.

```<code>        StreamWriter sw = null;
        var queue = new ConcurrentQueue<string>();

        var flushTask = new System.Timers.Timer(50);
        flushTask.Elapsed += (s, e) =>
        {
            while (!queue.IsEmpty)
            {
                string line = null;
                if (queue.TryDequeue(out line))
                    sw.WriteLine(line);
            }
            sw.FlushAsync();
        };
        flushTask.Start();

        using (var process = new Process())
        {
            try
            {
                process.StartInfo.FileName = @"...";
                process.StartInfo.Arguments = $"...";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                process.Start();

                var outputRead = Task.Run(() =>
                {
                    while (!process.StandardOutput.EndOfStream)
                    {
                        queue.Enqueue(process.StandardOutput.ReadLine());
                    }
                });

                var errorRead = Task.Run(() =>
                {
                    while (!process.StandardError.EndOfStream)
                    {
                        queue.Enqueue(process.StandardError.ReadLine());
                    }
                });

                var timeout = new TimeSpan(hours: 0, minutes: 10, seconds: 0);

                if (Task.WaitAll(new[] { outputRead, errorRead }, timeout) &&
                    process.WaitForExit((int)timeout.TotalMilliseconds))
                {
                    if (process.ExitCode != 0)
                    {
                        throw new Exception($"Failed run... blah blah");
                    }
                }
                else
                {
                    throw new Exception($"process timed out after waiting {timeout}");
                }
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to succesfully run the process.....", e);
            }
        }
    }
</code>```

Hope this helps someone, who thought this could be so hard!

OwnerDisplayName: Epaga

Body:
I have the following code:

info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents

I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at WaitForExit. Note also this code does NOT hang for smaller outputs (like 3KB).

Is it possible that the internal StandardOutput in ProcessStartInfo can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?

Body:
I know that this is supper old but, after reading this whole page none of the solutions was working for me, although I didn't try Muhammad Rehan as the code was a little hard to follow, although I guess he was on the right track.  When I say it didn't work that's not entirely true, sometimes it would work fine, I guess it is something to do with the length of the output before an EOF mark.

Anyway, the solution that worked for me was to use different threads to read the StandardOutput and StandardError and write the messages.

        StreamWriter sw = null;
        var queue = new ConcurrentQueue<string>();

        var flushTask = new System.Timers.Timer(50);
        flushTask.Elapsed += (s, e) =>
        {
            while (!queue.IsEmpty)
            {
                string line = null;
                if (queue.TryDequeue(out line))
                    sw.WriteLine(line);
            }
            sw.FlushAsync();
        };
        flushTask.Start();

        using (var process = new Process())
        {
            try
            {
                process.StartInfo.FileName = @"...";
                process.StartInfo.Arguments = $"...";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;

                process.Start();

                var outputRead = Task.Run(() =>
                {
                    while (!process.StandardOutput.EndOfStream)
                    {
                        queue.Enqueue(process.StandardOutput.ReadLine());
                    }
                });

                var errorRead = Task.Run(() =>
                {
                    while (!process.StandardError.EndOfStream)
                    {
                        queue.Enqueue(process.StandardError.ReadLine());
                    }
                });

                var timeout = new TimeSpan(hours: 0, minutes: 10, seconds: 0);

                if (Task.WaitAll(new[] { outputRead, errorRead }, timeout) &&
                    process.WaitForExit((int)timeout.TotalMilliseconds))
                {
                    if (process.ExitCode != 0)
                    {
                        throw new Exception($"Failed run... blah blah");
                    }
                }
                else
                {
                    throw new Exception($"process timed out after waiting {timeout}");
                }
            }
            catch (Exception e)
            {
                throw new Exception($"Failed to succesfully run the process.....", e);
            }
        }
    }

Hope this helps someone, who thought this could be so hard!


答:
Make it a function that takes the object as argument. Then just make sure you call the function with a valid, initialised argument. And then you might as well also pass foo as argument:

```<code>const f = (obj, foo) => obj.filter((item) => item.id === foo.id)
// ...
return f(obj, foo)[0]
</code>```

Title: Guard against filtering an empty JS object

Body:
Make it a function that takes the object as argument. Then just make sure you call the function with a valid, initialised argument. And then you might as well also pass foo as argument:

const f = (obj, foo) => obj.filter((item) => item.id === foo.id)
// ...
return f(obj, foo)[0]


问:
Correctly using crypt() with SHA512 in PHP
All the examples online show the use of crypt like this:

```<code>$pass = crypt('something','$6$rounds=5000$anexamplestringforsalt$');
</code>```

But everyone says that you are not supposed to define the rounds or the salt.

So how should I use it?

Also I am having a problem: when I run the code above, it only runs 50 rounds instead of 5000 rounds as if the system is stopping it.

Any help will be greatly appreciated.

//- Solution -//

I have found some of these to be useful:

For generating Salt:

Here is a random way of generating salt

```<code>$randomString = random_bytes(32);
</code>```

Base 64 encode to ensure that some characters will not cause problems for crypt

```<code>$salt = base64_encode($randomString);
</code>```

For Hashing:

```<code>$hashed = crypt($passwordInput, '$6$'.$salt);
</code>```

To Confirm:

```<code>if (crypt($passwordInput, $hashed) == $hashed) {
  // Valid action
} else {
  // Invalid action
}
</code>```

** Special Thanks to @lathspell for help with arriving at above solution **

答:
Use OpenSSL for salt generation, it's even more random. And maybe 20000 rounds to future proof your code a bit.</p>

```<code>function cryptPassword($password, $salt = "", $rounds = 20000)
{
    if ($salt == "")
    {
        // Generate random salt
        $salt = substr(bin2hex(openssl_random_pseudo_bytes(16)),0,16);
    }
    // $6$ specifies SHA512
    $hash = crypt($password, sprintf('$6$rounds=%d$%s$', $rounds, $salt));

    return $hash;
}
</code>```

Body:
All the examples online show the use of crypt like this:

$pass = crypt('something','$6$rounds=5000$anexamplestringforsalt$');

But everyone says that you are not supposed to define the rounds or the salt.

So how should I use it?

Also I am having a problem: when I run the code above, it only runs 50 rounds instead of 5000 rounds as if the system is stopping it.

Any help will be greatly appreciated.

//- Solution -//

I have found some of these to be useful:

For generating Salt:

Here is a random way of generating salt

$randomString = random_bytes(32);

Base 64 encode to ensure that some characters will not cause problems for crypt

$salt = base64_encode($randomString);

For Hashing:

$hashed = crypt($passwordInput, '$6$'.$salt);

To Confirm:

if (crypt($passwordInput, $hashed) == $hashed) {
  // Valid action
} else {
  // Invalid action
}

** Special Thanks to @lathspell for help with arriving at above solution **

Body:
Use OpenSSL for salt generation, it's even more random. And maybe 20000 rounds to future proof your code a bit.

function cryptPassword($password, $salt = "", $rounds = 20000)
{
    if ($salt == "")
    {
        // Generate random salt
        $salt = substr(bin2hex(openssl_random_pseudo_bytes(16)),0,16);
    }
    // $6$ specifies SHA512
    $hash = crypt($password, sprintf('$6$rounds=%d$%s$', $rounds, $salt));

    return $hash;
}


问:
compile error = multipartentitybuilder() is not public cannot be accessed from outside package
can you help me find out what does the error below means? I don't know why I cannot access it outside the package, I mean what ACCESS SPECIFIER should I use?
 I tried using static and all specifiers but still I could not get rid of this error. I have been using it when the user takes a pic using the camera to upload the picture to the server.</p>

答:
It looks like the MultipartEntityBuilder doesn't have a public constructor. Look at the documentation:
https://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntityBuilder.html

You should create your object by static method create:

```<code>MultipartEntityBuilder entity = MultipartEntityBuilder.create()
</code>```

Body:
It looks like the MultipartEntityBuilder doesn't have a public constructor. Look at the documentation:
https://hc.apache.org/httpcomponents-client-ga/httpmime/apidocs/org/apache/http/entity/mime/MultipartEntityBuilder.html

You should create your object by static method create:

MultipartEntityBuilder entity = MultipartEntityBuilder.create()


问:
Make notification when app is closed
I have separate API for my Android app and I'm using Restful services for connecting my API. For now, I need to show notification even app is closed by the way of connecting my backend using the Restful method because all notification messages are, will get only the way of calling the API.
What is the correct implementation to solve this problem?</p>

答: You need to use FCM. It allows you to send push notifications to your app from your backend through google servers. </p>

Title: Make notification when app is closed


问:
How will I know when to create an interface?
I'm at a point in my development learning where I feel like I must learn more about interfaces.

I frequently read about them but it just seems like I cannot grasp them.

I've read examples like: Animal base class, with IAnimal interface for things like 'Walk', 'Run', 'GetLegs', etc - but I've never been working on something and felt like "Hey I should use an interface here!"

What am I missing? Why is it such a hard concept for me to grasp! I am just intimidated by the fact that I might not ever realize a concrete need for one - mostly due to some missing aspect of understanding them! It makes me feel like I'm missing something up top in terms of being a developer! If anyone has had an experience like this and had a breakthrough I would appreciate some tips on how to understand this concept. Thank you.

答:
It's entirely possible to go your whole life as a .net developer and never write your own interfaces. After all, we survived fine without them for decades and our languages were still Turing-complete.

I can't tell you why you need interfaces, but I can give you a list of where we use them in our current project:

In our plug-in model, we load plug-ins by interface and provide that interface to plug-in writers to conform to.

In our intermachine messaging system, the message classes all implement a specific interface and are "unwrapped" using the interface.

Our configuration management system defines an interface used to set and retrieve configuration settings.

We have one interface that we use to avoid a nasty circular reference problem. (Don't do this if you don't have to.)

I guess if there's a rule, it's to use interfaces when you want to group several classes within an is-a relationship, but you don't want to provide any implementation in the base class.

LastEditorDisplayName: ALassek

OwnerDisplayName: Jekke


问:
SQL Server Express CREATE DATABASE permission denied in database 'master'
After I change the option as UserInstance="False", then the error starts to happen.

Because I want to use full-text search, the option change is required. BUT, it stopped to work. Is there any way to make it work again?

I'm running Application Pool as Network Service with full control.

答:
After I performed the following instructions in SSMS, everything works fine:</p>

```<code>create login [IIS APPPOOL\MyWebAPP] from windows;

exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin
</code>```

Body:
After I performed the following instructions in SSMS, everything works fine:

create login [IIS APPPOOL\MyWebAPP] from windows;

exec sp_addsrvrolemember N'IIS APPPOOL\MyWebAPP', sysadmin


问:
Compare list of JSONArray in ArrayList
I have an ArrayList containing a list of JSONArrays

```<code>staffArray = new ArrayList<JSONArray>();
</code>```

the JSONArray is in a form of this:

```<code>[
    {
      "id": "k40dn-dff02-mm1",
      "name": "staff1",
      "tel": "0123456789",
    },
    {
      "id": "ch2mq-pmw01-ps6",
      "name": "staff2",
      "tel": "9876543210",
    }
    ...
]
</code>```

And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.

So far I have tried this to extract the string:

```<code>for(int i = 0; i < staffArray.size(); i++){
    JSONArray jsonArray = new JSONArray();
    jsonArray = staffArray.get(i);
    for(int j = 0; j < jsonArray.length(); j ++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            String id = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
</code>```

答:
If you would like to check for duplicate IDs in your ArrayList, you could do something like this:

```<code>ArrayList<JSONArray> staffArray = new ArrayList<>();

Set<String> ids = new HashSet<>();
for (JSONArray array : staffArray) {
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        if (!ids.add(obj.getString("id"))) {
            // duplicate IDs found, do something
        }
    }
}
</code>```

Title: Compare list of JSONArray in ArrayList

Body:
I have an ArrayList containing a list of JSONArrays

staffArray = new ArrayList<JSONArray>();

the JSONArray is in a form of this:

[
    {
      "id": "k40dn-dff02-mm1",
      "name": "staff1",
      "tel": "0123456789",
    },
    {
      "id": "ch2mq-pmw01-ps6",
      "name": "staff2",
      "tel": "9876543210",
    }
    ...
]

And the ArrayList will be containing different sizes of JSONArray.
Now I want to check in the ArrayList for each JSONArray, if they contain the same value for "id". So say that if the ArrayList has three different sizes of JSONArray, how can I tell the they each contain a JSONObject with the same value for "id" in it.

So far I have tried this to extract the string:

for(int i = 0; i < staffArray.size(); i++){
    JSONArray jsonArray = new JSONArray();
    jsonArray = staffArray.get(i);
    for(int j = 0; j < jsonArray.length(); j ++){
        JSONObject json = null;
        try {
            json = jsonArray.getJSONObject(j);
            String id = json.getString("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Body:
If you would like to check for duplicate IDs in your ArrayList, you could do something like this:

ArrayList<JSONArray> staffArray = new ArrayList<>();

Set<String> ids = new HashSet<>();
for (JSONArray array : staffArray) {
    for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
        if (!ids.add(obj.getString("id"))) {
            // duplicate IDs found, do something
        }
    }
}


问:
Find which element of the stream does not match the given predicate in allmatch
I want to find out which element is failing the predicate in case of allmatch.

```<code>List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);
</code>```

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

```<code>numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });
</code>```

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

答:
Try:

```<code>List<Integer> notMatchElements = numbers.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());
</code>```

If notMatchElements length equals 0 -> all match

Else -> you got not match elements

Body:
I want to find out which element is failing the predicate in case of allmatch.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean isEven = numbers.stream().allMatch(n-> n % 2 == 0);

Here isEven is false, as element 1 fails the predicate.

I can use forEach over the stream to find which element fails like:

numbers.stream().forEach(n -> {
            if (n % 2 != 0)
                System.out.println(n + "is Odd");
        });

Is there a way to figure out which elements fails the predicate in the allmatch when it returns false?

Body:
Try:

List<Integer> notMatchElements = numbers.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());

If notMatchElements length equals 0 -> all match

Else -> you got not match elements


问:
Using MSBuild with Hudson?
I am building a CI Server using Hudson to deploy .NET applications.  My problem is that it keeps throwing the error:

```<code>error MSB4019: The imported project
"C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications
\Microsoft.WebApplication.targets" was not found. Confirm that the path
 in the <Import> declaration is correct, and that the file exists on disk.
</code>```

Do I need to have VisualStudio installed on my CI server?

答: Just Install VS2010 in the hudson host machine.</p>

Title: Using MSBuild with Hudson?

Body:
I am building a CI Server using Hudson to deploy .NET applications.  My problem is that it keeps throwing the error:

error MSB4019: The imported project
"C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications
\Microsoft.WebApplication.targets" was not found. Confirm that the path
 in the <Import> declaration is correct, and that the file exists on disk.

Do I need to have VisualStudio installed on my CI server?


问:
Extract data from Graph API query in C#
I'm querying the Graph API on AAD for group membership information.  From this, I get back a JSON string containing one or more groups to which the user belongs.  I know I can reverse engineer a structure and de-serialize it, but are the Graph API structures available as some sort of contract that I can exploit?

I've found examples of queries against the Graph API that get the raw string data, but I could really use a simple example where someone extracts the raw information (e.g. the group ID or group name) and uses it in a structure.

答:
Create a  user class as below

```<code>public class ActiveDirectoryUser
    {
        public bool accountEnabled { get; set; }
        public List<SignInName> signInNames { get; set; }
        public string creationType { get; set; }
        public string displayName { get; set; }
        public string mailNickname { get; set; }

        [JsonProperty("passwordProfile", NullValueHandling = NullValueHandling.Ignore)]
        public PasswordProfile PasswordProfile { get; set; }

        [JsonProperty("passwordPolicies", NullValueHandling = NullValueHandling.Ignore)]
        public string PasswordPolicies { get; set; }

        public string city { get; set; }
        public object country { get; set; }
        public object facsimileTelephoneNumber { get; set; }
        public string givenName { get; set; }
        public object mail { get; set; }
        public object mobile { get; set; }
        //public List<object> otherMails { get; set; }
        public string postalCode { get; set; }
        public object preferredLanguage { get; set; }
        public string state { get; set; }
        public object streetAddress { get; set; }
        public string surname { get; set; }
        public Guid objectId { get; set; }
        public object telephoneNumber { get; set; }

    }

    public class SignInName
    {
        public string type { get; set; }
        public string value { get; set; }
    }

    public class PasswordProfile
    {
        public string password { get; set; }
        public bool forceChangePasswordNextLogin { get; set; }
    }
</code>```

When getting the response from AD, use newtonsoft.json to  serialize to the corresponding class as below.

```<code>var response = await httpClient.SendAsync(request);

if (response.IsSuccessStatusCode)
{
   var result = response.Content.ReadAsStringAsync().Result;
   return JsonConvert.DeserializeObject<ActiveDirectoryUser>(result);
}
</code>```

Trick is JsonConvert.DeserializeObject<>(result);

Title: Extract data from Graph API query in C#

Body:
Create a  user class as below

public class ActiveDirectoryUser
    {
        public bool accountEnabled { get; set; }
        public List<SignInName> signInNames { get; set; }
        public string creationType { get; set; }
        public string displayName { get; set; }
        public string mailNickname { get; set; }

        [JsonProperty("passwordProfile", NullValueHandling = NullValueHandling.Ignore)]
        public PasswordProfile PasswordProfile { get; set; }

        [JsonProperty("passwordPolicies", NullValueHandling = NullValueHandling.Ignore)]
        public string PasswordPolicies { get; set; }

        public string city { get; set; }
        public object country { get; set; }
        public object facsimileTelephoneNumber { get; set; }
        public string givenName { get; set; }
        public object mail { get; set; }
        public object mobile { get; set; }
        //public List<object> otherMails { get; set; }
        public string postalCode { get; set; }
        public object preferredLanguage { get; set; }
        public string state { get; set; }
        public object streetAddress { get; set; }
        public string surname { get; set; }
        public Guid objectId { get; set; }
        public object telephoneNumber { get; set; }

    }

    public class SignInName
    {
        public string type { get; set; }
        public string value { get; set; }
    }

    public class PasswordProfile
    {
        public string password { get; set; }
        public bool forceChangePasswordNextLogin { get; set; }
    }

When getting the response from AD, use newtonsoft.json to  serialize to the corresponding class as below.

var response = await httpClient.SendAsync(request);

if (response.IsSuccessStatusCode)
{
   var result = response.Content.ReadAsStringAsync().Result;
   return JsonConvert.DeserializeObject<ActiveDirectoryUser>(result);
}

Trick is JsonConvert.DeserializeObject<>(result);


问:
Swift: How can I use synchronized thread for Alamofire?
I want to use synchronized thread using Alamofire.

I am using like this code for synchronization.

```<code>    let queue1 = DispatchQueue(label: "queue1")
    let queue2 = DispatchQueue(label: "queue2")
    queue1.async {
        self.dataFromServer.getData()
    }
    queue2.async {
        //check if success to get the data from server
        while(!self.dataFromServer.resultData){}

        DispatchQueue.main.async {
            // do something on screen
        }
    }
</code>```

...

```<code>   func getData() {
        Alamofire.request(url).responseJSON { response in
           if response.error == nil {
            // get data
            self.resultData = true
           }else{
            // error
           }
        }
   }
</code>```

I want to do something after get data from server using Alamofire.
Is this correct?
If this is not good, please tell me about the synchronization please.
Kind regards.

答:
Modify the getData() function to return block so that you get callback on the sucess of the api call

```<code>func getData(sucess:((Void) -> Void)?) {
Alamofire.request(url).responseJSON { response in
           if response.error == nil {
            // get data
            sucess!()
            self.resultData = true
           }else{
            // error
           }
        }
}
</code>```

Do whatever you want to do after the api response has received in the sucess callback of the getData() function

Body:
I want to use synchronized thread using Alamofire.

I am using like this code for synchronization.

    let queue1 = DispatchQueue(label: "queue1")
    let queue2 = DispatchQueue(label: "queue2")
    queue1.async {
        self.dataFromServer.getData()
    }
    queue2.async {
        //check if success to get the data from server
        while(!self.dataFromServer.resultData){}

        DispatchQueue.main.async {
            // do something on screen
        }
    }

...

   func getData() {
        Alamofire.request(url).responseJSON { response in
           if response.error == nil {
            // get data
            self.resultData = true
           }else{
            // error
           }
        }
   }

I want to do something after get data from server using Alamofire.
Is this correct?
If this is not good, please tell me about the synchronization please.
Kind regards.

Body:
Modify the getData() function to return block so that you get callback on the sucess of the api call

func getData(sucess:((Void) -> Void)?) {
Alamofire.request(url).responseJSON { response in
           if response.error == nil {
            // get data
            sucess!()
            self.resultData = true
           }else{
            // error
           }
        }
}

Do whatever you want to do after the api response has received in the sucess callback of the getData() function


问:
Merging Two HashTable with removal of duplicates in java
I am having two Hashtables with <int,string> pair. Now they both have duplicate values in each of them, and I want to merge both the hashtables to give me distinct values. How can I do that!?

thanks
Edit #1 I am reading file contents from a directory. and storing those contents as tokens in two different hashtables. Now I need to merge them into a single hashtable which would give me distinct values of both the tables.

答:
You can use the putAll method of Hashtable to merge two hashtables. The hashtable passed as an argument will overwrite duplicates in the original hashtable.

I didn't get how two hashtables can be merged and still have distinct values. If you want to remove duplicate items from one hashtable (and leave them in the second hashtable) just do as suggested in another answer, but without adding non-duplicate items to map2. After that you will have the first table unmodified and the second with entries which aren't in map1.

Another solution is to merge two hashtables using putAll and clear the second hashtable :)


问:
Neo4j/Cypher: Match on dynamic property
According to the developer manual section 3.2.4 on Parameters:

Parameters cannot be used for the following constructs, as these form part of the >query structure that is compiled into a query plan:

property keys; so, MATCH (n) WHERE n.$param = 'something' is invalid (source)

Is there no way around this (c#, using the official driver)? I have a case where a node of a particular type can contain from a few up to hundreds of properties, and I want the users to be able to search for any of these without having to write all possible queries in advance. Ideally I'd like to be able to do something similar to

```<code>MATCH (a) WHERE ({prop} CONTAINS {val}) RETURN a
</code>```

supplying a dictionary where prop: "a.Description" and val: "Freeform item description"

Is this at all possible, or is string concatenation (with related drawbacks) the only possibility here?

答:
@cybersam's response is one way of getting the result, but as InverseFalcon said - you lose indexing performance - assuming you're planning on making the query a bit more detailed than just the example.

You don't need to write hundreds of queries (1 for each property), surely this is just a job for string.Format?  That way you get around the concat issue of string, and you can use indexing properly.

Something like:

```<code>const string QueryFormat = "MATCH (a) WHERE (a.{0} CONTAINS {{val}})";
</code>```

which you'd use like:

```<code>string.Format(QueryFormat, "Description");
</code>```

So...

```<code>session.Run(string.Format(QueryFormat, "Description"), /*params object here*/);
</code>```

Presumably you've already provided a list of properties for a user to select from, so it makes sense just to pass that in with the parameters. string.Format doesn't have the issues that concat does so performance wise it'll be better in the long run as you can use the indexing on Neo4j when you get to it.

Title: Neo4j/Cypher: Match on dynamic property

Body:
According to the developer manual section 3.2.4 on Parameters:

Parameters cannot be used for the following constructs, as these form part of the >query structure that is compiled into a query plan:

property keys; so, MATCH (n) WHERE n.$param = 'something' is invalid (source)

Is there no way around this (c#, using the official driver)? I have a case where a node of a particular type can contain from a few up to hundreds of properties, and I want the users to be able to search for any of these without having to write all possible queries in advance. Ideally I'd like to be able to do something similar to

MATCH (a) WHERE ({prop} CONTAINS {val}) RETURN a

supplying a dictionary where prop: "a.Description" and val: "Freeform item description"

Is this at all possible, or is string concatenation (with related drawbacks) the only possibility here?

Body:
@cybersam's response is one way of getting the result, but as InverseFalcon said - you lose indexing performance - assuming you're planning on making the query a bit more detailed than just the example.

You don't need to write hundreds of queries (1 for each property), surely this is just a job for string.Format?  That way you get around the concat issue of string, and you can use indexing properly.

Something like:

const string QueryFormat = "MATCH (a) WHERE (a.{0} CONTAINS {{val}})";

which you'd use like:

string.Format(QueryFormat, "Description");

So...

session.Run(string.Format(QueryFormat, "Description"), /*params object here*/);

Presumably you've already provided a list of properties for a user to select from, so it makes sense just to pass that in with the parameters. string.Format doesn't have the issues that concat does so performance wise it'll be better in the long run as you can use the indexing on Neo4j when you get to it.


问:
Array initialization with error LNK2001: unresolved external symbol _memset
Compiler: VC2013

I have an array as below:

```<code>typedef char CHAR8;
CHAR8 buffer[HEX_DUMP_BUFFER_LENGTH];
</code>```

With below code, I get an error LNK2001: unresolved external symbol _memset

```<code>for (i = 0; i < HEX_DUMP_BUFFER_LENGTH; i++){
    buffer[i] = 'a';
}
</code>```

But with manual assignment to an array element, there's no link error.

```<code>buffer[0] = 'a';
</code>```

Why?

答:
For some performance reason, the compiler will optimize your code.
You can disassemble your binary file to find out if the compiler has done it.
And you can adjust the compile flag, optimize level, or link the lib for the symbol of _memset.</p>

Body:
Compiler: VC2013

I have an array as below:

typedef char CHAR8;
CHAR8 buffer[HEX_DUMP_BUFFER_LENGTH];

With below code, I get an error LNK2001: unresolved external symbol _memset

for (i = 0; i < HEX_DUMP_BUFFER_LENGTH; i++){
    buffer[i] = 'a';
}

But with manual assignment to an array element, there's no link error.

buffer[0] = 'a';

Why?