问:
jquery function unexpected token error
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

```<code><div class="primary-colors">
    <h3>Primary Colors</h3>
    <div class="primary-range-container">
        <input type="range" min="1" max="15" value ="5" class="primary-slider"><span class="value">0</span>
    </div>
    <hr>
    <div class="color-container">
        <div class="color primary-color-1"></div>
        <div class="color primary-color-2"></div>
        <div class="color primary-color-3"></div>
        <div class="color primary-color-4"></div>
        <div class="color primary-color-5"></div>
        <div class="color primary-color-6"></div>
        <div class="color primary-color-7"></div>
        <div class="color primary-color-8"></div>
        <div class="color primary-color-9"></div>
        <div class="color primary-color-10"></div>
        <div class="color primary-color-11"></div>
    </div>
</div>
</code>```

And the javascript code looks like this

```<code>var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);
</code>```

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

答:
You have syntactical error. function should be defined as
$.fn.colorBlocks = function(colorContainer, rangeSlider) {
.

this.change(function() {
...
});

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks = function(colorContainer, rangeSlider) {
  this.change(function() {
    var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
   });
  this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);```
<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>
<div class="primary-colors">
 <h3>Primary Colors</h3>
 <div class="primary-range-container">
  <input type="range" min="1" max="15" value ="5" class="primary-slider">
  <span class="value">0</span>
 </div>
 <hr>
 <div class="color-container">
  <div class="color primary-color-1"></div>
  <div class="color primary-color-2"></div>
  <div class="color primary-color-3"></div>
  <div class="color primary-color-4"></div>
  <div class="color primary-color-5"></div>
  <div class="color primary-color-6"></div>
  <div class="color primary-color-7"></div>
  <div class="color primary-color-8"></div>
  <div class="color primary-color-9"></div>
  <div class="color primary-color-10"></div>
  <div class="color primary-color-11"></div>
 </div>
</div></code>```

Title: jquery function unexpected token error

Body:
So I am trying to write a reusable function in jquery for a style guide I'm creating.  The goal of the function is to hide/show a number of divs based on the value of a range slider.

The html code looks like this

Primary Colors

        <input type="range" min="1" max="15" value ="5" class="primary-slider">0

And the javascript code looks like this

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks(colorContainer, rangeSlider) {
    this.change(function() {
        var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
    }
    this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);

The expected result in my head would be that the function would work, but so far I'm just not seeing anything and instead the compiler is giving me Parsing error: Unexpected Token {.

Any advice or better methods would be incredibly helpful.

Body:
You have syntactical error. function should be defined as
$.fn.colorBlocks = function(colorContainer, rangeSlider) {
.

this.change(function() {
...
});

var primarySlider = $(".primary-slider");
var primaryColorContainer = $(".primary-colors .color");
var primaryValue = $('.primary-range-container .value');

$.fn.colorBlocks = function(colorContainer, rangeSlider) {
  this.change(function() {
    var number = $(rangeSlider).val();
        $(colorContainer).hide();
        $(colorContainer).hide().slice( 0, number ).show();
   });
  this.change();
}

primarySlider.colorBlocks(primaryColorContainer, primaryValue);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="primary-colors">
 <h3>Primary Colors</h3>
 <div class="primary-range-container">
  <input type="range" min="1" max="15" value ="5" class="primary-slider">
  <span class="value">0</span>
 </div>
 <hr>
 <div class="color-container">
  <div class="color primary-color-1"></div>
  <div class="color primary-color-2"></div>
  <div class="color primary-color-3"></div>
  <div class="color primary-color-4"></div>
  <div class="color primary-color-5"></div>
  <div class="color primary-color-6"></div>
  <div class="color primary-color-7"></div>
  <div class="color primary-color-8"></div>
  <div class="color primary-color-9"></div>
  <div class="color primary-color-10"></div>
  <div class="color primary-color-11"></div>
 </div>
</div>


来源: stackexchange

问:
Google Calendar/FullCalendar not loading in Android WebView
I have a WebView in Android that loads a web app that has an embedded Google Calendar/FullCalendar.  That calendar loads in mobile browsers but won't load in the WebView.

I have tried webSettings.setJavaScriptEnabled(true); but that doesn't get it to load either.

```<code>public class WebView extends AppCompatActivity {

    android.webkit.WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        myWebView = (android.webkit.WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.loadUrl("mywebsite.com");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState ) {
        super.onSaveInstanceState(outState);
        myWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        myWebView.restoreState(savedInstanceState);
    }
}
</code>```

Does anyone know what I may need to enable/do to get an embedded Google Calendar/FullCalendar to load in a WebView?

答:
Set the user agent in the onCreate:

```<code>myWebView.getSettings();.setUserAgentString("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a WebView in Android that loads a web app that has an embedded Google Calendar/FullCalendar.  That calendar loads in mobile browsers but won't load in the WebView.

I have tried webSettings.setJavaScriptEnabled(true); but that doesn't get it to load either.

public class WebView extends AppCompatActivity {

    android.webkit.WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        myWebView = (android.webkit.WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.getSettings().setDomStorageEnabled(true);
        myWebView.loadUrl("mywebsite.com");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState ) {
        super.onSaveInstanceState(outState);
        myWebView.saveState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        myWebView.restoreState(savedInstanceState);
    }
}

Does anyone know what I may need to enable/do to get an embedded Google Calendar/FullCalendar to load in a WebView?

Body:
Set the user agent in the onCreate:

myWebView.getSettings();.setUserAgentString("Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36");


问:
c# Switch case not working
I'm trying to check a value by using a switch:

private void btnInput1Rste_Click(object sender, EventArgs e)
{
    switch (sender == btnInput1Rste)
    {
        case "1": currentButtonPressedRste = 1;
            break;
    }
}
```

It gives the error as follows:

can't convert type 'string' to 'bool'

However, when i try to convert it to a boolean it says:

a constant value is expected.

How do I fix it?

When it works it's supposed to check 3 values. (not with just this switch)

答: sender == btnInput1Rste is a boolean expression; the result is either true or false. Frankly, you probably just want an if/else here. You probably can do a switch with case true: but...

Title: c# Switch case not working

Body:
I'm trying to check a value by using a switch:

private void btnInput1Rste_Click(object sender, EventArgs e)
{
    switch (sender == btnInput1Rste)
    {
        case "1": currentButtonPressedRste = 1;
            break;
    }
}

It gives the error as follows:

can't convert type 'string' to 'bool'

However, when i try to convert it to a boolean it says:

a constant value is expected.

How do I fix it?

When it works it's supposed to check 3 values. (not with just this switch)


问:
Does Sonarqube supports Xamarin for code quality?
I am working on a Xamarin project. I would like to check code quality with sonarqube. I see there is a support for .net/c# project. I have followed the instruction here for Xamarin.I was able to do the first two steps  Begin and Rebuild. When i execute the third step "end"

SonarQube.Scanner.MSBuild.exe end

I am getting below error

```<code>mono /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Scanner.MSBuild.exe end
SonarQube Scanner for MSBuild 2.3.2
Default properties file was found at /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Analysis.xml
Loading analysis properties from /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Analysis.xml
Post-processing started.
SONAR_SCANNER_OPTS is not configured. Setting it to the default value of -Xmx1024m
Calling the SonarQube Scanner...
Execution failed. The specified executable does not exist: /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/sonar-scanner-3.0.3.778\bin\sonar-scanner.bat
The SonarQube Scanner did not complete successfully
13:17:17.361  Creating a summary markdown file...
13:17:17.366  Post-processing failed. Exit code: 1
</code>```

答:
Now SonarQube.Scanner.MSBuild.exe has the support for mac, it works.

The sonarqube for MSBuild version 3.0.2 was not supporting Non window OS, now the SonarQube.Scanner.MSBuild.exe 4.0 has the support for mac

Also the sonarC# Plugin has to be > 6.6 to run the analysis on mac os version.

Please check the below link,
https://forums.xamarin.com/discussion/111935/source-code-analysis-for-xamarin-project-with-sonarqube-on-mac/p1?new=1

Body:
I am working on a Xamarin project. I would like to check code quality with sonarqube. I see there is a support for .net/c# project. I have followed the instruction here for Xamarin.I was able to do the first two steps  Begin and Rebuild. When i execute the third step "end"

SonarQube.Scanner.MSBuild.exe end

I am getting below error

mono /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Scanner.MSBuild.exe end
SonarQube Scanner for MSBuild 2.3.2
Default properties file was found at /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Analysis.xml
Loading analysis properties from /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/SonarQube.Analysis.xml
Post-processing started.
SONAR_SCANNER_OPTS is not configured. Setting it to the default value of -Xmx1024m
Calling the SonarQube Scanner...
Execution failed. The specified executable does not exist: /Users/apple/Downloads/sonar-scanner-msbuild-2.3.2.573/sonar-scanner-3.0.3.778\bin\sonar-scanner.bat
The SonarQube Scanner did not complete successfully
13:17:17.361  Creating a summary markdown file...
13:17:17.366  Post-processing failed. Exit code: 1


问:
Java parallelStream not showing correct result
I was doing some performance evaluation of Java aggeragate operations to iterate over collections. I was doing an evaluation of performance stream and parallelStream. But I found that the output of parallelStream is wrong most of the times. For example in the following code i got wrong output from parallelStream more than 80% of the time:

```<code>    public class ParallelStreamPerformance {
    static int totaleven = 0;
    public static void main(String[] args) {
        List<Integer> randomList = new ArrayList<>();
        Random rnd = new Random();
        for(int i = 0 ;i < 1000;i++) {
            int r = rnd.nextInt(500000);
            randomList.add(r);
        }

        long s1 = System.currentTimeMillis();

        randomList.stream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);

        totaleven = 0;
        long s2 = System.currentTimeMillis();

        randomList.parallelStream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e2 = System.currentTimeMillis();
        System.out.println(e2 - s2);
    }
    public static void count() {
        totaleven++;
    }
}
</code>```

My question is: Am I using parallelStream in a wrong way? Is there any way to ensure the correctness of parallelStream.
Thanks

答: What's wrong with parallel stream result? If it is too small then most likely you have problem with totaleven++ as it is not thread safe. Use AtomicInteger or any other thread safe solution.

Body:
I was doing some performance evaluation of Java aggeragate operations to iterate over collections. I was doing an evaluation of performance stream and parallelStream. But I found that the output of parallelStream is wrong most of the times. For example in the following code i got wrong output from parallelStream more than 80% of the time:

    public class ParallelStreamPerformance {
    static int totaleven = 0;
    public static void main(String[] args) {
        List<Integer> randomList = new ArrayList<>();
        Random rnd = new Random();
        for(int i = 0 ;i < 1000;i++) {
            int r = rnd.nextInt(500000);
            randomList.add(r);
        }

        long s1 = System.currentTimeMillis();

        randomList.stream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e1 = System.currentTimeMillis();
        System.out.println(e1 - s1);

        totaleven = 0;
        long s2 = System.currentTimeMillis();

        randomList.parallelStream().filter(e -> e%2 ==0).forEach(e -> count());
        System.out.println("Even: "+totaleven);
        long e2 = System.currentTimeMillis();
        System.out.println(e2 - s2);
    }
    public static void count() {
        totaleven++;
    }
}

My question is: Am I using parallelStream in a wrong way? Is there any way to ensure the correctness of parallelStream.
Thanks


问:
How to change jQuery panel href?
I have an  record with an href to a panel. In differing states, I would like the button to open different panels.  I've tried changing the href, but that doesn't appear to be enough, as the button always opens the original panel.

The a record is defined like this ...

```<code>  <li><a href="#panel1" id="Xpanel" class="icon fa-crop"> </a>
</code>```

When clicked, panel1 is displayed and works great ...

I'm changing the href for the a record like so ...

```<code>   var id = document.getElementById('Xpanel');
   $(id).attr('href', "#panel2");
</code>```

In the Safari debugger, I can see that all is changing, but the button always opens the original #panel1.

Do I need to rebind the  records href somehow ???

答:
There's no need to grab your element with document.getElementById(), and then again with jQuery. Based on your markup, the code below should work:

```<code>// Use jQuery's id selector
$("#Xpanel").attr('href', "#panel2");
</code>```

If the code above isn't sufficient, then I would be looking at the event that fires off the code above. Is it being called before the use clicks the link?

Take a look a jQuery's selector docs.

Title: How to change jQuery panel href?

Body:
I have an  record with an href to a panel. In differing states, I would like the button to open different panels.  I've tried changing the href, but that doesn't appear to be enough, as the button always opens the original panel.

The a record is defined like this ...

When clicked, panel1 is displayed and works great ...

I'm changing the href for the a record like so ...

   var id = document.getElementById('Xpanel');
   $(id).attr('href', "#panel2");

In the Safari debugger, I can see that all is changing, but the button always opens the original #panel1.

Do I need to rebind the  records href somehow ???

Body:
There's no need to grab your element with document.getElementById(), and then again with jQuery. Based on your markup, the code below should work:

// Use jQuery's id selector
$("#Xpanel").attr('href', "#panel2");

If the code above isn't sufficient, then I would be looking at the event that fires off the code above. Is it being called before the use clicks the link?

Take a look a jQuery's selector docs.


问:
Access to json variable (node.js)
How can I get the value "success" if the value that stands in place "Everlasting hair" is changing?</p>

```<code>{
'Everlasting hair' :
   { succes : true,
     volume:'12'
   }
}
</code>```

答:
You can discover the property names in the object via for-in or Object.keys. Object.keys, for instance, will give you an array of the object's own, enumerable properties. If you know for sure there will only be one, then:

```<code>var success = yourObject[Object.keys(yourObject)[0]].succes;
// Another s here? It's missing in the question -----------^
</code>```

On cutting-edge JavaScript engines with Object.values (new in ES2017, but polyfillable), as Keith points out if you don't need the name you can use Object.values instead:

```<code>var success = Object.values(yourObject)[0].succes;
// Another s here? It's missing in the question -^
</code>```

Title: Access to json variable (node.js)

Body:
How can I get the value "success" if the value that stands in place "Everlasting hair" is changing?

{
'Everlasting hair' :
   { succes : true,
     volume:'12'
   }
}

Body:
You can discover the property names in the object via for-in or Object.keys. Object.keys, for instance, will give you an array of the object's own, enumerable properties. If you know for sure there will only be one, then:

var success = yourObject[Object.keys(yourObject)[0]].succes;
// Another s here? It's missing in the question -----------^

On cutting-edge JavaScript engines with Object.values (new in ES2017, but polyfillable), as Keith points out if you don't need the name you can use Object.values instead:

var success = Object.values(yourObject)[0].succes;
// Another s here? It's missing in the question -^


问:
Immutable actions with Javascript ES6 Map
Is it possible to perform immutable actions with a JS Map?
How would you set or delete an item without altering the original Map?

答:
Answer for the first part of question:

If you want to make your map immutable you can use Proxy to handle all getters/setters to the map, example is bellow:

IMPORTANT: This is slow and memory consuming way. Do not do this in real life. You was awared.

const map = new Map();
map.set(1, 'someValue');
const freezeThemAll = {
  get: (target, propName) => {
    if (propName === 'set') throw 'Sorry, map is immutable!';

    if (propName === 'get') {
      return target.get.bind(target);
    }

    return target[propName];
  }
};
const immutable = new Proxy(map, freezeThemAll);
try {
  console.log(`Trying to get some value: ${immutable.get(1)}`);
  console.log(`Trying to set some value: ${immutable.set(2, 'other value')}`);
} catch (e) {
  console.log(e);
}```

But, if you really need this, try to search for related libs, like Mori or immutable.js

Body:
Answer for the first part of question:

If you want to make your map immutable you can use Proxy to handle all getters/setters to the map, example is bellow:

IMPORTANT: This is slow and memory consuming way. Do not do this in real life. You was awared.

const map = new Map();
map.set(1, 'someValue');
const freezeThemAll = {
  get: (target, propName) => {
    if (propName === 'set') throw 'Sorry, map is immutable!';

    if (propName === 'get') {
      return target.get.bind(target);
    }

    return target[propName];
  }
};
const immutable = new Proxy(map, freezeThemAll);
try {
  console.log(`Trying to get some value: ${immutable.get(1)}`);
  console.log(`Trying to set some value: ${immutable.set(2, 'other value')}`);
} catch (e) {
  console.log(e);
}

But, if you really need this, try to search for related libs, like Mori or immutable.js


问:
Method that takes in integers or strings. C++
So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.

For instance

the method (called up):

```<code> //goes to coordinates 5,6 (creates side of 5 with a char called 'X')
 triangle(5,6,5,'X',"",5);
</code>```

Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type

```<code>triangle(5,6,5,'X',"I love code", );
</code>```

But an error would pop up and say that it needs one more parameter.

I've done some searching on boolean methods, like in java when you can type

```<code>public static void randommethod bool(/*params*\){

  /*Enter code if its either true or false*/

}
</code>```

But I've come up empty with any trying to find a method like that in C++.

答:
I'm not really sure what each parameter corresponds to in your function, but if you want the last parameter to be optional, then you need to explicitly make it an optional parameter. When you create the function definition/prototype, you just assign the optional parameter the default value. If no value is provided, the default value is used.

For example, if I have a function to draw a triangle, I could write:

```<code>public void triangle(int base, int side1, int side2=1)
{
    ....
}
</code>```

The side2 variable is optional. If no value is provided, 1 becomes the value. You could give the optional variable some kind of nonsense value that the function will detect and perform actions accordingly. Just make sure that the optional parameter is last in the list of parameters, otherwise it will give errors.

Hope this helps.

Body:
So right now I'm trying to make a graphic C header file that could create shapes like triangle's, boxes, and circles in C++. Its supposed to help kids in my class, but I also want to be able for them to type stuff in the shapes. But I was wondering if there was a place holder for a integer in case you don't to cout<< a int.

For instance

the method (called up):

 //goes to coordinates 5,6 (creates side of 5 with a char called 'X')
 triangle(5,6,5,'X',"",5);

Will make a triangle with 2 sides of 5 units of X and have a regular base. But what if the user just wanted to print out the string w/o the integer. Then they would type

triangle(5,6,5,'X',"I love code", );

But an error would pop up and say that it needs one more parameter.

I've done some searching on boolean methods, like in java when you can type

public static void randommethod bool(/*params*\){

  /*Enter code if its either true or false*/

}

But I've come up empty with any trying to find a method like that in C++.

Body:
I'm not really sure what each parameter corresponds to in your function, but if you want the last parameter to be optional, then you need to explicitly make it an optional parameter. When you create the function definition/prototype, you just assign the optional parameter the default value. If no value is provided, the default value is used.

For example, if I have a function to draw a triangle, I could write:

public void triangle(int base, int side1, int side2=1)
{
    ....
}

The side2 variable is optional. If no value is provided, 1 becomes the value. You could give the optional variable some kind of nonsense value that the function will detect and perform actions accordingly. Just make sure that the optional parameter is last in the list of parameters, otherwise it will give errors.

Hope this helps.


问:
Loopback timeout(no response from server) when make a time consume request
I have a request which processes thousands of data. So sometimes It takes more then 5 minutes to complete.

But unfortunately loopback returns timeout(no response from server) before process is completed.

In nodejs request. You can remove request timeout for specific request by below code.

```<code>request.setTimeout(0)
</code>```

Can anyone tell me how can i do this for loopback remote method?

答:
I am not quite sure of this but you can give it a try as i feel this might work

You can create a interceptor for that particular route or all the routes in the server.js file.

```<code>app.all('/api/*', function(req, res, next){
    request.setTimeout(0); // this is the statement and pass it to the next middle ware func.
    next();
});
</code>```

If not you can also use a remote method for that route and add the
  same there.

Update

If you want it for a single api just use

```<code>app.all('<exact api path>', function(req, res, next){
    request.setTimeout(0); // this is the statement and pass it to the next middle ware func.
    next();
});
</code>```

Body:
I have a request which processes thousands of data. So sometimes It takes more then 5 minutes to complete.

But unfortunately loopback returns timeout(no response from server) before process is completed.

In nodejs request. You can remove request timeout for specific request by below code.

request.setTimeout(0)

Can anyone tell me how can i do this for loopback remote method?

Body:
I am not quite sure of this but you can give it a try as i feel this might work

You can create a interceptor for that particular route or all the routes in the server.js file.

app.all('/api/*', function(req, res, next){
    request.setTimeout(0); // this is the statement and pass it to the next middle ware func.
    next();
});

If not you can also use a remote method for that route and add the
  same there.

Update

If you want it for a single api just use

app.all('<exact api path>', function(req, res, next){
    request.setTimeout(0); // this is the statement and pass it to the next middle ware func.
    next();
});


问:
Android studio - Use library from Project in another project
I have jar file(use like library) in lib folder in android studio project.

I added another android studio project to the first project.

Added another project steps: File -> New -> Import Module.

I want to use with the file jar from the first project in the another project that I added.

How can I do this?

答: you should add that library again to your new project by following this file -> new -> import module.</p>


问:
Prevent Chrome from automatically suggest credit card numbers on my site
I have an internal app for my company and we usually ask for credit card information, since a given user often processed several credit cards a day, it is not advisable to have on the autocomplete, we added an autocomplete="off" attribute to our inputs to prevent this, but chrome
seems to ignore this, and it is still showing suggestions to our users. We have removed the autocomplete from all the other fields our users requested, but this one just won't go

I have seen several questions regarding this topic but they're all about passwords and my question seems to be a bit more specific, so

Here is how the input tag looks like:

```<code><input autocomplete="off" class="form-control"
       data-card-number="data-card-number"
       data-val="true"
       data-val-creditcard="The CardNumber field is not a valid credit card number."
       data-val-required="The CardNumber field is required."
       id="CreditCardInfo_CardNumber"
       name="manolo"
       style="padding-left: 55px;"
       type="text"
       value="">
</code>```

What should I do to prevent Chrome from suggesting credit cards numbers?

It would be better if I could do it in HTML only.

Disable form autofill in Chrome without disabling autocomplete [duplicate]

Disabling Chrome Autofill

答:
Try to change your input name to something else, for example randomWord

```<code><input type="text" name="randomWord">
</code>```

Body:
I have an internal app for my company and we usually ask for credit card information, since a given user often processed several credit cards a day, it is not advisable to have on the autocomplete, we added an autocomplete="off" attribute to our inputs to prevent this, but chrome
seems to ignore this, and it is still showing suggestions to our users. We have removed the autocomplete from all the other fields our users requested, but this one just won't go

I have seen several questions regarding this topic but they're all about passwords and my question seems to be a bit more specific, so

Here is how the input tag looks like:

<input autocomplete="off" class="form-control"
       data-card-number="data-card-number"
       data-val="true"
       data-val-creditcard="The CardNumber field is not a valid credit card number."
       data-val-required="The CardNumber field is required."
       id="CreditCardInfo_CardNumber"
       name="manolo"
       style="padding-left: 55px;"
       type="text"
       value="">

What should I do to prevent Chrome from suggesting credit cards numbers?

It would be better if I could do it in HTML only.

Disable form autofill in Chrome without disabling autocomplete [duplicate]

Disabling Chrome Autofill

Body:
Try to change your input name to something else, for example randomWord

<input type="text" name="randomWord">


问:
Populating an array defined in a structure
I am trying to populate an array of vertices with float coordinates but its not going well. I define multiple Structures as shown below:

```<code>typedef struct _Polyg
{
   float *verts;
   int nverts;
} Polyg;

typedef struct _Layer
{
   // array of polygons
   Polyg *polys;
   int npolys;
} Layer;
</code>```

So I have Layers, which consist of polygons which consist of vertices essentially. I then attempt to populate the data structure arrays as following:

```<code>void loadLayers(Layer *layers)
{
    // takes an array of layers and fills them with data
    layers[0].npolys = 2;
    layers[0].polys[0].nverts = 8;
    layers[0].polys[0].verts = {     //ERROR IS HERE
    100.0f, 134.0f, 0.0f,
    100.0f, 115.0f, 0.0f,
    119.0f, 98.0f, 0.0f,
    119.0f, 0.0f, 0.0f,
    7.0f, 0.0f, 0.0f,
    3.0f, 5.0f, 0.0f,
    3.0f, 130.0f, 0.0f,
    7.0f, 134.0f, 0.0f, };
}
</code>```

So in this exmaplen I'm attempting to populate the first polygon of the first layer with the vertex coordinates (X, Y, Z). However I am getting errors:

Expected an Expression

and

C2059 - syntax error: '{'

on the line I commented above.

Really lost with what's going wrong here.

答:
With the line: layers[0].polys[0].verts = { you're trying to do initializer-list assignment to a float* which is only allowed if:

An assignment expression, where list-initialization initializes the parameter of the overloaded operator=

float* is a built in type, thus it's built in assignment operator will only take a float*. Meaning that you cannot assign an initializer_list<float> to a float*.

Instead consider vector<float> which does have the builtin operator= (initializer_list<float>) defined: http://en.cppreference.com/w/cpp/container/vector/operator%3D

Additionally consider elimination of the _Polyg and _Layer structs all together, in favor of vectors.

Body:
I am trying to populate an array of vertices with float coordinates but its not going well. I define multiple Structures as shown below:

typedef struct _Polyg
{
   float *verts;
   int nverts;
} Polyg;

typedef struct _Layer
{
   // array of polygons
   Polyg *polys;
   int npolys;
} Layer;

So I have Layers, which consist of polygons which consist of vertices essentially. I then attempt to populate the data structure arrays as following:

void loadLayers(Layer *layers)
{
    // takes an array of layers and fills them with data
    layers[0].npolys = 2;
    layers[0].polys[0].nverts = 8;
    layers[0].polys[0].verts = {     //ERROR IS HERE
    100.0f, 134.0f, 0.0f,
    100.0f, 115.0f, 0.0f,
    119.0f, 98.0f, 0.0f,
    119.0f, 0.0f, 0.0f,
    7.0f, 0.0f, 0.0f,
    3.0f, 5.0f, 0.0f,
    3.0f, 130.0f, 0.0f,
    7.0f, 134.0f, 0.0f, };
}

So in this exmaplen I'm attempting to populate the first polygon of the first layer with the vertex coordinates (X, Y, Z). However I am getting errors:

Expected an Expression

and

C2059 - syntax error: '{'

on the line I commented above.

Really lost with what's going wrong here.


问:
NullInjectorError: No provider for AngularFirestore
I'm learning Angular looking for help in fixing the error:
I'm following this link : https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
to create a angular small app with angular2 and angularfirestore2

but when I hit ng serve I am getting the below error in browser console..

```<code>StaticInjectorError[AngularFirestore]:
  StaticInjectorError[AngularFirestore]:
    NullInjectorError: No provider for AngularFirestore!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10585)
    at NgModuleRef_.get (core.js:11806)
    at resolveDep (core.js:12302)
</code>```

I tried googling it but didn't find the exact solution nothing worked for me :(,

Here is what I followed:
1) Installed Node Version 8.9.1
2) npm install -g @angular/cli --> Version 1.5.2
3) ng new 'project-name'
4) npm install angularfire2 firebase --save

Here are my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase)
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}
```

<p>app.component.ts:</p>

<pre class="lang-ts prettyprint-override"><code>import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(db: AngularFirestore) {}
}
</code>```

environemnt.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxxxx',
    authDomain: 'aaaaaaa',
    databaseURL: 'bbbbbbbbbbbbbbbbbb',
    projectId: 'aaaaaaaaaaaaaa',
    storageBucket: 'aaaaaaaaaaaa',
    messagingSenderId: 'aaaaaaaaaaaaa'
  }
};
```

then ng serve, and I am getting the above error...

答:
Open: ./src/app/app.module.ts

And import Firebase Modules at the top:

import { environment } from '../environments/environment';

  import { AngularFireModule } from 'angularfire2';

  import { AngularFirestoreModule } from 'angularfire2/firestore';

And VERY IMPORTANT:

Remember to update 'imports' in NgModule:

```<code>@NgModule({
  declarations: [
    AppComponent,
    OtherComponent // Add other components here
    ...
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase, 'your-APP-name-here'),
    AngularFirestoreModule
  ],
  ...
})
</code>```

Give it a try, it shall now work.

For detailed information follow the angularfire2 documentation:

https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md

Good luck!

ContentLicense: CC BY-SA 4.0

Body:
I'm learning Angular looking for help in fixing the error:
I'm following this link : https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md
to create a angular small app with angular2 and angularfirestore2

but when I hit ng serve I am getting the below error in browser console..

StaticInjectorError[AngularFirestore]:
  StaticInjectorError[AngularFirestore]:
    NullInjectorError: No provider for AngularFirestore!
    at _NullInjector.get (core.js:923)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveToken (core.js:1211)
    at tryResolveToken (core.js:1153)
    at StaticInjector.get (core.js:1024)
    at resolveNgModuleDep (core.js:10585)
    at NgModuleRef_.get (core.js:11806)
    at resolveDep (core.js:12302)

I tried googling it but didn't find the exact solution nothing worked for me :(,

Here is what I followed:
1) Installed Node Version 8.9.1
2) npm install -g @angular/cli --> Version 1.5.2
3) ng new 'project-name'
4) npm install angularfire2 firebase --save

Here are my app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { environment } from '../environments/environment';

@NgModule({
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase)
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

app.component.ts:

import { Component } from '@angular/core';
import { AngularFirestore } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
  constructor(db: AngularFirestore) {}
}

environemnt.ts:

export const environment = {
  production: false,
  firebase: {
    apiKey: 'xxxxx',
    authDomain: 'aaaaaaa',
    databaseURL: 'bbbbbbbbbbbbbbbbbb',
    projectId: 'aaaaaaaaaaaaaa',
    storageBucket: 'aaaaaaaaaaaa',
    messagingSenderId: 'aaaaaaaaaaaaa'
  }
};

then ng serve, and I am getting the above error...

Body:
Open: ./src/app/app.module.ts

And import Firebase Modules at the top:

import { environment } from '../environments/environment';

  import { AngularFireModule } from 'angularfire2';

  import { AngularFirestoreModule } from 'angularfire2/firestore';

And VERY IMPORTANT:

Remember to update 'imports' in NgModule:

@NgModule({
  declarations: [
    AppComponent,
    OtherComponent // Add other components here
    ...
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase, 'your-APP-name-here'),
    AngularFirestoreModule
  ],
  ...
})

Give it a try, it shall now work.

For detailed information follow the angularfire2 documentation:

https://github.com/angular/angularfire2/blob/master/docs/install-and-setup.md

Good luck!


问:
How to change Content-Type in Flurl?
I have a .NET Core 2.0 WebApi application in which I have added the "Flurl.Http" (Version 2.1.0) NuGet package to my project.

I am trying to use Flurl to make a simple REST API call to one of Visual Studio Team Services' (VSTS) Api endpoints.

However, the particular VSTS api endpoint that I am calling requires that the Content-Type be set to "application/json-patch+json" instead of the typical "application/json".

In my Flurl call, I am using the "WithHeader()" method to try and set the Content-Type in the header of the request, but it is not working. Flurl seems to not allow me to override the default or standard Content-Type that is built into the PostJsonAsync method.

Does anyone know how to change the Content-Type of the request using Flurl? Or how to properly override the default behavior of the Content-Type in the Flurl configuration?

Thanks in advance!

My code:

```<code>public bool CreateNewBug(NewBugRequest newBugRequest)
{
    return _apiUrlToCreateNewBug.WithHeader("Authorization", "Basic Base64PersonalAccessTokenGoesHere")
                                .WithHeader("Content-Type", "application/json-patch+json")
                                .PostJsonAsync(newBugRequest.Fields)
                                .Result
                                .IsSuccessStatusCode;
}
</code>```

(This code works, but the response from the VSTS api is that the Content-Type is not allowed and needs to be changed to "application/json-patch+json", which is what I tried to set it to in the header.)

答:
I was able to figure it out and find a working solution to my problem.

Here is the updated version of my working code:

```<code>public HttpResponseMessage CreateNewBug(NewBugRequest newBugRequest)
{
    return _apiUrlToCreateNewBug.AllowAnyHttpStatus()
                                .WithBasicAuth("", _personalAccessTokenForBasicAuth)
                                .PostAsync(new StringContent(JsonConvert.SerializeObject(newBugRequest.Fields), Encoding.UTF8, "application/json-patch+json"))
                                .Result;
}
</code>```

The PostAsync method takes in an HttpContent object. HttpContent is an abstract class. Once I figured out all the concrete classes that implement the abstract class HttpContent, then I chose the one that best fit my situation and plugged it into the PostAsync method.

In this case, the StringContent class was the one that best fit what I needed. One of StringContent's constructors takes in the Content-Type as one of its parameters. So I passed in my custom Content-Type and everything worked as expected.

Title: How to change Content-Type in Flurl?

Body:
I have a .NET Core 2.0 WebApi application in which I have added the "Flurl.Http" (Version 2.1.0) NuGet package to my project.

I am trying to use Flurl to make a simple REST API call to one of Visual Studio Team Services' (VSTS) Api endpoints.

However, the particular VSTS api endpoint that I am calling requires that the Content-Type be set to "application/json-patch+json" instead of the typical "application/json".

In my Flurl call, I am using the "WithHeader()" method to try and set the Content-Type in the header of the request, but it is not working. Flurl seems to not allow me to override the default or standard Content-Type that is built into the PostJsonAsync method.

Does anyone know how to change the Content-Type of the request using Flurl? Or how to properly override the default behavior of the Content-Type in the Flurl configuration?

Thanks in advance!

My code:

public bool CreateNewBug(NewBugRequest newBugRequest)
{
    return _apiUrlToCreateNewBug.WithHeader("Authorization", "Basic Base64PersonalAccessTokenGoesHere")
                                .WithHeader("Content-Type", "application/json-patch+json")
                                .PostJsonAsync(newBugRequest.Fields)
                                .Result
                                .IsSuccessStatusCode;
}

(This code works, but the response from the VSTS api is that the Content-Type is not allowed and needs to be changed to "application/json-patch+json", which is what I tried to set it to in the header.)

Body:
I was able to figure it out and find a working solution to my problem.

Here is the updated version of my working code:

public HttpResponseMessage CreateNewBug(NewBugRequest newBugRequest)
{
    return _apiUrlToCreateNewBug.AllowAnyHttpStatus()
                                .WithBasicAuth("", _personalAccessTokenForBasicAuth)
                                .PostAsync(new StringContent(JsonConvert.SerializeObject(newBugRequest.Fields), Encoding.UTF8, "application/json-patch+json"))
                                .Result;
}

The PostAsync method takes in an HttpContent object. HttpContent is an abstract class. Once I figured out all the concrete classes that implement the abstract class HttpContent, then I chose the one that best fit my situation and plugged it into the PostAsync method.

In this case, the StringContent class was the one that best fit what I needed. One of StringContent's constructors takes in the Content-Type as one of its parameters. So I passed in my custom Content-Type and everything worked as expected.


问:
How to retrieve summarized data from stored procedure with Entity Framework and .Net Core
Using .Net Core 1.1 with Entity Framework with SQL database

I have a stored procedure which produces summarized data for things like Number of Orders, percentage change on previous month Total value of order in month and does this for the last 12 months.

This is used to graphing in client script and so doesn't have a model (and I don't want one as its not a real object), but I need to get the data into a view model to pass to the view for graphing on the client.

I am sure this is quite common requirement for summarized data but I'm not sure how to do this?

Edit: Question isn't quite the same as the one identified, I have used store procedures in .net core previously but the data mapped to real entities, where as I am returning summarized data here which doesn't have a model and want to do this in the most appropriate way.

Thanks
Richard

答:
I achieved this in the end by creating a model with the following attributes:
[ComplexType]
[NotMapped]

This model contains properties to match the output of a stored procedure which I then call from my API


问:
Summary for the a specific branch
I have a tensorflow graph that has a complicated loss function for the training, but a simpler one for evaluation (they share ancestors). Essentially this

```<code>train_op = ... (needs more things in feed_dict etc.)
acc = .... (just needs one value for placeholer)
</code>```

to better understand what's going on, I added summaries. But calling

```<code>merged = tf.summary.merge_all()
</code>```

and then

```<code>(summ, acc) = session.run([merged, acc_eval], feed_dict={..})
</code>```

tensorflow complains that values for placeholders are missing.

答:
As far as I understand your question, to summary a specific tensorflow operation, you should run it specifically.

For example:

```<code># define accuracy ops
correct_prediction = tf.equal(tf.argmax(Y, axis=1), tf.argmax(Y_labels, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))

# summary_accuracy is the Summary protocol buffer you need to run,
# instead of merge_all(), if you want to summary specific ops
summary_accuracy = tf.summary.scalar('testing_accuracy', accuracy)

# define writer file
sess.run(tf.global_variables_initializer())
test_writer = tf.summary.FileWriter('log/test', sess.graph)

(summ, acc) = sess.run([summary_accuracy, accuracy], feed_dict={..})
test_writer.add_summary(summ)
</code>```

Also, you can use tf.summary.merge(), which is documented here.

Hope this help !

Title: Summary for the a specific branch

Body:
I have a tensorflow graph that has a complicated loss function for the training, but a simpler one for evaluation (they share ancestors). Essentially this

train_op = ... (needs more things in feed_dict etc.)
acc = .... (just needs one value for placeholer)

to better understand what's going on, I added summaries. But calling

merged = tf.summary.merge_all()

and then

(summ, acc) = session.run([merged, acc_eval], feed_dict={..})

tensorflow complains that values for placeholders are missing.

Body:
As far as I understand your question, to summary a specific tensorflow operation, you should run it specifically.

For example:

# define accuracy ops
correct_prediction = tf.equal(tf.argmax(Y, axis=1), tf.argmax(Y_labels, axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, dtype=tf.float32))

# summary_accuracy is the Summary protocol buffer you need to run,
# instead of merge_all(), if you want to summary specific ops
summary_accuracy = tf.summary.scalar('testing_accuracy', accuracy)

# define writer file
sess.run(tf.global_variables_initializer())
test_writer = tf.summary.FileWriter('log/test', sess.graph)

(summ, acc) = sess.run([summary_accuracy, accuracy], feed_dict={..})
test_writer.add_summary(summ)

Also, you can use tf.summary.merge(), which is documented here.

Hope this help !


问:
How can I expose the Math object properties to the window in JavaScript?
I want to expose the Math properties to the window in JavaScript. This way, I'd be able to do things like pow(n, n) instead of Math.pow(n, n).

I've tried using the following methods, but neither work.

for (var obj in Math) window[obj.name] = obj;```
</div>
</div>
</p>

<p>Returns undefined</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (var obj of Math) window[obj.name] = obj;</code>```

Throws error: Math object is not iterable.

答:
Grab Math's property names, then assign them to window.

const arr = Object.getOwnPropertyNames(Math);
arr.forEach(el => window[el] = Math[el]);
console.log(pow(7,2))```

Body:
I want to expose the Math properties to the window in JavaScript. This way, I'd be able to do things like pow(n, n) instead of Math.pow(n, n).

I've tried using the following methods, but neither work.

for (var obj in Math) window[obj.name] = obj;

Returns undefined

for (var obj of Math) window[obj.name] = obj;

Throws error: Math object is not iterable.


问:
mySQL select with old table and new table query
Hey all i am trying to figure out why my query code below does not seem to work:

```<code>SELECT id, itemName, itemRUDate, Sum(itemsSold) AS SumOf
FROM productr, productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC
</code>```

The table productr2010 is the OLD data and productr is a brand new table for this year (2011). When i try running the query i get this:

```<code>Column 'id' in field list is ambiguous
</code>```

I'm not sure what i need to do in order for it to grad data from both tables? I've also tried this:

```<code>SELECT productr.id, productr.itemName, productr.itemRUDate, Sum(productr.itemsSold) AS    SumOf
FROM productr, productr2010
WHERE productr.itemRUDate >= '2010/12/01' AND productr.itemRUDate <= '2011/01/22'
AND productr2010.itemRUDate >= '2010/12/01' AND productr2010.itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC
</code>```

And i get only the data from the productr table and not that and productr2010 table.

I'm sure i am just overlooking something easy..

UPDATE

Got it using this:

```<code>SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
UNION
SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC
</code>```

David

答:
First off, you are not specifying any JOIN conditions to link the records in the two tables.  You will, therefore, get a cartesian JOIN (a very large result set composed of every row in productr JOINed to every row in productr2010, almost certainly not what you want).

Secondly, you normally want to include all non-aggregated columns (in this case id, itemname and itemRUdate) in the GROUP BY clause.  MySQL, alone among major databases TTBOMK, allows you not to do this but you will get unspecified values from the non-GROUP BY columns if those columns do not contain all the same data.

Finally, because you are joining to tables with the same column names, you must prefix each reference to a column with the name of the table you want to get it from, otherwise the engine will decide for you where the data comes from.

ContentLicense: CC BY-SA 2.5

Body:
Hey all i am trying to figure out why my query code below does not seem to work:

SELECT id, itemName, itemRUDate, Sum(itemsSold) AS SumOf
FROM productr, productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC

The table productr2010 is the OLD data and productr is a brand new table for this year (2011). When i try running the query i get this:

Column 'id' in field list is ambiguous

I'm not sure what i need to do in order for it to grad data from both tables? I've also tried this:

SELECT productr.id, productr.itemName, productr.itemRUDate, Sum(productr.itemsSold) AS    SumOf
FROM productr, productr2010
WHERE productr.itemRUDate >= '2010/12/01' AND productr.itemRUDate <= '2011/01/22'
AND productr2010.itemRUDate >= '2010/12/01' AND productr2010.itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC

And i get only the data from the productr table and not that and productr2010 table.

I'm sure i am just overlooking something easy..

UPDATE

Got it using this:

SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
UNION
SELECT id, itemName, itemRUDate, Sum(itemsSold) AS    SumOf
FROM productr2010
WHERE itemRUDate >= '2010/12/01' AND itemRUDate <= '2011/01/22'
GROUP BY itemName
ORDER BY SumOf DESC

David


问:
Nativescript - Data does not refresh/update when a new value is added
My app is does not refresh/update labels or other king of input when a new value is added, this is a very weird issue because seams that the function to add the values is working properly but the view does not refresh with the new values, I only can see the new values just when I click on back button. You can see the bug on this video.
https://youtu.be/Dv3jRiusUqo

TNS version is 3.3.1

My code:
view.html

```<code><ActionBar class="action-bar" >
        <Label class="action-bar-title title" [text]="hostname"></Label>
        <NavigationButton text="{{ 'msg_btn_close' | translate }}" icon="res://ic_chevron_left_white_24dp" (tap)="goBack()"></NavigationButton>
</ActionBar>
<TabView #proxyTabView>
        <StackLayout *tabItem="{iconSource: 'res://ic_dashboard_black_24dp'}">
                <GridLayout columns="*,*,*,*" rows="auto, 180, 180">
                        <GridLayout colSpan="4" columns="*" row="0">
                                <RadDataForm tkExampleTitle tkToggleNavButton #proxyServerForm [source]="proxyData">
                                        <TKEntityProperty tkDataFormProperty name="hostname" displayName="{{ 'msg_ip_hostname' | translate }}" index="1">
                                                <TKPropertyEditor tkEntityPropertyEditor>
                                                        <TKPropertyEditorStyle tkPropertyEditorStyle labelHidden="false" labelTextSize="15"ios:labelFontName="Questrial" android:labelFontName="Questrial-Regular" labelPosition="Top"></TKPropertyEditorStyle>
                                                </TKPropertyEditor>
                                                <TKNonEmptyValidator tkEntityPropertyValidators errorMessage="{{ 'msg_error_ip_empty' | translate }}" ></TKNonEmptyValidator>
                                        </TKEntityProperty>
                                </RadDataForm>
                        </GridLayout>
                </GridLayout>
        </StackLayout>
        <StackLayout *tabItem="{iconSource: 'res://ic_http_black_24dp'}">
                <Label text="This is Label in Tab 2"></Label>
        </StackLayout>
        <StackLayout *tabItem="{iconSource: 'res://ic_memory_black_24dp'}">
                <Label text="This is Label in Tab 2"></Label>
        </StackLayout>
        <StackLayout *tabItem="{iconSource: 'res://ic_network_check_black_24dp'}">
                <Label text="This is Label in Tab 2"></Label>
        </StackLayout>
</TabView>
</code>```

view.ts

```<code>import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ObservableArray } from "tns-core-modules/data/observable-array";
import { TranslateService } from "ng2-translate";
import { Server } from "../../model/server.model";
import { DatabaseService } from "../../services/database.service";
import { RouterExtensions } from "nativescript-angular/router";
import { LoadingIndicator } from 'nativescript-loading-indicator';
import { ProxyData } from "../../model/proxy-data.model"
@Component({
    selector: 'proxy-server',
    templateUrl: './components/proxy-server/proxy-server.component.html',
    styleUrls: ['./components/proxy-server/proxy-server.component.css']
})

export class ProxyServerComponent implements OnInit {

    public server: Server;
    public worker;
    private _token: string;
    private hostname: string;
    public test: string;
    private indicator: LoadingIndicator;
    private _proxyData: ProxyData;

    constructor(private zone: NgZone, private route: ActivatedRoute, private databaseService: DatabaseService, private nav: RouterExtensions, private translate: TranslateService) {
        this.indicator = new LoadingIndicator();
        this.route.params.subscribe((params) => {
            this.server = {id:params["id"]};

        });
        this.worker = new Worker('../../workers/server-worker');
        this.databaseService.fetchByID(this.server).then((res: any) => {
            this._token=res[0].token
            this.worker.postMessage({server:res[0].hostname,port:res[0].port, username:res[0].username, pwd:res[0].pwd, token:res[0].token, action:"start"});
        })

    }

    ngOnInit() {
        this.hostname ="Loading data"
        this.worker.onmessage = (msg) =>{
            if (msg.data!=="error"){
                this._proxyData = new ProxyData(msg.data.os.hostname);
                this.hostname=msg.data.os.hostname
                console.log(msg.data.os.hostname);
            }
        }
        this.worker.onerror = (e) =>{
            console.log(e.message);
        }
    }
    get proxyData(): ProxyData {
        return this._proxyData;
    }
    private goBack() {
        this.indicator.show({ message: 'Please Wait...' });
        this.worker.postMessage({token:this._token, action:"stop"});
        setTimeout(() => {
            this.worker.terminate();
            this.indicator.hide();
            this.nav.navigate(['/home'], { clearHistory: true });
        }, 5000);
    }
}
</code>```

Best regards

答:
Issue fixed by using NgZone inside on ngOnInit.</p>

```<code>ngOnInit() {
        this.hostname ="Loading data"
        this.worker.onmessage = (msg) =>{
                        this.zone.run(() => {
            if (msg.data!=="error"){
                this._proxyData = new ProxyData(msg.data.os.hostname);
                this.hostname=msg.data.os.hostname
                console.log(msg.data.os.hostname);
            }
                        });
        }
        this.worker.onerror = (e) =>{
            console.log(e.message);
        }
    }
</code>```

Body:
My app is does not refresh/update labels or other king of input when a new value is added, this is a very weird issue because seams that the function to add the values is working properly but the view does not refresh with the new values, I only can see the new values just when I click on back button. You can see the bug on this video.
https://youtu.be/Dv3jRiusUqo

TNS version is 3.3.1

My code:
view.html

<ActionBar class="action-bar" >

        <NavigationButton text="{{ 'msg_btn_close' | translate }}" icon="res://ic_chevron_left_white_24dp" (tap)="goBack()"></NavigationButton>
</ActionBar>
<TabView #proxyTabView>
        <StackLayout *tabItem="{iconSource: 'res://ic_dashboard_black_24dp'}">
                <GridLayout columns="*,*,*,*" rows="auto, 180, 180">
                        <GridLayout colSpan="4" columns="*" row="0">
                                <RadDataForm tkExampleTitle tkToggleNavButton #proxyServerForm [source]="proxyData">
                                        <TKEntityProperty tkDataFormProperty name="hostname" displayName="{{ 'msg_ip_hostname' | translate }}" index="1">
                                                <TKPropertyEditor tkEntityPropertyEditor>
                                                        <TKPropertyEditorStyle tkPropertyEditorStyle labelHidden="false" labelTextSize="15"ios:labelFontName="Questrial" android:labelFontName="Questrial-Regular" labelPosition="Top"></TKPropertyEditorStyle>
                                                </TKPropertyEditor>
                                                <TKNonEmptyValidator tkEntityPropertyValidators errorMessage="{{ 'msg_error_ip_empty' | translate }}" ></TKNonEmptyValidator>
                                        </TKEntityProperty>
                                </RadDataForm>
                        </GridLayout>
                </GridLayout>
        </StackLayout>
        <StackLayout *tabItem="{iconSource: 'res://ic_http_black_24dp'}">

        </StackLayout>
        <StackLayout *tabItem="{iconSource: 'res://ic_memory_black_24dp'}">

        </StackLayout>
        <StackLayout *tabItem="{iconSource: 'res://ic_network_check_black_24dp'}">

        </StackLayout>
</TabView>

view.ts

import { Component, OnInit, OnDestroy, NgZone } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ObservableArray } from "tns-core-modules/data/observable-array";
import { TranslateService } from "ng2-translate";
import { Server } from "../../model/server.model";
import { DatabaseService } from "../../services/database.service";
import { RouterExtensions } from "nativescript-angular/router";
import { LoadingIndicator } from 'nativescript-loading-indicator';
import { ProxyData } from "../../model/proxy-data.model"
@Component({
    selector: 'proxy-server',
    templateUrl: './components/proxy-server/proxy-server.component.html',
    styleUrls: ['./components/proxy-server/proxy-server.component.css']
})

export class ProxyServerComponent implements OnInit {

    public server: Server;
    public worker;
    private _token: string;
    private hostname: string;
    public test: string;
    private indicator: LoadingIndicator;
    private _proxyData: ProxyData;

    constructor(private zone: NgZone, private route: ActivatedRoute, private databaseService: DatabaseService, private nav: RouterExtensions, private translate: TranslateService) {
        this.indicator = new LoadingIndicator();
        this.route.params.subscribe((params) => {
            this.server = {id:params["id"]};

        });
        this.worker = new Worker('../../workers/server-worker');
        this.databaseService.fetchByID(this.server).then((res: any) => {
            this._token=res[0].token
            this.worker.postMessage({server:res[0].hostname,port:res[0].port, username:res[0].username, pwd:res[0].pwd, token:res[0].token, action:"start"});
        })

    }

    ngOnInit() {
        this.hostname ="Loading data"
        this.worker.onmessage = (msg) =>{
            if (msg.data!=="error"){
                this._proxyData = new ProxyData(msg.data.os.hostname);
                this.hostname=msg.data.os.hostname
                console.log(msg.data.os.hostname);
            }
        }
        this.worker.onerror = (e) =>{
            console.log(e.message);
        }
    }
    get proxyData(): ProxyData {
        return this._proxyData;
    }
    private goBack() {
        this.indicator.show({ message: 'Please Wait...' });
        this.worker.postMessage({token:this._token, action:"stop"});
        setTimeout(() => {
            this.worker.terminate();
            this.indicator.hide();
            this.nav.navigate(['/home'], { clearHistory: true });
        }, 5000);
    }
}

Best regards

Body:
Issue fixed by using NgZone inside on ngOnInit.

ngOnInit() {
        this.hostname ="Loading data"
        this.worker.onmessage = (msg) =>{
                        this.zone.run(() => {
            if (msg.data!=="error"){
                this._proxyData = new ProxyData(msg.data.os.hostname);
                this.hostname=msg.data.os.hostname
                console.log(msg.data.os.hostname);
            }
                        });
        }
        this.worker.onerror = (e) =>{
            console.log(e.message);
        }
    }


问:
SQL print a space between concat statements
Concatenating two columns together, Just want them to be displaying together in column with a space between the two numbers. It keeps adding the two numbers together. One is a bigint other is a smallint.Will be displayed in an SSRS report eventually but right now just using SQL to query the data</p>

```<code>    (NBR +''+ ACCT_NBR) as acct,
</code>```

答:
I know this post is already answered and is correct. But would like to post the below answer because from SQL Server 2017 onwards, this is too easy and someoen might find this helpful in future.

```<code>CONCAT_WS(CHAR(10),Cast(NBR as varchar(20)) ,Cast(ACCT_NBR as varchar(20))) as acct
</code>```

CHAR(10) can be  for space in SQL SERVER. You can replace CHAR(10) with any separator you like to. For example,

```<code>CONCAT_WS(',',Cast(NBR as varchar(20)) ,Cast(ACCT_NBR as varchar(20))) as acct
</code>```

the above query will add the separator ',' between each strings being concatenated.

Body:
Concatenating two columns together, Just want them to be displaying together in column with a space between the two numbers. It keeps adding the two numbers together. One is a bigint other is a smallint.Will be displayed in an SSRS report eventually but right now just using SQL to query the data

    (NBR +''+ ACCT_NBR) as acct,

Body:
I know this post is already answered and is correct. But would like to post the below answer because from SQL Server 2017 onwards, this is too easy and someoen might find this helpful in future.

CONCAT_WS(CHAR(10),Cast(NBR as varchar(20)) ,Cast(ACCT_NBR as varchar(20))) as acct

CHAR(10) can be  for space in SQL SERVER. You can replace CHAR(10) with any separator you like to. For example,

CONCAT_WS(',',Cast(NBR as varchar(20)) ,Cast(ACCT_NBR as varchar(20))) as acct

the above query will add the separator ',' between each strings being concatenated.


问:
Segmentation fault when I try to run Anaconda Navigator
I have recently Installed Anaconda for Python 3.6 but it shows the error "Segmentation fault" whenever I try to run Anaconda-Navigator.
I've tried just writting in the terminal Anaconda-Navigator and also going to my Anaconda3 folder and try to execute it inside bin.

The only solution that works so far is accessing the previously bin folder as root. My problem is that I need to activate TensorFlow before I run anything in my console, but that is imposible as a root user.

I've already try to upgrade both, Anaconda and Navigator and reinstall them but nothing ocurrs

Anyone here has any idea of what is happening?

答:
I had the same problem.I solved it by adding /lib to mt LD_LIBRARY_PATH.

Note: On my system Anaconda installation path is /home/pushyamik/anaconda3.


问:
How to display self pointing table?
I've a table named category. Some categories are sub-categories of other categories.

```<code>--------------------------
ID | Name | Upper_Category
--------------------------
</code>```

Upper_Category references to another category's ID.

I need to display the table like so:

```<code>ID | Name    | Upper_Category
1  | ROOT #1 | NULL
5  | exam #2 | 1
7  | exam #3 | 1
4  | ROOT #2 | NULL
9  | exam #4 | 4
2  | exam #5 | 4
3  | exam #6 | 4
6  | ROOT #3 | NULL
...
</code>```

The categories whichs Upper_Category is NULL display first and then the sub-categories which reference to them.

I tried a lot by USING JOINS and UNION but didnt succeed.

答:
You need case in order by clause:

```<code>select *
from table1
order by case when Upper_Category is null then id else upper_category end, upper_category
</code>```

Result:

```<code>+----+---------+----------------+
| ID |  Name   | Upper_Category |
+----+---------+----------------+
|  1 | ROOT #1 | NULL           |
|  5 | exam #2 | 1              |
|  7 | exam #3 | 1              |
|  4 | ROOT #2 | NULL           |
|  9 | exam #4 | 4              |
|  2 | exam #5 | 4              |
|  3 | exam #6 | 4              |
|  6 | ROOT #3 | NULL           |
+----+---------+----------------+
</code>```

DEMO

Title: How to display self pointing table?

Body:
I've a table named category. Some categories are sub-categories of other categories.

--------------------------
ID | Name | Upper_Category
--------------------------

Upper_Category references to another category's ID.

I need to display the table like so:

ID | Name    | Upper_Category
1  | ROOT #1 | NULL
5  | exam #2 | 1
7  | exam #3 | 1
4  | ROOT #2 | NULL
9  | exam #4 | 4
2  | exam #5 | 4
3  | exam #6 | 4
6  | ROOT #3 | NULL
...

The categories whichs Upper_Category is NULL display first and then the sub-categories which reference to them.

I tried a lot by USING JOINS and UNION but didnt succeed.

Body:
You need case in order by clause:

select *
from table1
order by case when Upper_Category is null then id else upper_category end, upper_category

Result:

+----+---------+----------------+
| ID |  Name   | Upper_Category |
+----+---------+----------------+
|  1 | ROOT #1 | NULL           |
|  5 | exam #2 | 1              |
|  7 | exam #3 | 1              |
|  4 | ROOT #2 | NULL           |
|  9 | exam #4 | 4              |
|  2 | exam #5 | 4              |
|  3 | exam #6 | 4              |
|  6 | ROOT #3 | NULL           |
+----+---------+----------------+

DEMO


问:
SVG: How to use an unclosed path as a clip path
Is it possible to clip an SVG element to an unclosed path (e.g. a straight line)?

For example:

```<code><svg>
  <rect x="0" y="0" width="100" height="100" fill="blue" clip-path="url(#mask)"></rect>
  <defs>
    <clipPath id="mask">
        <path stroke-width="10" stroke="white" d="M 0 0 L 100 100"></path>
    </clipPath>
  </defs>
</svg>
</code>```

答:
You can use that as a clipPath but it will clip everything because stroke doesn't count for clipPaths.

The raw geometry of each child element exclusive of rendering properties such as ‘fill’, ‘stroke’, ‘stroke-width’ within a ‘clipPath’ conceptually defines a 1-bit mask

Body:
Is it possible to clip an SVG element to an unclosed path (e.g. a straight line)?

For example:

<svg>
  <rect x="0" y="0" width="100" height="100" fill="blue" clip-path="url(#mask)"></rect>
  <defs>
    <clipPath id="mask">
        <path stroke-width="10" stroke="white" d="M 0 0 L 100 100"></path>
    </clipPath>
  </defs>
</svg>


问:
Project Dependencies in WiX Installer MSI
Very new to WiX but having an issue I can't resolve.
I have a simple console application, I have a simple Wix Installer.
I have followed the basic guides to install my console application.
The software appears to have installed correctly but it is missing a library that I have included in my console application.

The error I am getting is:

```<code>Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'FluentCommandLineParser, Version=1.4.3.0, Culture=neutral, PublicKeyToken
=null' or one of its dependencies. The system cannot find the file specified.
</code>```

This 'FluentCommandLineParser' is simply a library I am using that I installed to the project using the Nuget Package Manager.

Do I have to reference each individual library that the console application is using? If so, how do I do this?

I attempted to resolve by adding the FluentCommandLineParser.dll from the project debug/bin folder as a reference in the WiX installer project but it spits that back on build.

答:
You need to add the FluentCommandLineParser.dll as a component in your installer if you want it included in the install.

Since you added it with nuget it is probably added as a reference with "Copy Local = True" so you can pretty easily add it to your install.

Just add a new component

```<code><Component Id="FluentCommandLineParser.dll" Guid="*">
    <File Id="FluentCommandLineParser.dll" KeyPath="yes" Source="$(var.ProjectNameHere.TargetDir)FluentCommandLineParser.dll" />
</Component>
</code>```

and that should add the dll to your installer.

Here is a link that explains and defines all the available preprocessor variables associated with a project reference.

Body:
Very new to WiX but having an issue I can't resolve.
I have a simple console application, I have a simple Wix Installer.
I have followed the basic guides to install my console application.
The software appears to have installed correctly but it is missing a library that I have included in my console application.

The error I am getting is:

Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'FluentCommandLineParser, Version=1.4.3.0, Culture=neutral, PublicKeyToken
=null' or one of its dependencies. The system cannot find the file specified.

This 'FluentCommandLineParser' is simply a library I am using that I installed to the project using the Nuget Package Manager.

Do I have to reference each individual library that the console application is using? If so, how do I do this?

I attempted to resolve by adding the FluentCommandLineParser.dll from the project debug/bin folder as a reference in the WiX installer project but it spits that back on build.

Body:
You need to add the FluentCommandLineParser.dll as a component in your installer if you want it included in the install.

Since you added it with nuget it is probably added as a reference with "Copy Local = True" so you can pretty easily add it to your install.

Just add a new component

<Component Id="FluentCommandLineParser.dll" Guid="*">
    <File Id="FluentCommandLineParser.dll" KeyPath="yes" Source="$(var.ProjectNameHere.TargetDir)FluentCommandLineParser.dll" />
</Component>

and that should add the dll to your installer.

Here is a link that explains and defines all the available preprocessor variables associated with a project reference.


问:
Read source file from and XML file
I have a process that is receiving files that come in pairs. One is a ctr file and the other is the data file. The ctr and data file will always have the same name except different extensions. E.g. dfghj.ctl and dfghj.dat

The problem I have is that I receive multiple of these pairs at the same time. The only way to tell which is which is to look into the ctl file. This tells me if the the .dat file related to it is either the report.jsonl file or the delta.jsonl file.

An example of a .ctl is:

```<code><DTSControl>
<Version>1.0</Version>
<AddressType>DTS</AddressType>
<MessageType>Data</MessageType>
<From_DTS>x26OT075</From_DTS>
<To_DTS>x26OT075</To_DTS>
<Subject>ECDS Submission</Subject>
<LocalId>TEST-delta.jsonl</LocalId>
<WorkflowId>SUS_CDS</WorkflowId>
<Encrypted>N</Encrypted>
<Compress>Y</Compress>
</DTSControl>
</code>```

The bit I need to get to is the LocalId which tells me what type of file the .dat is and therefore which table I need I need to load it to. Once I know which file is which, I then need to pass the associated .dat file name to a variable to populate the source connection.

The only thing I can think of is a script task to load a ctl file, isolate the LocalId and if it is like *-report.jsonl then strip the last three characters of the file and replace ctl with dat and pass that string to the variable but I've no idea how to get to LocalId as I don't work with c#.

Is anyone able to give a pointer as to how to get there? It may not always be the eighth line so I would prefer to tell it to go LocalID which won't change.

Thanks in advance

答:
So far both of these solutions helped you identify LocalID. Great.

But I think you are asking a bigger picture. How does your package look.

Foreach loop through files with your mask of *.ctl

Store the file name in a variable

Add a script task and use whatever method you want to find local ID and store in a variable

You need to have a data flow for each of the possible local ids.

Set precedence constraints to those data flows based on local id

Your target file will always be based on this formula and you should use an expression for your connections: Left([Variable from Step 2],len([Var from 2])-3)+"dat"

Title: Read source file from and XML file

Body:
I have a process that is receiving files that come in pairs. One is a ctr file and the other is the data file. The ctr and data file will always have the same name except different extensions. E.g. dfghj.ctl and dfghj.dat

The problem I have is that I receive multiple of these pairs at the same time. The only way to tell which is which is to look into the ctl file. This tells me if the the .dat file related to it is either the report.jsonl file or the delta.jsonl file.

An example of a .ctl is:

<DTSControl>
<Version>1.0</Version>
<AddressType>DTS</AddressType>
<MessageType>Data</MessageType>
<From_DTS>x26OT075</From_DTS>
<To_DTS>x26OT075</To_DTS>
<Subject>ECDS Submission</Subject>
<LocalId>TEST-delta.jsonl</LocalId>
<WorkflowId>SUS_CDS</WorkflowId>
<Encrypted>N</Encrypted>
<Compress>Y</Compress>
</DTSControl>

The bit I need to get to is the LocalId which tells me what type of file the .dat is and therefore which table I need I need to load it to. Once I know which file is which, I then need to pass the associated .dat file name to a variable to populate the source connection.

The only thing I can think of is a script task to load a ctl file, isolate the LocalId and if it is like *-report.jsonl then strip the last three characters of the file and replace ctl with dat and pass that string to the variable but I've no idea how to get to LocalId as I don't work with c#.

Is anyone able to give a pointer as to how to get there? It may not always be the eighth line so I would prefer to tell it to go LocalID which won't change.

Thanks in advance


问:
How do I persist a ES6 Map in localstorage (or elsewhere)?
```<code>var a = new Map([[ 'a', 1 ]]);
a.get('a') // 1

var forStorageSomewhere = JSON.stringify(a);
// Store, in my case, in localStorage.

// Later:
var a = JSON.parse(forStorageSomewhere);
a.get('a') // TypeError: undefined is not a function
</code>```

Unfortunatly JSON.stringify(a); simply returns '{}', which means a becomes an empty object when restored.

I found es6-mapify that allows up/down-casting between a Map and a plain object, so that might be one solution, but I was hoping I would need to resort to an external dependency simply to persist my map.

答:
One thing that is being left outis that Map is an ORDERED structure - i.e. when iterating the first item entered would be the first listed.

This is NOT like a Javascript Object. I required this type of structure (so i used Map) and then to find out that JSON.stringify doesn't work is painful (but understandable).

I ended up making a 'value_to_json' function, which means parsing EVERYTHING -
using JSON.stringify only for the most basic 'types'.

Unfortunately subclassing MAP with a .toJSON() doesn't work as it excepts a value not a JSON_string. Also it is considered legacy.

My use case would be exceptional though.

related:

https://github.com/DavidBruant/Map-Set.prototype.toJSON/issues/16

JSON left out Infinity and NaN; JSON status in ECMAScript?

How to stringify objects containing ES5 Sets and Maps?

JSON stringify a Set

function value_to_json(value) {
  if (value === null) {
    return 'null';
  }
  if (value === undefined) {
    return 'null';
  }
  //DEAL WITH +/- INF at your leisure - null instead..

  const type = typeof value;
  //handle as much as possible taht have no side effects. function could
  //return some MAP / SET -> TODO, but not likely
  if (['string', 'boolean', 'number', 'function'].includes(type)) {
    return JSON.stringify(value)
  } else if (Object.prototype.toString.call(value) === '[object Object]') {
    let parts = [];
    for (let key in value) {
      if (Object.prototype.hasOwnProperty.call(value, key)) {
        parts.push(JSON.stringify(key) + ': ' + value_to_json(value[key]));
      }
    }
    return '{' + parts.join(',') + '}';
  }
  else if (value instanceof Map) {
    let parts_in_order = [];
    value.forEach((entry, key) => {
      if (typeof key === 'string') {
        parts_in_order.push(JSON.stringify(key) + ':' + value_to_json(entry));
      } else {
        console.log('Non String KEYS in MAP not directly supported');
      }
      //FOR OTHER KEY TYPES ADD CUSTOM... 'Key' encoding...
    });
    return '{' + parts_in_order.join(',') + '}';
  } else if (typeof value[Symbol.iterator] !== "undefined") {
    //Other iterables like SET (also in ORDER)
    let parts = [];
    for (let entry of value) {
      parts.push(value_to_json(entry))
    }
    return '[' + parts.join(',') + ']';
  } else {
    return JSON.stringify(value)
  }
}

let m = new Map();
m.set('first', 'first_value');
m.set('second', 'second_value');
let m2 = new Map();
m2.set('nested', 'nested_value');
m.set('sub_map', m2);
let map_in_array = new Map();
map_in_array.set('key', 'value');
let set1 = new Set(["1", 2, 3.0, 4]);

m2.set('array_here', [map_in_array, "Hello", true, 0.1, null, undefined, Number.POSITIVE_INFINITY, {
  "a": 4
}]);
m2.set('a set: ', set1);
const test = {
  "hello": "ok",
  "map": m
};

console.log(value_to_json(test));```

Body:
var a = new Map([[ 'a', 1 ]]);
a.get('a') // 1

var forStorageSomewhere = JSON.stringify(a);
// Store, in my case, in localStorage.

// Later:
var a = JSON.parse(forStorageSomewhere);
a.get('a') // TypeError: undefined is not a function

Unfortunatly JSON.stringify(a); simply returns '{}', which means a becomes an empty object when restored.

I found es6-mapify that allows up/down-casting between a Map and a plain object, so that might be one solution, but I was hoping I would need to resort to an external dependency simply to persist my map.


问:
How to get a specific value out an an array of objects in PHP
I have the follow array and and am trying to get the meta_value for the the object that has the meta_key of license_number.  How can I return that value?</p>

```<code>items: [
{
    account_id: "7890",
    t: 1990007,
    meta_value: "27",
    id: "123",
    create_date: 1507174015113,
    update_date: 1512628710384,
    meta_key: "content_items",
},
{
    account_id: "7890",
    t: 1990007,
    meta_value: "123456",
    id: "123",
    create_date: 1498492590855,
    update_date: 1498492590855,
    meta_key: "location_id",
},
{
    account_id: "7890",
    t: 1990007,
    meta_value: "123456789",
    id: "123",
    create_date: 1498492590855,
    update_date: 1498492590855,
    meta_key: "license_number",
}
]
</code>```

答:
Use array_filter() and a callable to fit your needs (here an anonymous fonction) :

```<code>$searchedValue = 'license_number';
$o = array_filter( $items,
    function ($e) use (&$searchedValue) {
        return $e->meta_key == $searchedValue;
    }
);
</code>```

Note the return is an array of objects containing all values that fit the condition. This will give you the first result.

```<code>reset($o);
</code>```

Body:
I have the follow array and and am trying to get the meta_value for the the object that has the meta_key of license_number.  How can I return that value?

items: [
{
    account_id: "7890",
    t: 1990007,
    meta_value: "27",
    id: "123",
    create_date: 1507174015113,
    update_date: 1512628710384,
    meta_key: "content_items",
},
{
    account_id: "7890",
    t: 1990007,
    meta_value: "123456",
    id: "123",
    create_date: 1498492590855,
    update_date: 1498492590855,
    meta_key: "location_id",
},
{
    account_id: "7890",
    t: 1990007,
    meta_value: "123456789",
    id: "123",
    create_date: 1498492590855,
    update_date: 1498492590855,
    meta_key: "license_number",
}
]

Body:
Use array_filter() and a callable to fit your needs (here an anonymous fonction) :

$searchedValue = 'license_number';
$o = array_filter( $items,
    function ($e) use (&$searchedValue) {
        return $e->meta_key == $searchedValue;
    }
);

Note the return is an array of objects containing all values that fit the condition. This will give you the first result.

reset($o);


问:
Mass-reversing smartsheet mistake
Someone managed to copy and paste a huge amount of data into the wrong place in smartsheet. Of course it wasn't reversed at the time, and now I have the lovely task of reversing out all of the entries. Manually. One cell at a time. </p>

<p>There has to be a better way. </p>

答:
Take a look at the Get Cell History endpoint on the Smartsheet API. When you call that you'll get a response back that looks like this:

```<code>{
  "pageNumber": 1,
  "pageSize": 100,
  "totalPages": 1,
  "totalCount": 3,
  "data": [
      {
        "columnId":4567890123456789,
        "displayValue": "Revision 3",
        "columnType": "TEXT_NUMBER",
        "value": "Revision 3",
        "modifiedAt": "2013-06-24T00:10:18Z",
        "modifiedBy" : {
            "name" : "Jane Smart",
            "email" : "jane.smart@smartsheet.com"
        }
    },
    {
        "columnId":4567890123456789,
        "displayValue": "Revision 2",
        "columnType": "TEXT_NUMBER",
        "value": "Revision 2",
        "modifiedAt": "2013-06-23T00:10:18Z",
        "modifiedBy" : {
            "name" : "Joe Smart",
            "email" : "joe.smart@smartsheet.com"
        }
    }
  ]
}
</code>```

You should be able to write a script that analyzes the revisions and lets you revert the value in a more automated fashion.

Title: Mass-reversing smartsheet mistake

Body:
Someone managed to copy and paste a huge amount of data into the wrong place in smartsheet. Of course it wasn't reversed at the time, and now I have the lovely task of reversing out all of the entries. Manually. One cell at a time.

There has to be a better way.

Body:
Take a look at the Get Cell History endpoint on the Smartsheet API. When you call that you'll get a response back that looks like this:

{
  "pageNumber": 1,
  "pageSize": 100,
  "totalPages": 1,
  "totalCount": 3,
  "data": [
      {
        "columnId":4567890123456789,
        "displayValue": "Revision 3",
        "columnType": "TEXT_NUMBER",
        "value": "Revision 3",
        "modifiedAt": "2013-06-24T00:10:18Z",
        "modifiedBy" : {
            "name" : "Jane Smart",
            "email" : "jane.smart@smartsheet.com"
        }
    },
    {
        "columnId":4567890123456789,
        "displayValue": "Revision 2",
        "columnType": "TEXT_NUMBER",
        "value": "Revision 2",
        "modifiedAt": "2013-06-23T00:10:18Z",
        "modifiedBy" : {
            "name" : "Joe Smart",
            "email" : "joe.smart@smartsheet.com"
        }
    }
  ]
}

You should be able to write a script that analyzes the revisions and lets you revert the value in a more automated fashion.


问:
Get implemented method when intercepting from an interface
I am intercepting the methods on an interface because I want to be sure my pre-invoke code is run for all public methods of any given implementation. I know I could do method interception, but that makes configuration harder and risks new methods in the future not getting configured.

At runtime I am able to get the implemented class from the IInvocation argument by calling GetType on invocation.Request.Target. What I can't find is how to get which method is being called.

Once I have the class type, I could probably query the method by name, but then I have to get in to querying on parameters as well in case there's overloads and I'd rather avoid that if possible.

Ultimately I am trying to pull the attributes off the calling method. So if there's a shortcut, that would work too.

EDIT: I know that I can put my attributes on the interface members (I am doing that now as a work around), but that cannot be the final solution in my case.

EDIT 2: Requested code sample:

```<code>public class PublicBusinessInterceptor : SimpleInterceptor
{
    protected override void BeforeInvoke(IInvocation invocation)
    {
        var interfaceMemberType = invocation.Request.Target.GetType();
    }
}
</code>```

In the code sample above, interfaceMemberType is, as the variable name implies, the type of the interface member. I need the type of the implemented member that is being called in this context. The implemented member type has the attributes that I need. The interface member type does not.

答:
Not sure I understand your question, but, as far as I understand, this may be a starting basis :</p>

```<code> public class MyInterceptor : IInterceptor
 {
     public void Intercept(IInvocation invocation)
     {
         // The intercepted method
         var method = invocation.Request.Method;

         // the method of the concrete type which is intercepted
         var actualMethod = invocation.Request.Target.GetType()
             .GetMethod(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray());

         // the desired attribute
         var myAttribute = actualMethod.GetCustomAttributes<MyAttribute>().FirstOrDefault();

         if (myAttribute == null)
        {
            invocation.Proceed();
        }
        else
        {
          // Do stuff
        }
     }
</code>```

Body:
I am intercepting the methods on an interface because I want to be sure my pre-invoke code is run for all public methods of any given implementation. I know I could do method interception, but that makes configuration harder and risks new methods in the future not getting configured.

At runtime I am able to get the implemented class from the IInvocation argument by calling GetType on invocation.Request.Target. What I can't find is how to get which method is being called.

Once I have the class type, I could probably query the method by name, but then I have to get in to querying on parameters as well in case there's overloads and I'd rather avoid that if possible.

Ultimately I am trying to pull the attributes off the calling method. So if there's a shortcut, that would work too.

EDIT: I know that I can put my attributes on the interface members (I am doing that now as a work around), but that cannot be the final solution in my case.

EDIT 2: Requested code sample:

public class PublicBusinessInterceptor : SimpleInterceptor
{
    protected override void BeforeInvoke(IInvocation invocation)
    {
        var interfaceMemberType = invocation.Request.Target.GetType();
    }
}

In the code sample above, interfaceMemberType is, as the variable name implies, the type of the interface member. I need the type of the implemented member that is being called in this context. The implemented member type has the attributes that I need. The interface member type does not.

Body:
Not sure I understand your question, but, as far as I understand, this may be a starting basis :

 public class MyInterceptor : IInterceptor
 {
     public void Intercept(IInvocation invocation)
     {
         // The intercepted method
         var method = invocation.Request.Method;

         // the method of the concrete type which is intercepted
         var actualMethod = invocation.Request.Target.GetType()
             .GetMethod(method.Name, method.GetParameters().Select(p => p.ParameterType).ToArray());

         // the desired attribute
         var myAttribute = actualMethod.GetCustomAttributes<MyAttribute>().FirstOrDefault();

         if (myAttribute == null)
        {
            invocation.Proceed();
        }
        else
        {
          // Do stuff
        }
     }


问:
Make a CD run once
We're doing an "Amazing Race" kind of event, and thought it would be cool to have CDs that could only play once... like a "this message will self destruct in 5 seconds..."

Any thoughts on how to do this?  I was thinking it could be a compiled HTML website that would write a cookie and only play once.  I don't want to write to the registry (don't want to depend on windows, don't want to install anything, etc).

I also don't care if it's hackable... This is a one-time fun event, and I don't really care too much if people could remove the cookie or something.

Any other ideas?

答: Make a Java Swing application. That will not require Internet and it runs on Mac, Windows, and Linux. You can write to the file system for the lock. System.getProperty("user.home") gives you the home equivalent for the platform. You might have to include a jre in your CD.</p>

OwnerDisplayName: Nathan DeWitt

Title: Make a CD run once


问:
dojo.xd.js not recognizing dojox.data.CsvStore
When I use an import such as

```<code><script type="text/javascript" src="http://o.aolcdn.com/dojo/1.2.3/dojo/dojo.xd.js"
      djConfig="parseOnLoad:true, isDebug: true"></script>
</code>```

I get the error

```<code>dojox.data.CsvStore is not a constructor
</code>```

for lines such as

```<code>var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"});
</code>```

but the error vanishes if I use an import from a local installation of dojo such as

```<code><script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js"
     djConfig="parseOnLoad:true, isDebug: true"></script>
</code>```

I would really want to be able to use a CDN hosted dojo installation. Is there a known problem between the DojoX libraries and dojo.xd.js?

Thanks in advance,

Animesh

P.S. The dojo.require("dojox.data.CsvStore"); declarations are in place.

P.P.S The full "working code" is below. Replacing the CSS and JS references with those from the CDN breaks it.

```<code><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <style type="text/css">
        @import "dojo-release-1.2.3/dijit/themes/tundra/tundra.css";
        @import "dojo-release-1.2.3/dojo/resources/dojo.css"
    </style>
    <script type="text/javascript" src="dojo-release-1.2.3/dojo/dojo.js"
         djConfig="parseOnLoad:true, isDebug: true"></script>
    <script>
        dojo.require("dojox.data.CsvStore");
        dojo.require("dijit.Tree");
        dojo.require("dojo.parser");
    </script>
    <script type="text/javascript">
        var stateStore = new dojox.data.CsvStore({url: "states.csv", label: "name"});
    </script>

</head>
<body class="tundra">
    <div dojoType="dijit.Tree" store="stateStore" labelAttr="name" label="States">
    </div>
</body>
</html>
</code>```

答:
Are you running that code inside dojo.addOnLoad()?  As in:

```<code>dojo.addOnLoad(function(){
   dojo.require("dojox.data.CsvStore");
   var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"});
});
</code>```

Also, are you using FireFox 3?  If so, try putting your  block at the very end of the  section, just before the closing  tag.  (I know that is not standard practice, but it's related to Firefox's bug 444322, which should be fixed in release 3.0.6.)

Other than that, your code seems to be fine, and such strange discrepancies usually boil down to issues of timing with the loading of dojo modules.

OwnerDisplayName: Animesh

Body:
When I use an import such as

I get the error

dojox.data.CsvStore is not a constructor

for lines such as

var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"});

but the error vanishes if I use an import from a local installation of dojo such as

I would really want to be able to use a CDN hosted dojo installation. Is there a known problem between the DojoX libraries and dojo.xd.js?

Thanks in advance,

Animesh

P.S. The dojo.require("dojox.data.CsvStore"); declarations are in place.

P.P.S The full "working code" is below. Replacing the CSS and JS references with those from the CDN breaks it.

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

LastEditorDisplayName: Animesh

Body:
Are you running that code inside dojo.addOnLoad()?  As in:

dojo.addOnLoad(function(){
   dojo.require("dojox.data.CsvStore");
   var stateStore = new dojox.data.CsvStore({url: "dojo-passcsv.php", label: "name"});
});

Also, are you using FireFox 3?  If so, try putting your <script></script> block at the very end of the <body> section, just before the closing </body> tag.  (I know that is not standard practice, but it's related to Firefox's bug 444322, which should be fixed in release 3.0.6.)

Other than that, your code seems to be fine, and such strange discrepancies usually boil down to issues of timing with the loading of dojo modules.

OwnerDisplayName: pierdeux


问:
Return request HttpModules as quickly as possible
In a web site I capture the http POST request with a HttpModule as in this answer.

After reading the body of the POST in the context's BeginRequest event I would like to return as quickly as possible an "OK" response to the client.

What would be the best way to prevent further processing in IIS (7.5 integrated mode)?

答: Call HttpResponse.End().  It will flush any pending content (your OK response) and then end the request.


问:
Configure module logger to flask app logger
My flask application uses a module which gets a logger like this:

```<code>import logging
logger = logging.getLogger("XYZ")
...
logger.debug("stuff")
</code>```

Without having to modify anything in the module, can I configure flask such that the module will get flask's app.logger when it makes the getLogger("XYZ") call?

答:
This solution worked to me:

```<code>import logging

logger = logging.getLogger('werkzeug')
logger.debug('stuff')
</code>```

The default Flask configuration seems to use the logger name werkzeug. Adding or changing handlers for this logger changes the way Flask logs.

PS.: Python 3.5, Flask 0.12.2

Body:
My flask application uses a module which gets a logger like this:

import logging
logger = logging.getLogger("XYZ")
...
logger.debug("stuff")

Without having to modify anything in the module, can I configure flask such that the module will get flask's app.logger when it makes the getLogger("XYZ") call?

Body:
This solution worked to me:

import logging

logger = logging.getLogger('werkzeug')
logger.debug('stuff')

The default Flask configuration seems to use the logger name werkzeug. Adding or changing handlers for this logger changes the way Flask logs.

PS.: Python 3.5, Flask 0.12.2