问:
How to make select option field using laravel and axios jquery
I had one database json value

```<code>$fos = ToFieldOfStudy::where('parent_id', -1)->get();
return response()->json($fos);
</code>```

MyJson ouput :

```<code>[{
    "id": 7,
    "value": "Business Administration",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 8,
    "value": "Engineering",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 9,
    "value": "Medical",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 10,
    "value": "Medicine",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 12,
    "value": "Accountancy",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 13,
    "value": "Actuarial Science",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 14,
    "value": "Administrative Office Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 15,
    "value": "Aging Studies",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 16,
    "value": "Agriculture",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 17,
    "value": "Air-Conditioning & `Refrigeration",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 18,
    "value": "Aircraft Maintenance Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 19,
    "value": "American Sign Language",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 20,
    "value": "American Studies",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 21,
    "value": "Animation Engineeering",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 22,
    "value": "Applied Geography",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 23,
    "value": "Architectural / Construction Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 24,
    "value": "Architecture",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 25,
    "value": "Art Education",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 26,
    "value": "Art History",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 27,
    "value": "Arts",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 28,
    "value": "Auto Body Repair",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 29,
    "value": "Automatic / Manual Transmission",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 30,
    "value": "Automotive Air-Conditioning Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 31,
    "value": "Automotive Electrical Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 32,
    "value": "Automotive Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 33,
    "value": "Aviation Airframe Structure / Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 34,
    "value": "Aviation Powerplant Theory / Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 35,
    "value": "Aviation Systems",
    "parent_id": -1,
    "is_active": 1
}]
</code>```

in my view.blade.php file i tried code like this :

$(document).on('change', '[name="field_of_study[]"]', function () {
       url = "{{route('getfieldofstudy')}}";
       const data = {
           'fos' : $(this).val()
       }
       $(this).parent('.input-group').nextAll('div.input-group').remove();
       axios.post(url, data).then(response =>{
           var sel = '<select class="form-control input-sm" name="field_of_study[]">';
           var opt = [];
           if (!$.isEmptyObject(response)) {
               $.each(response, function (key, value) {
                   opt.push('<option value="' + key + '">' + value + '</option>');
               });
           }
           if (opt.length > 1) {
               sel += opt.join() + '</select>';
               $('.fos').append('
' + sel + '
');
           }
       }, 'json');
   });
  //  /*----------Field of Study end----------------*/
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

anyone tell what am doing wrong..? that selection box shows but values are not displaying.

答:
The wanted Json is wrraped inside the data on the response object :

```<code>$(document).on('change', '[name="field_of_study[]"]', function () {
       url = "{{route('getfieldofstudy')}}";
       const data = {
           'fos' : $(this).val()
       }
       $(this).parent('.input-group').nextAll('div.input-group').remove();
       $('#field_of_study').remove();
       axios.post(url, data).then(response =>{
           var sel = '<select class="form-control input-sm" id="field_of_study" name="field_of_study[]">';
           var opt = [];
           if (!$.isEmptyObject(response.data)) {
               $.each(response.data, function (key, value) {
                   opt.push('<option value="' + key + '">' + value + '</option>');
               });
           }
           if (opt.length > 1) {
               sel += opt.join() + '</select>';
               $('.fos').append('<div class="col-lg-12 col-md-12 input-group pad-top5">' + sel + '</div>');
           }
       }, 'json');
   });
  //  /*----------Field of Study end----------------*/
});
</code>```

Body:
I had one database json value

$fos = ToFieldOfStudy::where('parent_id', -1)->get();
return response()->json($fos);

MyJson ouput :

[{
    "id": 7,
    "value": "Business Administration",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 8,
    "value": "Engineering",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 9,
    "value": "Medical",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 10,
    "value": "Medicine",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 12,
    "value": "Accountancy",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 13,
    "value": "Actuarial Science",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 14,
    "value": "Administrative Office Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 15,
    "value": "Aging Studies",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 16,
    "value": "Agriculture",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 17,
    "value": "Air-Conditioning & `Refrigeration",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 18,
    "value": "Aircraft Maintenance Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 19,
    "value": "American Sign Language",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 20,
    "value": "American Studies",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 21,
    "value": "Animation Engineeering",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 22,
    "value": "Applied Geography",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 23,
    "value": "Architectural / Construction Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 24,
    "value": "Architecture",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 25,
    "value": "Art Education",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 26,
    "value": "Art History",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 27,
    "value": "Arts",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 28,
    "value": "Auto Body Repair",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 29,
    "value": "Automatic / Manual Transmission",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 30,
    "value": "Automotive Air-Conditioning Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 31,
    "value": "Automotive Electrical Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 32,
    "value": "Automotive Technology",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 33,
    "value": "Aviation Airframe Structure / Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 34,
    "value": "Aviation Powerplant Theory / Systems",
    "parent_id": -1,
    "is_active": 1
}, {
    "id": 35,
    "value": "Aviation Systems",
    "parent_id": -1,
    "is_active": 1
}]

in my view.blade.php file i tried code like this :

$(document).on('change', '[name="field_of_study[]"]', function () {
       url = "{{route('getfieldofstudy')}}";
       const data = {
           'fos' : $(this).val()
       }
       $(this).parent('.input-group').nextAll('div.input-group').remove();
       axios.post(url, data).then(response =>{
           var sel = '<select class="form-control input-sm" name="field_of_study[]">';
           var opt = [];
           if (!$.isEmptyObject(response)) {
               $.each(response, function (key, value) {
                   opt.push('<option value="' + key + '">' + value + '</option>');
               });
           }
           if (opt.length > 1) {
               sel += opt.join() + '</select>';
               $('.fos').append('
' + sel + '
');
           }
       }, 'json');
   });
  //  /*----------Field of Study end----------------*/
});

anyone tell what am doing wrong..? that selection box shows but values are not displaying.

Body:
The wanted Json is wrraped inside the data on the response object :

$(document).on('change', '[name="field_of_study[]"]', function () {
       url = "{{route('getfieldofstudy')}}";
       const data = {
           'fos' : $(this).val()
       }
       $(this).parent('.input-group').nextAll('div.input-group').remove();
       $('#field_of_study').remove();
       axios.post(url, data).then(response =>{
           var sel = '<select class="form-control input-sm" id="field_of_study" name="field_of_study[]">';
           var opt = [];
           if (!$.isEmptyObject(response.data)) {
               $.each(response.data, function (key, value) {
                   opt.push('<option value="' + key + '">' + value + '</option>');
               });
           }
           if (opt.length > 1) {
               sel += opt.join() + '</select>';
               $('.fos').append('<div class="col-lg-12 col-md-12 input-group pad-top5">' + sel + '</div>');
           }
       }, 'json');
   });
  //  /*----------Field of Study end----------------*/
});


来源: stackexchange

问:
What is meant by a transport independent/dependent protocol?
I am a beginner in web services and network protocols. I have come across a term called "transport independent" as in "SOAP is known as a transport-independent messaging protocol".

I googled a lot of sites, but I could not find an appropriate explanation for the same ? Could anyone explain me what the term means ?

Thanks in advance..

答:
The transport layer of a protocol stack is the layer that deals with the transfer of information between processes, often on different computers.

Common transport protocols used on the web are HTTP, HTTPS, FTP, SMTP etc.

Many of these transport protocols have features built in such as security, compression, encryption etc.

SOAP has been implemented to have all the required features built-in in a self contained way. So although there are bindings for SOAP over HTTP, it is not a requirement that SOAP has to use HTTP.

In other words SOAP is a transport-independent messaging protocol

ContentLicense: CC BY-SA 3.0


问:
swift3，my timer can't stop. why?
this is i seting a timer function, the code like this:

```<code>@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}
</code>```

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!

答:
I think you didn't set timer value

```<code>timer = Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
</code>```

Title: swift3，my timer can't stop. why?

Body:
this is i seting a timer function, the code like this:

@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!

Body:
I think you didn't set timer value

timer = Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)


问:
Unable to download .gz file with requests module
How do I properly download a .gz file? My code goes below:

```<code>import requests
response = requests.get('https://www.propertyshark.com/sitemap/CA-San-Bernardino-reports_1.xml.gz', headers=headers)
    print(response.status_code)
    if response.status_code == 200:
        print('Downloading...')
        file_name = 'file.xml.gz'
</code>```

It does download gz file but it's corrupted - only 1KB in size and when I try to unzip it adds .gz.cpgz in the file name.

答:
I tried running your code and got the following error page. You seem to need to manipulate headless browsers such as Headless chrome via selenium. The Requests module applies to the condition of Bot mentioned on this error page.

```<code>import requests

res = requests.get("https://www.propertyshark.com/sitemap/CA-San-Bernardino-reports_1.xml.gz")
print(res.text)
</code>```

Body:
How do I properly download a .gz file? My code goes below:

import requests
response = requests.get('https://www.propertyshark.com/sitemap/CA-San-Bernardino-reports_1.xml.gz', headers=headers)
    print(response.status_code)
    if response.status_code == 200:
        print('Downloading...')
        file_name = 'file.xml.gz'

It does download gz file but it's corrupted - only 1KB in size and when I try to unzip it adds .gz.cpgz in the file name.

Body:
I tried running your code and got the following error page. You seem to need to manipulate headless browsers such as Headless chrome via selenium. The Requests module applies to the condition of Bot mentioned on this error page.

import requests

res = requests.get("https://www.propertyshark.com/sitemap/CA-San-Bernardino-reports_1.xml.gz")
print(res.text)


问:
.Net dynamic list conversion
I have to do a comparison of 2 lists. The problem is that I don't know of what type the field inside the list are, they can be int, string, decimal, enums or even other objects.

I will know the type only on runtime. I was thinking of creating a list of object and cast them to object the problem is that let's say I have a List<int> and I'm trying to cast it to object it fails.

Another problem is that  I know there is a list only on runtime. so on runtime I need to transform the variable of type object to a list.

How can I cast that object to List and how can I cast it to let's say list of objects?

Update:

I have and object and by reflection I'm getting the the property of it with

```<code>var oldProperty = property.GetValue(old);
var newProperty = property.GetValue(new);
</code>```

Once I have the properties values and I can see it's a list I will need to compare those 2. Let's say oldProperty is of type List
I've tried to do something like:

```<code>var myOldList = (List<object>)oldProperty;
</code>```

If the cast fails with

```<code>Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.Collections.Generic.List`1[System.Object]'
</code>```

Here you have a look of the function i;m trying to create. Please don't mind of null objects(is not in the scope)

```<code> public void SetDifference(object first, object second)
    {
        var properties = first.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            var oldValue = property.GetValue(first);
            var newValue = property.GetValue(second);
            if (Convert.GetTypeCode(newValue) != TypeCode.Object)
            {
                if (!oldValue.Equals(newValue))
                {
                    result.AddDifference(new PrimitiveComparison()
                    {
                        BeforeValue = oldValue.ToString(),
                        AfterValue = newValue.ToString(),
                        PropertyName = property.Name
                    });
                }
            }
            else
            {
                if (property.PropertyType.Name.Contains("List"))
                {
                    // here fails with the error from above
                    var oldList = (List<object>)oldValue;
                    var newList = (List<object>)newValue;
                    if (oldList.Count != newList.Count)
                    {
                        result.AddDifference(new PrimitiveComparison()
                        {
                            BeforeValue = oldList.Count.ToString(),
                            AfterValue = newList.Count.ToString(),
                            PropertyName = property.Name + "Count"
                        });
                    }
                    // add the list differences
                    result.AddDifference(SetListDifference(oldList, newList);
                }
                else
                {
                    var diffrence = SetDifference(oldValue, newValue);
                    if (!diffrence.areEqual)
                    {
                        result.AddDifference(diffrence);
                    }
                }

            }
        }

}
</code>```

答:
once you do conversion of you list than you can check both the list have same element or not by using except method of linq, to find both are equal or not

```<code>double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };

IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
if(onlyInFirstSet.Count() ==0)
 Console.WriteLine("equal");
</code>```

for primitive type this works fine but for user defined type you need compare implementation.

Check this blog post for comparing list of two different type : Difference between list of user defined types

If you are aware that is going to be IEnumerable type than you can try

```<code> List<object> objlst = (value as IEnumerable<object>).Cast<object>
    ().ToList()
</code>```

you can try like this

```<code>Type t = typeof(obj);

if (t == typeof(List<int>)) {
    var lst= (List<int>)obj;

} else if (t == typeof(List<string>)) {
    var lst = (List<string>)obj;
} else if (t == typeof(List<decimal>)) {
    var lst = (List<decimal>)obj;
}
else if (t == typeof(List<EnumName>)) {
    var lst = (List<EnumName>)obj;
}
</code>```

Title: .Net dynamic list conversion

Body:
I have to do a comparison of 2 lists. The problem is that I don't know of what type the field inside the list are, they can be int, string, decimal, enums or even other objects.

I will know the type only on runtime. I was thinking of creating a list of object and cast them to object the problem is that let's say I have a List<int> and I'm trying to cast it to object it fails.

Another problem is that  I know there is a list only on runtime. so on runtime I need to transform the variable of type object to a list.

How can I cast that object to List and how can I cast it to let's say list of objects?

Update:

I have and object and by reflection I'm getting the the property of it with

var oldProperty = property.GetValue(old);
var newProperty = property.GetValue(new);

Once I have the properties values and I can see it's a list I will need to compare those 2. Let's say oldProperty is of type List
I've tried to do something like:

var myOldList = (List<object>)oldProperty;

If the cast fails with

Unable to cast object of type 'System.Collections.Generic.List`1[System.Int32]' to type 'System.Collections.Generic.List`1[System.Object]'

Here you have a look of the function i;m trying to create. Please don't mind of null objects(is not in the scope)

 public void SetDifference(object first, object second)
    {
        var properties = first.GetType().GetProperties();
        foreach (PropertyInfo property in properties)
        {
            var oldValue = property.GetValue(first);
            var newValue = property.GetValue(second);
            if (Convert.GetTypeCode(newValue) != TypeCode.Object)
            {
                if (!oldValue.Equals(newValue))
                {
                    result.AddDifference(new PrimitiveComparison()
                    {
                        BeforeValue = oldValue.ToString(),
                        AfterValue = newValue.ToString(),
                        PropertyName = property.Name
                    });
                }
            }
            else
            {
                if (property.PropertyType.Name.Contains("List"))
                {
                    // here fails with the error from above
                    var oldList = (List<object>)oldValue;
                    var newList = (List<object>)newValue;
                    if (oldList.Count != newList.Count)
                    {
                        result.AddDifference(new PrimitiveComparison()
                        {
                            BeforeValue = oldList.Count.ToString(),
                            AfterValue = newList.Count.ToString(),
                            PropertyName = property.Name + "Count"
                        });
                    }
                    // add the list differences
                    result.AddDifference(SetListDifference(oldList, newList);
                }
                else
                {
                    var diffrence = SetDifference(oldValue, newValue);
                    if (!diffrence.areEqual)
                    {
                        result.AddDifference(diffrence);
                    }
                }

            }
        }

}

Body:
once you do conversion of you list than you can check both the list have same element or not by using except method of linq, to find both are equal or not

double[] numbers1 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };
double[] numbers2 = { 2.0, 2.1, 2.2, 2.3, 2.4, 2.5 };

IEnumerable<double> onlyInFirstSet = numbers1.Except(numbers2);
if(onlyInFirstSet.Count() ==0)
 Console.WriteLine("equal");

for primitive type this works fine but for user defined type you need compare implementation.

Check this blog post for comparing list of two different type : Difference between list of user defined types

If you are aware that is going to be IEnumerable type than you can try

 List<object> objlst = (value as IEnumerable<object>).Cast<object>
    ().ToList()

you can try like this

Type t = typeof(obj);

if (t == typeof(List<int>)) {
    var lst= (List<int>)obj;

} else if (t == typeof(List<string>)) {
    var lst = (List<string>)obj;
} else if (t == typeof(List<decimal>)) {
    var lst = (List<decimal>)obj;
}
else if (t == typeof(List<EnumName>)) {
    var lst = (List<EnumName>)obj;
}


问:
How can new clojure libraries be loaded in the repl
So I have this workflow problem:

I'm happily typing away on my clojure project repl and realise that i need another library that is not in my project.clj, say in this case, i needed the tools.cli library.

I open up project.clj in my editor and add in an entry to the :dependencies

```<code>     [org.clojure/tools.cli "0.2.1"]
</code>```

Then, within the project directory, I type lein deps in the shell to pull in the necessary libraries

After the project dependencies are pulled, technically all the class files are already there ready to be loaded, but if I go back to my repl and type:

```<code>> (use 'tools.cli)
</code>```

I get this:

```<code>=>> FileNotFoundException Could not locate tools/cli__init.class
  or tools/cli.clj on classpath:   clojure.lang.RT.load (RT.java:432)
</code>```

So I would have to restart my repl, wasting a whole heap of time reconfiguring the state of the repl to where I was before I needed the library.

Is there a way to just load in the library dynamically? eg, after I run lein deps I just go back to the repl and type:

```<code>> (load-library "tools.cli")
> (use 'tools.cli)
</code>```

Thanks in advance

答:
You can try out one library in the repl using lein-try.

~/.lein/profiles.clj:

{:user {:plugins [[lein-try "0.4.3"]]}}

command line:

```<code>$ lein try clj-time "0.5.1"
Fetching dependencies... (takes a while the first time)
lein-try loaded [clj-time "0.5.1"]

nREPL server started on port 57036
REPL-y 0.2.0
Clojure 1.5.1
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)

user=>
</code>```

Body:
So I have this workflow problem:

I'm happily typing away on my clojure project repl and realise that i need another library that is not in my project.clj, say in this case, i needed the tools.cli library.

I open up project.clj in my editor and add in an entry to the :dependencies

     [org.clojure/tools.cli "0.2.1"]

Then, within the project directory, I type lein deps in the shell to pull in the necessary libraries

After the project dependencies are pulled, technically all the class files are already there ready to be loaded, but if I go back to my repl and type:

> (use 'tools.cli)

I get this:

=>> FileNotFoundException Could not locate tools/cli__init.class
  or tools/cli.clj on classpath:   clojure.lang.RT.load (RT.java:432)

So I would have to restart my repl, wasting a whole heap of time reconfiguring the state of the repl to where I was before I needed the library.

Is there a way to just load in the library dynamically? eg, after I run lein deps I just go back to the repl and type:

> (load-library "tools.cli")
> (use 'tools.cli)

Thanks in advance

Body:
You can try out one library in the repl using lein-try.

~/.lein/profiles.clj:

{:user {:plugins [[lein-try "0.4.3"]]}}

command line:

$ lein try clj-time "0.5.1"
Fetching dependencies... (takes a while the first time)
lein-try loaded [clj-time "0.5.1"]

nREPL server started on port 57036
REPL-y 0.2.0
Clojure 1.5.1
    Docs: (doc function-name-here)
          (find-doc "part-of-name-here")
  Source: (source function-name-here)
 Javadoc: (javadoc java-object-or-class-here)
    Exit: Control+D or (exit) or (quit)

user=>


问:
how to block UI during data fetching in windows form c#
```<code>this.Enabled = false;
LoadAllQCDetails();
this.Enabled = true;
</code>```

LoadAllQCDetails(): this is method takes upto 40 sec; during this time if user click button multiple times (even though this.Enabled = false)  after this.Enabled = true it will execute all click events, I need to block all click events during this time

答:
you can use a task to prevent UI blocking such as the following:</p>

```<code> await System.Threading.Tasks.Task.Run(() => LoadData());

 private async System.Threading.Tasks.Task LoadData()
    {
      LoadAllQCDetails();
      btn.Enabled = true;
    }
</code>```

Body:
this.Enabled = false;
LoadAllQCDetails();
this.Enabled = true;

LoadAllQCDetails(): this is method takes upto 40 sec; during this time if user click button multiple times (even though this.Enabled = false)  after this.Enabled = true it will execute all click events, I need to block all click events during this time

Body:
you can use a task to prevent UI blocking such as the following:

 await System.Threading.Tasks.Task.Run(() => LoadData());

 private async System.Threading.Tasks.Task LoadData()
    {
      LoadAllQCDetails();
      btn.Enabled = true;
    }


问:
$(find) not working consistently
I have a search box on a website that uses an AJAX extender with a webservice.
It works perfectly on the home page.
http://www.as-technology.co.uk.

I have the same control on a subsection page at
https://www.as-technology.co.uk/toner-cartridges/printer/brother

This is the exact same control, but the page is one level lower in the file hierarchy(not in the root folder but a sub folder).

I have narrowed down the problem to do with the $(find) javascript function as in the second webpage it can't find the AJAX extender called "dp1". In the first page example(default page) it does.

The javascript function called UpdateControl

```<code><script type="text/javascript">
function UpdateControl(value) {
    var behavior = $find('dp1');
    if (behavior) {
        behavior.populate(value);
    }
    return false;
}
function ClearSearch() {
    var lbl = $(this).find('lblSearchResults');
    lbl.value = "";
    return false;
}
</code>```

 On the second page the var "behaviour" is null and so the populate doesn't work.

The control's code is this.

```<code> <%@ Control Language="C#" AutoEventWireup="true"
    CodeFile="SearchBoxWithService.ascx.cs"
    Inherits="MB.ASTechnology.UI.Controls.SearchBoxWithService" %>
    <%@ Import Namespace="MB.ASTechnology.UI" %>

    <script type="text/javascript">
    function UpdateControl(value) {
        var behavior = $find('dp1');
        if (behavior) {
            behavior.populate(value);
        }
        return false;
    }
    function ClearSearch() {
        var lbl = $find('lblSearchResults');
        lbl.value = "";
        return false;
    }
     </script>

    <asp:Panel ID="Panel1" runat="server" DefaultButton="btnGetHtml"
    style="float:left;" >

    <div class="input-append">
        <input class="span2" id="txtGetHtml" type="text"  placeholder="Brand & printer model or cartridge code" style="width: 250px;height:35px;"  />
        <asp:Button  CssClass="btn btn-primary" ID="btnGetHtml" UseSubmitBehavior="true"  runat="server" OnClientClick="return UpdateControl(txtGetHtml.value)" Text="Search" />
        <asp:Button  CssClass="btn btn-default" ID="btnClearSearch" UseSubmitBehavior="true"  runat="server" OnClientClick="return ClearSearch" Text="Clear" />
    </div>

    <asp:Button  CssClass="btn" ID="Button1" UseSubmitBehavior="true"  runat="server"  Text="Search" visible="false"/>
</asp:Panel>
<asp:Label ID="lblSearchResults" runat="server" Text=""></asp:Label>
<ajaxToolkit:DynamicPopulateExtender ID="dp1" runat="server" BehaviorID="dp1"
    TargetControlID="lblSearchResults" ServicePath="~/TextSearchService.asmx" ServiceMethod="DynamicPopulateMethod"
    ClearContentsDuringUpdate="true" PopulateTriggerControlID="Button1">
</ajaxToolkit:DynamicPopulateExtender>
</code>```

答:
I used a slideshow extender and it worked basically like this:

```<code>$find('behaviorID')._contextKey = value;
</code>```

I think most extenders work the same, so it would be something like:

```<code>function UpdateControl(value) {
    var behavior = $find('dp1');
    if (behavior) {
        behavior._contextKey = value;
    }
    return false;
}
</code>```

hth.

Title: $(find) not working consistently

Body:
I have a search box on a website that uses an AJAX extender with a webservice.
It works perfectly on the home page.
http://www.as-technology.co.uk.

I have the same control on a subsection page at
https://www.as-technology.co.uk/toner-cartridges/printer/brother

This is the exact same control, but the page is one level lower in the file hierarchy(not in the root folder but a sub folder).

I have narrowed down the problem to do with the $(find) javascript function as in the second webpage it can't find the AJAX extender called "dp1". In the first page example(default page) it does.

The javascript function called UpdateControl

    <asp:Panel ID="Panel1" runat="server" DefaultButton="btnGetHtml"
    style="float:left;" >

        <input class="span2" id="txtGetHtml" type="text"  placeholder="Brand & printer model or cartridge code" style="width: 250px;height:35px;"  />
        <asp:Button  CssClass="btn btn-primary" ID="btnGetHtml" UseSubmitBehavior="true"  runat="server" OnClientClick="return UpdateControl(txtGetHtml.value)" Text="Search" />
        <asp:Button  CssClass="btn btn-default" ID="btnClearSearch" UseSubmitBehavior="true"  runat="server" OnClientClick="return ClearSearch" Text="Clear" />

    <asp:Button  CssClass="btn" ID="Button1" UseSubmitBehavior="true"  runat="server"  Text="Search" visible="false"/>
</asp:Panel>
<asp:Label ID="lblSearchResults" runat="server" Text=""></asp:Label>
<ajaxToolkit:DynamicPopulateExtender ID="dp1" runat="server" BehaviorID="dp1"
    TargetControlID="lblSearchResults" ServicePath="~/TextSearchService.asmx" ServiceMethod="DynamicPopulateMethod"
    ClearContentsDuringUpdate="true" PopulateTriggerControlID="Button1">
</ajaxToolkit:DynamicPopulateExtender>

Body:
I used a slideshow extender and it worked basically like this:

$find('behaviorID')._contextKey = value;

I think most extenders work the same, so it would be something like:

function UpdateControl(value) {
    var behavior = $find('dp1');
    if (behavior) {
        behavior._contextKey = value;
    }
    return false;
}

hth.


问:
Get Value From 'param' Of 'views.py' In Javascript Django
In views.py

```<code>def website(request, pk=None):
if not model_utils.check_admin_permission(request):
    return loginAndContinuosRequest(request)

if pk:
    obj = get_object_or_404(Website, pk = pk)
    form = WebsiteForm(instance=obj)
    fields = obj.get_manage_payment_accounts()
else:
    obj = None
    form = WebsiteForm()
    fields = []

if request.POST:
    if pk:
        form = WebsiteForm(request.POST, request.FILES, instance=obj)
    else:
        form = WebsiteForm(request.POST, request.FILES)

    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("views_manage_websites"))

params = {
    'obj':obj ,
    'form':form,
    'fields': fields,
    'test': 'test',
}

return render(request, TEMPLATE_PATH + 'website.html', params)
</code>```

In script in template (.html),

```<code><script>

    $(document).ready(function() {
        alert({{ obj.id }}); //(1)
        alert({{ obj.pk }}); //(2)
        alert({{ obj.site_name }}); //(3)
        alert ({{ test }}); //(4)
    });

</script>
</code>```

The alert (1) and (2) is shown. But the alert (3) and (4) isn't shown.
Can you explain for me.
Thanks.

答:
obj.site_name and test are strings. In JavaScript, as in Python, strings need to be surrounded by quotes.

```<code>    alert("{{ obj.site_name }}");
    alert("{{ test }}");
</code>```

Your browser's developer tools will have shown the original code generating a syntax error.

Body:
In views.py

def website(request, pk=None):
if not model_utils.check_admin_permission(request):
    return loginAndContinuosRequest(request)

if pk:
    obj = get_object_or_404(Website, pk = pk)
    form = WebsiteForm(instance=obj)
    fields = obj.get_manage_payment_accounts()
else:
    obj = None
    form = WebsiteForm()
    fields = []

if request.POST:
    if pk:
        form = WebsiteForm(request.POST, request.FILES, instance=obj)
    else:
        form = WebsiteForm(request.POST, request.FILES)

    if form.is_valid():
        form.save()
        return HttpResponseRedirect(reverse("views_manage_websites"))

params = {
    'obj':obj ,
    'form':form,
    'fields': fields,
    'test': 'test',
}

return render(request, TEMPLATE_PATH + 'website.html', params)

In script in template (.html),

The alert (1) and (2) is shown. But the alert (3) and (4) isn't shown.
Can you explain for me.
Thanks.

Body:
obj.site_name and test are strings. In JavaScript, as in Python, strings need to be surrounded by quotes.

    alert("{{ obj.site_name }}");
    alert("{{ test }}");

Your browser's developer tools will have shown the original code generating a syntax error.


问:
How to replicate only one data type 'n' times in list using rep()
```<code>fred <- list(num = c(1:10) , name = "hello")
</code>```

How to repeat num type 5 times and name type 10 times in lists using rep()?

答:
You can try mapply which applies the function to the elements of fred and the times vector.

```<code>mapply(function(x, y) rep(x, times=y), fred, c(5, 10))
$num
 [1]  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9
[30] 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10

$name
 [1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"
</code>```

The list is replicated simply using

```<code>rep(fred, c(5,10))
</code>```

Body:
fred <- list(num = c(1:10) , name = "hello")

How to repeat num type 5 times and name type 10 times in lists using rep()?

Body:
You can try mapply which applies the function to the elements of fred and the times vector.

mapply(function(x, y) rep(x, times=y), fred, c(5, 10))
$num
 [1]  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9
[30] 10  1  2  3  4  5  6  7  8  9 10  1  2  3  4  5  6  7  8  9 10

$name
 [1] "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello" "hello"

The list is replicated simply using

rep(fred, c(5,10))


问:
Java streams: Add to map but avoid mutation
I often find myself in a situation where I need to create a Map of objects from a Set or List.
The key is usually some String or Enum or the like, and the value is some new object with data lumped together.
The usual way of doing this, for my part, is by first creating the Map<String, SomeKeyValueObject> and then iterating over the Set or List I get in and mutate my newly created map.

Like the following example:

```<code>class Example {
   Map<String, GroupedDataObject> groupData(final List<SomeData> list){
      final Map<String, GroupedDataObject> map = new HashMap<>();
      for(final SomeData data : list){
         final String key = data.valueToGroupBy();
         map.put(key, GroupedDataObject.of(map.get(key), data.displayName(), data.data()));
      }
      return map;
   }

}

class SomeData {
   private final String valueToGroupBy;
   private final Object data;
   private final String displayName;

   public SomeData(final String valueToGroupBy, final String displayName, final Object data) {
      this.valueToGroupBy = valueToGroupBy;
      this.data = data;
      this.displayName = displayName;
   }

   public String valueToGroupBy() {
      return valueToGroupBy;
   }

   public Object data() {
      return data;
   }

   public String displayName() {
      return displayName;
   }
}

class GroupedDataObject{

   private final String key;
   private final List<Object> datas;

   private GroupedDataObject(final String key, final List<Object> list) {
      this.key = key;
      this.datas = list;
   }

   public static GroupedDataObject of(final GroupedDataObject groupedDataObject, final String key, final Object data) {
      final List<Object> list = new ArrayList<>();
      if(groupedDataObject != null){
         list.addAll(groupedDataObject.datas());
      }
      list.add(data);
      return new GroupedDataObject(key, list);
   }

   public String key() {
      return key;
   }

   public List<Object> datas() {
      return datas;
   }
}
</code>```

This feels very unclean. We create a map, and then mutate it over and over.

I've taken a liking to java 8s use of Streams and creating non-mutating data structures (or rather, you don't see the mutation). So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way?

I tried to implement the suggestion in https://stackoverflow.com/a/34453814/3478016 but I seem to be stumbling. Using the approach in the answer (the suggestion of using Collectors.groupingBy and Collectors.mapping) I'm able to get the data sorted into a map. But I can't group the "datas" into one and the same object.

Is there some way to do it in a declarative way, or am I stuck with the imperative?

答:
Sometimes streams are not the way to go. I believe this is one of those times.

A little refactoring using merge() gives you:

```<code>Map<String, MyTuple> groupData(final List<SomeData> list) {
    Map<String, MyTuple> map = new HashMap<>();
    list.forEach(d -> map.merge(d.valueToGroupBy(), new MyTuple(data.displayName(), data.data()),
      (a, b) -> {a.addAll(b.getDatas()); return a;});
</code>```

Assuming a reasonable class to hold your stuff:

```<code>class MyTuple {
    String displayName;
    List<Object> datas = new ArrayList<>();
    // getters plus constructor that takes 1 data and adds it to list
}
</code>```

Body:
I often find myself in a situation where I need to create a Map of objects from a Set or List.
The key is usually some String or Enum or the like, and the value is some new object with data lumped together.
The usual way of doing this, for my part, is by first creating the Map<String, SomeKeyValueObject> and then iterating over the Set or List I get in and mutate my newly created map.

Like the following example:

class Example {
   Map<String, GroupedDataObject> groupData(final List<SomeData> list){
      final Map<String, GroupedDataObject> map = new HashMap<>();
      for(final SomeData data : list){
         final String key = data.valueToGroupBy();
         map.put(key, GroupedDataObject.of(map.get(key), data.displayName(), data.data()));
      }
      return map;
   }

}

class SomeData {
   private final String valueToGroupBy;
   private final Object data;
   private final String displayName;

   public SomeData(final String valueToGroupBy, final String displayName, final Object data) {
      this.valueToGroupBy = valueToGroupBy;
      this.data = data;
      this.displayName = displayName;
   }

   public String valueToGroupBy() {
      return valueToGroupBy;
   }

   public Object data() {
      return data;
   }

   public String displayName() {
      return displayName;
   }
}

class GroupedDataObject{

   private final String key;
   private final List<Object> datas;

   private GroupedDataObject(final String key, final List<Object> list) {
      this.key = key;
      this.datas = list;
   }

   public static GroupedDataObject of(final GroupedDataObject groupedDataObject, final String key, final Object data) {
      final List<Object> list = new ArrayList<>();
      if(groupedDataObject != null){
         list.addAll(groupedDataObject.datas());
      }
      list.add(data);
      return new GroupedDataObject(key, list);
   }

   public String key() {
      return key;
   }

   public List<Object> datas() {
      return datas;
   }
}

This feels very unclean. We create a map, and then mutate it over and over.

I've taken a liking to java 8s use of Streams and creating non-mutating data structures (or rather, you don't see the mutation). So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way?

I tried to implement the suggestion in https://stackoverflow.com/a/34453814/3478016 but I seem to be stumbling. Using the approach in the answer (the suggestion of using Collectors.groupingBy and Collectors.mapping) I'm able to get the data sorted into a map. But I can't group the "datas" into one and the same object.

Is there some way to do it in a declarative way, or am I stuck with the imperative?

Body:
Sometimes streams are not the way to go. I believe this is one of those times.

A little refactoring using merge() gives you:

Map<String, MyTuple> groupData(final List<SomeData> list) {
    Map<String, MyTuple> map = new HashMap<>();
    list.forEach(d -> map.merge(d.valueToGroupBy(), new MyTuple(data.displayName(), data.data()),
      (a, b) -> {a.addAll(b.getDatas()); return a;});

Assuming a reasonable class to hold your stuff:

class MyTuple {
    String displayName;
    List<Object> datas = new ArrayList<>();
    // getters plus constructor that takes 1 data and adds it to list
}


问:
How to work with Restful web service using jersey.Iam new to this Topic
Please suggest spring restful web service ..I have one doubt if iam having web service in one dynamic web project how can i get the value in client side(or)
For Example:
client side(Dynamic web project) iam giving two data 2 and 3 how to send this data to server side(onather Dynamic web project) for addition purpose is that possible.how server get data from client which is in another project.suggest some codes.</p>

答:
There are many frameworks you can use to consume the REST web-service, one of them i had used is Jersey which is implemented based on the JAX-RS specification.

Below is the sample Code of Jersey client consuming REST Web-service

REST WS Project

```<code>//Person pojo
@JsonInclude(Include.NON_NULL)
public class Person implements Serializable  {

   private static final long serialVersionUID = 8979562848777300129L;

   private String firstName;
   private String lastName;
   private String email

   //setter and getter methods
}

//REST WS controller
@RestController
@RequestMapping("/user")
public class SBUserController{

@RequestMapping(value = "/profile", method = RequestMethod.GET, consumes = "application/json", produces = "application/json")
public Person fetchProfile() {

//implement service layer and dao layer to fetch user profile from DB
//testing purpose i am creating one person and returning back
    Person person  = new Person();
    person.setFirstName("John");
    person.setLastName("Terry");
    person.setEmail("john@gmail.com");

    return person;
}
}
</code>```

//Client Side

```<code>   Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/user/profile");

ClientResponse clientResponse = webResource
                                .accept(MediaType.APPLICATION_JSON)
                                .type(MediaType.APPLICATION_JSON)
                                .get(ClientResponse.class);

        if (clientResponse.getStatus() == 200) {
        //You need to have the same Person bean class in client project also
          Person person = clientResponse.getEntity(Person.class));
        }
</code>```

Body:
There are many frameworks you can use to consume the REST web-service, one of them i had used is Jersey which is implemented based on the JAX-RS specification.

Below is the sample Code of Jersey client consuming REST Web-service

REST WS Project

//Person pojo
@JsonInclude(Include.NON_NULL)
public class Person implements Serializable  {

   private static final long serialVersionUID = 8979562848777300129L;

   private String firstName;
   private String lastName;
   private String email

   //setter and getter methods
}

//REST WS controller
@RestController
@RequestMapping("/user")
public class SBUserController{

@RequestMapping(value = "/profile", method = RequestMethod.GET, consumes = "application/json", produces = "application/json")
public Person fetchProfile() {

//implement service layer and dao layer to fetch user profile from DB
//testing purpose i am creating one person and returning back
    Person person  = new Person();
    person.setFirstName("John");
    person.setLastName("Terry");
    person.setEmail("john@gmail.com");

    return person;
}
}

//Client Side

   Client client = Client.create();
WebResource webResource = client.resource("http://localhost:8080/user/profile");

ClientResponse clientResponse = webResource
                                .accept(MediaType.APPLICATION_JSON)
                                .type(MediaType.APPLICATION_JSON)
                                .get(ClientResponse.class);

        if (clientResponse.getStatus() == 200) {
        //You need to have the same Person bean class in client project also
          Person person = clientResponse.getEntity(Person.class));
        }


答:
Ensure that you are invalidating correct instance of Timer.
Like in start function, you didn't assign timer instance to any object, but in stop function,you are using timer vaiable to stop that timer.
Which means you try to invalidate a variable, which never instantiated.

Still try below function to stop timer, after assigning timer variable.

```<code>@IBAction func stop(_ sender: UIButton) {

       start = false
       timer.invalidate()
       timer = nil
       time = 0
    }
</code>```

Hope this work

Title: swift3，my timer can't stop. why?

Body:
this is i seting a timer function, the code like this:

@IBAction func start(_ sender: UIButton) {

    Timer.scheduledTimer(timeInterval: 1,
                         target: self,
                         selector:#selector(ViewController.action),
                         userInfo: nil,
                         repeats: true)
}

@objc func action() {

    hoursMinutesSeconds()
    if stop == true{
        start = false
        timer.invalidate()
        timer.invalidate()
        time = 0
    }
}

@IBAction func stop(_ sender: UIButton){

    start = false
    timer.invalidate()
    timer.invalidate()
    time = 0
}

but, when i click the stop func,  this function not work. mean is the timer not stop. timer stil working……  why？ thank you  for your time!!

Body:
Ensure that you are invalidating correct instance of Timer.
Like in start function, you didn't assign timer instance to any object, but in stop function,you are using timer vaiable to stop that timer.
Which means you try to invalidate a variable, which never instantiated.

Still try below function to stop timer, after assigning timer variable.

@IBAction func stop(_ sender: UIButton) {

       start = false
       timer.invalidate()
       timer = nil
       time = 0
    }

Hope this work


问:
Formatter issue when language changed in device
I'm trying to get float number from amount string with out currency symbol like "100.00". Its working properly in English language. When language changed to German in device, its behaviour is getting changed. How can I achieve float value with out affecting by language change in device.

```<code>func getFloatNumberFromString(_ str: String) -> Float {
        guard let number = NumberFormatter().number(from: str) else {
            return 0.0
        }

        return number.floatValue
    }
</code>```

another piece of below code to deal with it:

```<code>    func removeFormatAmount() -> Double {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            return formatter.number(from: self) as! Double? ?? 0
   }
</code>```

When I use second method then the output is coming as 0.

Please let me know what am I missing or suggest me to deal with it.
Thanks in advance

答:
Did you try to cast directly? Like this.</p>

```<code>let floatString = "12.34"
let number = Double(floatString) ?? 0.0
</code>```

Body:
I'm trying to get float number from amount string with out currency symbol like "100.00". Its working properly in English language. When language changed to German in device, its behaviour is getting changed. How can I achieve float value with out affecting by language change in device.

func getFloatNumberFromString(_ str: String) -> Float {
        guard let number = NumberFormatter().number(from: str) else {
            return 0.0
        }

        return number.floatValue
    }

another piece of below code to deal with it:

    func removeFormatAmount() -> Double {
            let formatter = NumberFormatter()
            formatter.numberStyle = .decimal
            return formatter.number(from: self) as! Double? ?? 0
   }

When I use second method then the output is coming as 0.

Please let me know what am I missing or suggest me to deal with it.
Thanks in advance

Body:
Did you try to cast directly? Like this.

let floatString = "12.34"
let number = Double(floatString) ?? 0.0


问:
Highcharts many panes
I took this example from Highcharts
and tried to add the 3rd pane, same as the 2nd one. I added 3rd element to yAxis (same as the 2nd one) and to series (with name = Volume1 and yAxis = 2)

```<code>yAxis: [{
        labels: {
            align: 'right',
            x: -3
        },
        title: {
            text: 'OHLC'
        },
        height: '60%',
        lineWidth: 2,
        resize: {
            enabled: true
        }
    }, {
        labels: {
            align: 'right',
            x: -3
        },
        title: {
            text: 'Volume'
        },
        top: '65%',
        height: '35%',
        offset: 0,
        lineWidth: 2
    }, {
        labels: {
            align: 'right',
            x: -3
        },
        title: {
            text: 'Volume2'
        },
        top: '65%',
        height: '35%',
        offset: 0,
        lineWidth: 2
    }],

series: [{
        type: 'candlestick',
        name: 'AAPL',
        data: ohlc,
        dataGrouping: {
            units: groupingUnits
        }
    }, {
        type: 'column',
        name: 'Volume',
        data: volume,
        yAxis: 1,
        dataGrouping: {
            units: groupingUnits
        }
    }, {
        type: 'column',
        name: 'Volume1',
        data: volume,
        yAxis: 2,
        dataGrouping: {
            units: groupingUnits
        }
    }]
</code>```

but I got 2 charts in the 2nd pane instead.

Please take a look at here

I don't care which chart type to use, I just need more panes

答:
The controlling factor is top and height in the yAxis settings.

If you change the yAxis to have the following, it will work as you intend.

```<code>yAxis: [
  {
    height: '60%',
    ...
  }, {
    top: '65%',
    height: '15%',
    ...
  }, {
    top: '80%',
    height: '15%',
    ...
  }]
</code>```

You can of course play with the settings to create exactly the dimensions you seek.

Working example: http://jsfiddle.net/ewolden/2Lkg06g1/2/

API on yAxis.height: https://api.highcharts.com/highstock/yAxis.height

API on yAxis.top: https://api.highcharts.com/highstock/yAxis.top

Title: Highcharts many panes

Body:
I took this example from Highcharts
and tried to add the 3rd pane, same as the 2nd one. I added 3rd element to yAxis (same as the 2nd one) and to series (with name = Volume1 and yAxis = 2)

yAxis: [{
        labels: {
            align: 'right',
            x: -3
        },
        title: {
            text: 'OHLC'
        },
        height: '60%',
        lineWidth: 2,
        resize: {
            enabled: true
        }
    }, {
        labels: {
            align: 'right',
            x: -3
        },
        title: {
            text: 'Volume'
        },
        top: '65%',
        height: '35%',
        offset: 0,
        lineWidth: 2
    }, {
        labels: {
            align: 'right',
            x: -3
        },
        title: {
            text: 'Volume2'
        },
        top: '65%',
        height: '35%',
        offset: 0,
        lineWidth: 2
    }],

series: [{
        type: 'candlestick',
        name: 'AAPL',
        data: ohlc,
        dataGrouping: {
            units: groupingUnits
        }
    }, {
        type: 'column',
        name: 'Volume',
        data: volume,
        yAxis: 1,
        dataGrouping: {
            units: groupingUnits
        }
    }, {
        type: 'column',
        name: 'Volume1',
        data: volume,
        yAxis: 2,
        dataGrouping: {
            units: groupingUnits
        }
    }]

but I got 2 charts in the 2nd pane instead.

Please take a look at here

I don't care which chart type to use, I just need more panes

Body:
The controlling factor is top and height in the yAxis settings.

If you change the yAxis to have the following, it will work as you intend.

yAxis: [
  {
    height: '60%',
    ...
  }, {
    top: '65%',
    height: '15%',
    ...
  }, {
    top: '80%',
    height: '15%',
    ...
  }]

You can of course play with the settings to create exactly the dimensions you seek.

Working example: http://jsfiddle.net/ewolden/2Lkg06g1/2/

API on yAxis.height: https://api.highcharts.com/highstock/yAxis.height

API on yAxis.top: https://api.highcharts.com/highstock/yAxis.top


问:
Connect graph DB and SQL in laravel
I want to connect multiple databases in Laravel 5.5. I tried using this but it doesn't seem to work. I want to use https://github.com/graphaware/neo4j-php-client as a client to connect to graph DB, the reason I wanted to use this was to run cypher queries directly.

What changes should I make in the config/database.php to accommodate such condition and how do I access each database from the code?

答:
You can create a custom provider, for example in App\Providers\Neo4jServiceProvider.php and define 2 or more connections to the client :

```<code>class Neo4jServiceProvider extends ServiceProvider
{
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Client::class, function() {
            return ClientBuilder::create()
                ->addConnection('server1', getenv('NEO4J_1_HOST'))
                ->addConnection('server2', getenv('NEO4J_2_HOST'))
                ->build();
        });
    }
}
</code>```

Then you register the provider in your application, add this to the providers array of the config/app.php file :

```<code>App\Providers\Neo4jServiceProvider::class,
</code>```

Add the connections parameters for your neo4j dbs in the .env file.

Next, you can inject this service anywhere and query any db :

```<code>class MyController
{

  private $client;

  public function __construct(Client $client)
  {
    $this->client = $client;
  }

  public function doSomeQueries()
  {
    // Query DB 1
    $result = $this->client->run('MATCH (n) RETURN count(n)', null, null, 'server1');
    // Query DB 2
    $result2 = $this->client->run('MATCH (n) RETURN count(n)', null, null, 'server2');
}
</code>```

Title: Connect graph DB and SQL in laravel

Body:
You can create a custom provider, for example in App\Providers\Neo4jServiceProvider.php and define 2 or more connections to the client :

class Neo4jServiceProvider extends ServiceProvider
{
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Client::class, function() {
            return ClientBuilder::create()
                ->addConnection('server1', getenv('NEO4J_1_HOST'))
                ->addConnection('server2', getenv('NEO4J_2_HOST'))
                ->build();
        });
    }
}

Then you register the provider in your application, add this to the providers array of the config/app.php file :

App\Providers\Neo4jServiceProvider::class,

Add the connections parameters for your neo4j dbs in the .env file.

Next, you can inject this service anywhere and query any db :

class MyController
{

  private $client;

  public function __construct(Client $client)
  {
    $this->client = $client;
  }

  public function doSomeQueries()
  {
    // Query DB 1
    $result = $this->client->run('MATCH (n) RETURN count(n)', null, null, 'server1');
    // Query DB 2
    $result2 = $this->client->run('MATCH (n) RETURN count(n)', null, null, 'server2');
}


问:
Maven Encrypt Password ArrayIndexOutOfBoundsException
I have a problem with the mvn --encrypt-password function from maven.

I just installed Maven on my PC, added the bin directory to the PATH and now I'm trying to encrypt my password for the settings.xml. I have seen in the internet, that you normaly use mvn --encrypt-password for this, but everytime I try to use it I get the following error:

```<code>C:\Users\USER>mvn -ep
Password:
[ERROR] Error executing Maven.
[ERROR] java.lang.ArrayIndexOutOfBoundsException
[ERROR] Caused by: null
</code>```

I already tried to switch from JRE 1.8.0_112 to JDK 1.8.0_111 and maven realised the change:

```<code>C:\Users\USER>mvn -v
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T09:58:1
3+02:00)
Maven home: F:\Programme\apache-maven-3.5.2\bin\..
Java version: 1.8.0_111, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_111\jre
Default locale: de_DE, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"
</code>```

But I'm still getting the error. I would be very pleased if someone could help me with this problem.

Sincerely StefanPG

答:
SOLUTION:
As khmarbaise said, just using mvn -emp worked fine for me.

Again, thanks alot.

EDIT:
A coworker just told me, that the mvn -ep only works, if you have a master password in your %USER%/.m2/settings-security.xml

Body:
I have a problem with the mvn --encrypt-password function from maven.

I just installed Maven on my PC, added the bin directory to the PATH and now I'm trying to encrypt my password for the settings.xml. I have seen in the internet, that you normaly use mvn --encrypt-password for this, but everytime I try to use it I get the following error:

C:\Users\USER>mvn -ep
Password:
[ERROR] Error executing Maven.
[ERROR] java.lang.ArrayIndexOutOfBoundsException
[ERROR] Caused by: null

I already tried to switch from JRE 1.8.0_112 to JDK 1.8.0_111 and maven realised the change:

C:\Users\USER>mvn -v
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T09:58:1
3+02:00)
Maven home: F:\Programme\apache-maven-3.5.2\bin\..
Java version: 1.8.0_111, vendor: Oracle Corporation
Java home: C:\Program Files\Java\jdk1.8.0_111\jre
Default locale: de_DE, platform encoding: Cp1252
OS name: "windows 7", version: "6.1", arch: "amd64", family: "windows"

But I'm still getting the error. I would be very pleased if someone could help me with this problem.

Sincerely StefanPG


问:
Can I build a TensorFlow servable in Python
I'm new to Google TensorFlow Serving. I'm trying to see if I have a model which is written in Python. Can I make it a "servable" for TensorFlow Serving to run? I searched on Internet but I only could find instructions about the TensorFlow Serving client.

Any hint? Thanks!

答: I successfully build a model with TFServing by following this article. It has each you need to build a model. I think this is the hint you need.</p>


问:
Automatically deducing the type of bind1st(mem_fun(&my_class::f), this)?
I would like to pass the bind1st(mem_fun(&my_class::f), this) functor to for_each. Unfortunately it is very difficult to read so I would like to give it a more readible name like this:

```<code>(the type I am looking for) meaningful_name = bind1st(mem_fun(&my_class::f), this);

for_each(v.begin(), v.end(), meaningful_name);
</code>```

Is there a simple way to deduce the type of the functor? (I know mem_fun saves us a lot of pain exactly for this reason.)

答:
This depends on the argument and return types of my_class:f. If the function is

```<code>T my_class::f(A arg)
</code>```

then you need

```<code>binder1st<mem_fun1_t<T,my_class,A> > meaningful_name = bind1st(mem_fun(&my_class::f), this);
</code>```

This kind of thing will be nicer with C++0x:

```<code>auto meaningful_name = bind1st(mem_fun(&my_class::f), this);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I would like to pass the bind1st(mem_fun(&my_class::f), this) functor to for_each. Unfortunately it is very difficult to read so I would like to give it a more readible name like this:

(the type I am looking for) meaningful_name = bind1st(mem_fun(&my_class::f), this);

for_each(v.begin(), v.end(), meaningful_name);

Is there a simple way to deduce the type of the functor? (I know mem_fun saves us a lot of pain exactly for this reason.)

Body:
This depends on the argument and return types of my_class:f. If the function is

T my_class::f(A arg)

then you need

binder1st<mem_fun1_t<T,my_class,A> > meaningful_name = bind1st(mem_fun(&my_class::f), this);

This kind of thing will be nicer with C++0x:

auto meaningful_name = bind1st(mem_fun(&my_class::f), this);


问:
plot axis label formatting units in R
I'm plotting photosynthetically active radiation which has units of umol/m2/s
I can get R to plot "PAR umol m-2" with the u as mu and -2 in superscript using:

```<code>bp_m + ylab(expression(paste('PAR ',mu,'mol m')^-2))
</code>```

where bpm is the rest of the plot, but I can't get it to add the s^-1, I've tried various forms of expressions, paste etc

答:
Finally got there - R seems to have so many different ways of doing the same thing, taking me ages to get my head around the syntax etc

```<code>bp_m+labs(y = ~paste("PAR ", mu, "mol m"^-2,"s"^-1))
bp_m+ylab(~paste("PAR ", mu, "mol m"^-2,"s"^-1)))
</code>```

both work

Title: plot axis label formatting units in R

Body:
I'm plotting photosynthetically active radiation which has units of umol/m2/s
I can get R to plot "PAR umol m-2" with the u as mu and -2 in superscript using:

bp_m + ylab(expression(paste('PAR ',mu,'mol m')^-2))

where bpm is the rest of the plot, but I can't get it to add the s^-1, I've tried various forms of expressions, paste etc

Body:
Finally got there - R seems to have so many different ways of doing the same thing, taking me ages to get my head around the syntax etc

bp_m+labs(y = ~paste("PAR ", mu, "mol m"^-2,"s"^-1))
bp_m+ylab(~paste("PAR ", mu, "mol m"^-2,"s"^-1)))

both work


问:
No endpoint could be found for: test, please check your classpath contains the needed Camel component jar
I am trying to send and receive messages using akka-camel and created a sample example for producer and consumer like below :

Producer:

```<code>import akka.actor.{Actor, ActorSystem, Props}
import akka.camel.Producer

class CamelJmsProducer extends Actor with Producer {
  override def endpointUri = "test"
}

object CamelJmsProducerApp extends App {
  val system = ActorSystem("some-system")
  val ref = system.actorOf(Props[CamelJmsProducer])
  ref ! "HEY"
}
</code>```

Consumer:

```<code>import akka.actor.{Actor, ActorSystem, Props}
import akka.camel.{CamelMessage, Consumer}

class CamelJmsConsumer extends Actor with Consumer {
  override def receive = {
    case msg: CamelMessage ⇒ println("RECEIVED >>> " + msg)
    case _ ⇒ println("RECEIVED NOTHING>>> ")
  }

  override def endpointUri = "test"
}

object CamelJmsConsumerApp extends App {
  val system = ActorSystem("some-system1")
  system.actorOf(Props[CamelJmsConsumer])
}
</code>```

But I am facing issue in both producer and consumer like below. What I am missing?

Producer:

java.lang.IllegalArgumentException: destination must be specified

Consumer :

Caused by: org.apache.camel.NoSuchEndpointException: No endpoint could
  be found for: test, please check your classpath contains the needed
  Camel component jar.

答:
I believe you need to provide a name to the test mock endpoint, just test might not work. Can you try doing doing test:myMockEndpoint?

You can take a look here: http://camel.apache.org/components.html

Body:
I am trying to send and receive messages using akka-camel and created a sample example for producer and consumer like below :

Producer:

import akka.actor.{Actor, ActorSystem, Props}
import akka.camel.Producer

class CamelJmsProducer extends Actor with Producer {
  override def endpointUri = "test"
}

object CamelJmsProducerApp extends App {
  val system = ActorSystem("some-system")
  val ref = system.actorOf(Props[CamelJmsProducer])
  ref ! "HEY"
}

Consumer:

import akka.actor.{Actor, ActorSystem, Props}
import akka.camel.{CamelMessage, Consumer}

class CamelJmsConsumer extends Actor with Consumer {
  override def receive = {
    case msg: CamelMessage ⇒ println("RECEIVED >>> " + msg)
    case _ ⇒ println("RECEIVED NOTHING>>> ")
  }

  override def endpointUri = "test"
}

object CamelJmsConsumerApp extends App {
  val system = ActorSystem("some-system1")
  system.actorOf(Props[CamelJmsConsumer])
}

But I am facing issue in both producer and consumer like below. What I am missing?

Producer:

java.lang.IllegalArgumentException: destination must be specified

Consumer :

Caused by: org.apache.camel.NoSuchEndpointException: No endpoint could
  be found for: test, please check your classpath contains the needed
  Camel component jar.


问:
ASP.Net - Masked first 6 character on a string with dynamic length
is it possible to masked a first 6 characters on a string if the string is dynamics on it's length?

Example, I have a string "test123456789" and I want a result of "******3456789" or a string of "1234test" and I want a result of "******st". All I'm seeing sample codes here in masking are strings with a static length. Can anyone kindly help me with this? Thank you so much in advance.

答:
Linq is an alternative to Substring and ternary operator solution (see Zohar Peled's answer):

```<code>using System.Linq;

...

string original = "Some string here";
string result = "******" + string.Concat(original.Skip(6));
</code>```

If you want to preserve the length of short (less than 6 character string):

```<code>// if original shorter than 6 symbols, e.g. "short"
// we'll get "*****" (Length number of *, not 6)
// if original has six or more symbols, e.g. "QuiteLong"
// we'll get "******ong" as usual
string original = "short";
...
string result = new string('*', Math.Min(6, original.Length)) +
                string.Concat(original.Skip(Math.Min(6, original.Length)));
</code>```

You may want to have the routine as an extension method:

```<code>public static partial class StringExtensions {
  public static string MaskPrefix(this string value, int count = 6) {
    if (null == value)
      throw new ArgumentNullException("value"); // or return value
    else if (count < 0)
      throw new ArgumentOutOfRangeException("count"); // or return value

    int length = Math.Min(value.Length, count);

    return new string('*', length) + string.Concat(value.Skip(length));
  }
}
</code>```

And so you can put as if string has MaskPrefix method:

```<code>string original = "Some string here";
string result = original.MaskPrefix(6);
</code>```

Body:
Linq is an alternative to Substring and ternary operator solution (see Zohar Peled's answer):

using System.Linq;

...

string original = "Some string here";
string result = "******" + string.Concat(original.Skip(6));

If you want to preserve the length of short (less than 6 character string):

// if original shorter than 6 symbols, e.g. "short"
// we'll get "*****" (Length number of *, not 6)
// if original has six or more symbols, e.g. "QuiteLong"
// we'll get "******ong" as usual
string original = "short";
...
string result = new string('*', Math.Min(6, original.Length)) +
                string.Concat(original.Skip(Math.Min(6, original.Length)));

You may want to have the routine as an extension method:

public static partial class StringExtensions {
  public static string MaskPrefix(this string value, int count = 6) {
    if (null == value)
      throw new ArgumentNullException("value"); // or return value
    else if (count < 0)
      throw new ArgumentOutOfRangeException("count"); // or return value

    int length = Math.Min(value.Length, count);

    return new string('*', length) + string.Concat(value.Skip(length));
  }
}

And so you can put as if string has MaskPrefix method:

string original = "Some string here";
string result = original.MaskPrefix(6);


问:
vtk error: extension `GL_EXT_gpu_shader4' unsupported in fragment shader
I have XUBUNTU 16.04 32 bits. I am a beginner with VTK libraries. I have built and istalled VTK 7.1.1 from source. I followed the instructions from https://www.vtk.org/Wiki/VTK/Configure_and_Build
The installation is ok. No errors.
I download the simplest example: CylinderRenderingProperties.
Then, I compile the example. No errors. But, when I run the program

```<code>./CylinderRenderingProperties
</code>```

there is an error:

```<code>VTK-7.1.1/Rendering/OpenGL2/vtkShaderProgram.cxx, line 395 vtkShaderProgram (0x9fd1510): 0:39(12): error: extension `GL_EXT_gpu_shader4' unsupported in fragment shader
</code>```

I don't know what is wrong. Could be related with any graphic driver? This is the information of my graphics hardware:

```<code>inxi -G
Graphics:  Card: Intel Mobile 4 Series Integrated Graphics Controller
       Display Server: X.Org 1.19.3 drivers: (unloaded: fbdev,vesa)
       Resolution: 1280x800@60.00hz, 1280x1024@60.02hz
       GLX Renderer: Mesa DRI Mobile Intel GM45 Express x86/MMX/SSE2 GLX Version: 2.1 Mesa 17.0.7
</code>```

答:
Yes, it is about your graphic driver/card. As the error message states, you need your graphic driver to support the GL_EXT_gpu_shader4 extension, which in general comes with openGL 3.2 and higher. Your current driver does not support it and in fact, according to what I found on Intel's support website, your graphic card does not support it. Apart from changing your computer / GPU, I see two options:

1) use software rendering by Mesa: Mesa has a software renderer that would offload all openGL calls to be processed by the Mesa library on CPU. You would get slower rendering, but it would work. I have never used it though, so I can't help you in setting it up, you would have to do some research on how exactly to do it.

2) In case you don't plan to do any complex rendering in VTK, you might be ok with using the old rendering backend which was the default until VTK version 7. It doesn't use anything that requires openGL above 2.1, so it should work fine on your computer. To activate it, change the VTK's CMake variable VTK_RENDERING_BACKEND from openGL2 to openGL and then build VTK anew. It's a bit slower and doesn't have some new cool features, but otherwise it's perfectly functional and will suffice for many applications.

Body:
I have XUBUNTU 16.04 32 bits. I am a beginner with VTK libraries. I have built and istalled VTK 7.1.1 from source. I followed the instructions from https://www.vtk.org/Wiki/VTK/Configure_and_Build
The installation is ok. No errors.
I download the simplest example: CylinderRenderingProperties.
Then, I compile the example. No errors. But, when I run the program

./CylinderRenderingProperties

there is an error:

VTK-7.1.1/Rendering/OpenGL2/vtkShaderProgram.cxx, line 395 vtkShaderProgram (0x9fd1510): 0:39(12): error: extension `GL_EXT_gpu_shader4' unsupported in fragment shader

I don't know what is wrong. Could be related with any graphic driver? This is the information of my graphics hardware:

inxi -G
Graphics:  Card: Intel Mobile 4 Series Integrated Graphics Controller
       Display Server: X.Org 1.19.3 drivers: (unloaded: fbdev,vesa)
       Resolution: 1280x800@60.00hz, 1280x1024@60.02hz
       GLX Renderer: Mesa DRI Mobile Intel GM45 Express x86/MMX/SSE2 GLX Version: 2.1 Mesa 17.0.7


问:
RxJava2 Single take different route based on the item
I have the following code:

```<code>Single<Response<User>> single = service.registerUser();

single
     .subscribeOn(Schedulers.io())
     .observeOn(Schedulers.computation())
     .map(Response::body)
     .flatMap(parentsRepsitory::writeUser)
     .observeOn(AndroidSchedulers.mainThread())
     .flatMap(parentsRepsitory::getUser)
</code>```

Where the parentsRepository is a repo wraping my realm database. The problems come when the server returns validation errors, however. So somewhere in my stream i want to have the equivalent of

```<code>if(response.code() == 201){
    // CONTINUE STREAM USING THE LOGIC THAT HANDLES SUCCESS
}elseif(response.code() == 400){
    // CONTINUE STREAM USING LOGIC TO HANDLE THE VALIDATION ERRORS
}
</code>```

A solution I have previously implemented is as follows:

```<code>Observable<Response<User>> observable_from_api =
        service.attemptLogin(username, password)
               .share();

observable_from_api
        .filter(response -> response.code() == HttpStatus.HTTP_STATUS_200_OK)
        .//handle logic for success

observable_from_api
        .filter(response -> response.code() == HttpStatus.HTTP_STATUS_400_BAD_REQUEST)
        .//handle logic for validation errors
</code>```

I don't like this solution for several different reasons. The main one being it just does not seem right. The second one being that the .share() method is only available on an Observable object. Since my network operation emits only one responce I would much rather use Single instead, but the .share() method is not available there.

Excuse me if this is a duplicate question, I have done some digging around and only found the solution I mentioned. I want to either see the optimal solution or be told explicitly that this is in fact the optimal solution.

答:
I think you need to define which kind of data you want your consumer to receive. I assume you want to receive in the consumer a User object.

These are the signatures of the method that you should create:

```<code>Single<User> handleSuccess(Response<User> response)

Single<User> handleError(Response<User> response)
</code>```

And then you create you stream in this way:

```<code>service.registerUser()
    .flatMap(response -> {
         if (response.success) {
             return handleSuccess(response);
          } else {
             return handleError(response);
          }
     })
.subscribe(user -> logd("user: " + user.name));
</code>```

Body:
I have the following code:

Single<Response<User>> single = service.registerUser();

single
     .subscribeOn(Schedulers.io())
     .observeOn(Schedulers.computation())
     .map(Response::body)
     .flatMap(parentsRepsitory::writeUser)
     .observeOn(AndroidSchedulers.mainThread())
     .flatMap(parentsRepsitory::getUser)

Where the parentsRepository is a repo wraping my realm database. The problems come when the server returns validation errors, however. So somewhere in my stream i want to have the equivalent of

if(response.code() == 201){
    // CONTINUE STREAM USING THE LOGIC THAT HANDLES SUCCESS
}elseif(response.code() == 400){
    // CONTINUE STREAM USING LOGIC TO HANDLE THE VALIDATION ERRORS
}

A solution I have previously implemented is as follows:

Observable<Response<User>> observable_from_api =
        service.attemptLogin(username, password)
               .share();

observable_from_api
        .filter(response -> response.code() == HttpStatus.HTTP_STATUS_200_OK)
        .//handle logic for success

observable_from_api
        .filter(response -> response.code() == HttpStatus.HTTP_STATUS_400_BAD_REQUEST)
        .//handle logic for validation errors

I don't like this solution for several different reasons. The main one being it just does not seem right. The second one being that the .share() method is only available on an Observable object. Since my network operation emits only one responce I would much rather use Single instead, but the .share() method is not available there.

Excuse me if this is a duplicate question, I have done some digging around and only found the solution I mentioned. I want to either see the optimal solution or be told explicitly that this is in fact the optimal solution.

Body:
I think you need to define which kind of data you want your consumer to receive. I assume you want to receive in the consumer a User object.

These are the signatures of the method that you should create:

Single<User> handleSuccess(Response<User> response)

Single<User> handleError(Response<User> response)

And then you create you stream in this way:

service.registerUser()
    .flatMap(response -> {
         if (response.success) {
             return handleSuccess(response);
          } else {
             return handleError(response);
          }
     })
.subscribe(user -> logd("user: " + user.name));


问:
Azure Portal Mobile App Permissions
We just moved to Azure Portal and i created a Xamarin Cross-Platform app that gets authenticated via MSAL.

When i was building the app. it was registered on https://apps.dev.microsoft.com/, and the user was getting authenticated without any problems.

After testing, i registered it on our Azure Portal under app registration, gave it the required permissions as before, and updated the app ID in the code.

Now, i cant even go past my email page. I keep getting the message:"It looks like you're trying to open this resource with an app that hasn't been approved by your IT dept", even though the admin granted the permissions to the app. Not sure where to go from here. Any help appreciated.

Thanks in advance

答:
When i was building the app. it was registered on https://apps.dev.microsoft.com/, and the user was getting authenticated without any problems.

apps.dev.microsoft.com is used to register the application for Azure AD v2.0, and you could leverage MSAL for authenticating users by using AD account or personal Microsoft account.

For the application registered on Azure portal, you need to use the ADAL library. Detailed tutorial about integrating Azure AD (v1.0) with your xamarin apps, you could follow here.

UPDATE:

Based on your scenario, for using MS graph via ADAL, you could create an app under your tenant and add the required delegated permissions to the Microsoft Graph API. The AcquireTokenAsync method would look as follows:

```<code>var authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", clientId, returnUri, parent);
</code>```

Moreover, for differences between app-only and delegated scopes permissions, you could follow here. Also, you could check differences between Microsoft Graph or Azure AD Graph.

Title: Azure Portal Mobile App Permissions

Body:
When i was building the app. it was registered on https://apps.dev.microsoft.com/, and the user was getting authenticated without any problems.

apps.dev.microsoft.com is used to register the application for Azure AD v2.0, and you could leverage MSAL for authenticating users by using AD account or personal Microsoft account.

For the application registered on Azure portal, you need to use the ADAL library. Detailed tutorial about integrating Azure AD (v1.0) with your xamarin apps, you could follow here.

UPDATE:

Based on your scenario, for using MS graph via ADAL, you could create an app under your tenant and add the required delegated permissions to the Microsoft Graph API. The AcquireTokenAsync method would look as follows:

var authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", clientId, returnUri, parent);

Moreover, for differences between app-only and delegated scopes permissions, you could follow here. Also, you could check differences between Microsoft Graph or Azure AD Graph.


问:
Will hashing two eual strings give same hash value
I need to anonymyze personal data in our MySql database. The problem is that I still need to be able to link two persons together after they have been anonymized.

I thought this could be done by hashing their social security number or e-mail address, which lead to my question:

When hashing two equal strings (s1 and s1) I get two hash values (h1 and h2), how sure can I be that:

1) the hashed value is equal (h1 = h2)

2) no not equal (s3 = s1) will produce the same hash value

答:
1) Same strings will always produce equal hash values

2) Different strings theoretically might produce same hash if you choose small hash length compared to data volume. But using default hash lengths (32 or 40) wont cause such problems.


问:
Learning Python from Ruby; Differences and Similarities
I know Ruby very well. I believe that I may need to learn Python presently. For those who know both, what concepts are similar between the two, and what are different?

I'm looking for a list similar to a primer I wrote for Learning Lua for JavaScripters: simple things like whitespace significance and looping constructs; the name of nil in Python, and what values are considered "truthy"; is it idiomatic to use the equivalent of map and each, or are mumble somethingaboutlistcomprehensions mumble the norm?

If I get a good variety of answers I'm happy to aggregate them into a community wiki. Or else  you all can fight and crib from each other to try to create the one true comprehensive list.

Edit: To be clear, my goal is "proper" and idiomatic Python. If there is a Python equivalent of inject, but nobody uses it because there is a better/different way to achieve the common functionality of iterating a list and accumulating a result along the way, I want to know how you do things. Perhaps I'll update this question with a list of common goals, how you achieve them in Ruby, and ask what the equivalent is in Python.

答:
I know little Ruby, but here are a few bullet points about the things you mentioned:

nil, the value indicating lack of a value, would be None (note that you check for it like x is None or x is not None, not with == - or by coercion to boolean, see next point).

None, zero-esque numbers (0, 0.0, 0j (complex number)) and empty collections ([], {}, set(), the empty string "", etc.) are considered falsy, everything else is considered truthy.

For side effects, (for-)loop explicitly. For generating a new bunch of stuff without side-effects, use list comprehensions (or their relatives - generator expressions for lazy one-time iterators, dict/set comprehensions for the said collections).

Concerning looping: You have for, which operates on an iterable(! no counting), and while, which does what you would expect. The fromer is far more powerful, thanks to the extensive support for iterators. Not only nearly everything that can be an iterator instead of a list is an iterator (at least in Python 3 - in Python 2, you have both and the default is a list, sadly). The are numerous tools for working with iterators - zip iterates any number of iterables in parallel, enumerate gives you (index, item) (on any iterable, not just on lists), even slicing abritary (possibly large or infinite) iterables! I found that these make many many looping tasks much simpler. Needless to say, they integrate just fine with list comprehensions, generator expressions, etc.


问:
How do I import a CSV file into CockroachDB?
I have a CSV file I exported from a MySQL database and I want to move it over to CockroachDB. How do I read in the data from the command line?</p>

答:
Cockroach doesn't support the DELIMITER statement it also does not accepts the CSV format explicit so the right command in order to use COPY FROM would be:

psql postgres://user@host:port/DATABASE -c "COPY [table] FROM '[path to].csv';"

The delimiter character must be the special character \t so if your CSV file is using , as delimiter, you can convert it easily using sed:

sed -i 's/,/\t/g' [your file].csv

Why they hardcoded the special character \t as delimiter instead of , is beyond my knowledge.

There is already an open issue about this in https://github.com/cockroachdb/cockroach/issues/16407


问:
Show drop down values of a select option based on another select option
I have two dropdown select option. First is for select State and second is for select city. When any one select from state dropdown then related content should be shown on second select option (that will be related city.). I have some code, but it is not working. </p>

```<code>   <div class="vali-form">
        <div class="col-md-6 form-group2">

        <?php
   include("connection.php");
   $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        echo" <label class='control-label'>Select State</label>";
        echo" <select required name='selectstate'>";
        echo"<option>Select</option>";
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }
        echo" </select>";
       ?>

        </div>
        <div class="col-md-6 form-group2"  id="response">

         <label class='control-label'>City:</label>
     <select>

            <?php
   if(isset($_POST["selectstate"])){
// Capture selected country
$selectstate = $_POST["selectstate"];

// Define country and city array
$query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        $row1=mysql_fetch_array($query1);

    // Display city dropdown based on country name
   if($selectstate !== 'Select'){

    foreach($row1[$selectstate] as $value){
        echo "<option>". $value . "</option>";
    }

   }
   }
   ?>

 </select>

        </div>
        <div class="clearfix"> </div>
        </div>
</code>```

<p>jQuery-AJAX code is below.         </p>

```<code>     <script type="text/javascript" src="http://code.jquery.com/jquery.js">
  </script>
  <script type="text/javascript">
  $(document).ready(function(){
   $("select.selectstate").change(function(){
    var selectedstate = $(".selectstate option:selected").val();
    $.ajax({
        type: "POST",
        url: "locpac.php",
        data: { selectstate : selectedstate }
    }).done(function(data){
        $("#response").html(data);
    });
   });
   });
   </script>
</code>```

答:
Your code has so many problems, hope this work

```<code><div class="col-md-6 form-group2">
    <?php
       include("connection.php");
       $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
    ?>
    <label class='control-label'>Select State</label>";
    <select required name='selectstate' id="selectstate">
        <option>Select</option>
        <?php
            while($row1=mysql_fetch_array($query1))
            {
                ?>
                <option value="<?php echo $row1['id'];?>"><?php echo $row1['location'];?></option>
                <?php
            }
            ?>
        </select>

        </div>
        <div class="col-md-6 form-group2">

           <label class='control-label'>City:</label>
           <select id="location"></select>

        </div>
        <div class="clearfix"> </div>
        </div>

<script type="text/javascript" src="http://code.jquery.com/jquery.js">
  </script>
  <script type="text/javascript">
      $(document).ready(function(){
         $("#selectstate").change(function(){
             var selectedstate = $(this).val();
             $.ajax({
                type: "POST",
                url: "location.php",
                data: "selectstate="+selectedstate,
             }).done(function(data){
                 $("#location").html(data);
             });
          });
       });
   </script>
</code>```

create a new page I call here 'location.php and put the below code there

```<code><?php
    if(isset($_POST["selectstate"])){
    // Capture selected country
        $selectstate = $_POST["selectstate"];
        $query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        if($selectstate !== 'Select'){

            while($value = mysql_fetch_array($query1)) {
                ?>
                   <option><?php $value['field-name'];?></option>
                <?php
            }

       }
   }
  ?>
</code>```

Body:
I have two dropdown select option. First is for select State and second is for select city. When any one select from state dropdown then related content should be shown on second select option (that will be related city.). I have some code, but it is not working.

        <?php
   include("connection.php");
   $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        echo" Select State";
        echo" <select required name='selectstate'>";
        echo"<option>Select</option>";
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }
        echo" </select>";
       ?>

         City:
     <select>

            <?php
   if(isset($_POST["selectstate"])){
// Capture selected country
$selectstate = $_POST["selectstate"];

// Define country and city array
$query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        $row1=mysql_fetch_array($query1);

    // Display city dropdown based on country name
   if($selectstate !== 'Select'){

    foreach($row1[$selectstate] as $value){
        echo "<option>". $value . "</option>";
    }

   }
   }
   ?>

 </select>

jQuery-AJAX code is below.

Body:
Your code has so many problems, hope this work

<div class="col-md-6 form-group2">
    <?php
       include("connection.php");
       $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
    ?>
    <label class='control-label'>Select State</label>";
    <select required name='selectstate' id="selectstate">
        <option>Select</option>
        <?php
            while($row1=mysql_fetch_array($query1))
            {
                ?>
                <option value="<?php echo $row1['id'];?>"><?php echo $row1['location'];?></option>
                <?php
            }
            ?>
        </select>

        </div>
        <div class="col-md-6 form-group2">

           <label class='control-label'>City:</label>
           <select id="location"></select>

        </div>
        <div class="clearfix"> </div>
        </div>

<script type="text/javascript" src="http://code.jquery.com/jquery.js">
  </script>
  <script type="text/javascript">
      $(document).ready(function(){
         $("#selectstate").change(function(){
             var selectedstate = $(this).val();
             $.ajax({
                type: "POST",
                url: "location.php",
                data: "selectstate="+selectedstate,
             }).done(function(data){
                 $("#location").html(data);
             });
          });
       });
   </script>

create a new page I call here 'location.php and put the below code there

<?php
    if(isset($_POST["selectstate"])){
    // Capture selected country
        $selectstate = $_POST["selectstate"];
        $query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        if($selectstate !== 'Select'){

            while($value = mysql_fetch_array($query1)) {
                ?>
                   <option><?php $value['field-name'];?></option>
                <?php
            }

       }
   }
  ?>


问:
jQuery hover effect uses opacity, which IE doesn't support
Below is my code for use on this page: here

```<code>$(document).ready(function(){
$('.jcarousel-skin-tango a').hover(
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 1);

        },
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 0);

        }
    )
});
</code>```

The problem lies within IE 8 and below. When you hover over any of the slide images, the hover turns to black (because IE doesn't support 'opacity'). I basically need a new way of writing this so the same effect is achieved without a grey/black box appearing in IE.  Any ideas ?

答:
This is not about transparent pngs. I had a similar problem. Just set a background-color on the element right before the transition (and you can remove it right after).

```<code>$(document).ready(function(){
 $('.jcarousel-skin-tango a').hover(
         function() {
             $(this).find('.rollover').stop().addClass('transition').fadeIn(500, function(){
                  $(this).removeClass('transition');
             });
         },
         function() {
             $(this).find('.rollover').stop().addClass('transition').fadeOut(500, function(){
                  $(this).removeClass('transition');
             });
         }
     )
 });
</code>```

On your stylesheet:

```<code>.transition { background-color: #b1ab1a /* the nearest color of the parent background */
</code>```

Body:
Below is my code for use on this page: here

$(document).ready(function(){
$('.jcarousel-skin-tango a').hover(
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 1);

        },
        function() {
            $(this).find('.rollover').stop().fadeTo(500, 0);

        }
    )
});

The problem lies within IE 8 and below. When you hover over any of the slide images, the hover turns to black (because IE doesn't support 'opacity'). I basically need a new way of writing this so the same effect is achieved without a grey/black box appearing in IE.  Any ideas ?

Body:
This is not about transparent pngs. I had a similar problem. Just set a background-color on the element right before the transition (and you can remove it right after).

$(document).ready(function(){
 $('.jcarousel-skin-tango a').hover(
         function() {
             $(this).find('.rollover').stop().addClass('transition').fadeIn(500, function(){
                  $(this).removeClass('transition');
             });
         },
         function() {
             $(this).find('.rollover').stop().addClass('transition').fadeOut(500, function(){
                  $(this).removeClass('transition');
             });
         }
     )
 });

On your stylesheet:

.transition { background-color: #b1ab1a /* the nearest color of the parent background */