问:
Gulp - strip out test code then webpack modules
I'm new to gulp and am trying to understand how to set up a gulp recipe to strip out test test code with 'gulp-strip-code' and 'webpack-stream'.

For testing purposes I'm not doing any minification on the file.

```<code>gulp.task('strip-test-code', function(){
  return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
    .pipe(stripCode({
      start_comment: "start-test-block",
      end_comment: "end-test-block"
    }));
});

gulp.task('pack-strip',['strip-test-code'],function(){
  return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
    .pipe(webpack(require('./webpack.config.devel.js')))
    .pipe(gulp.dest('dist/'));
});
</code>```

When I run gulp pack-strip I still see my test bock tags in the bundle.

It seems to be running the strip-test-code.

```<code>[10:26:57] Using gulpfile ~/project/gulpfile.js
[10:26:57] Starting 'strip-test-code'...
[10:26:57] Finished 'strip-test-code' after 71 ms
[10:26:57] Starting 'pack-strip'...
[10:26:58] Version: webpack 1.15.0
              Asset    Size  Chunks             Chunk Names
project.bundle.js  141 kB       0  [emitted]  project
[10:26:58] Finished 'pack-strip' after 396 ms
</code>```

However after execution i grep for the test block

```<code>grep -r start-test-block *
dist/project.bundle.js:   /*start-test-block*/
</code>```

--- EDIT ---

My webpack config file looks like

```<code> 1 const path=require('path');
 2 module.exports={
 3   context:path.resolve(__dirname,'src'),
 4   entry:{
 5     project:['./project.js']
 6   },
 7   output:{
 8     path:path.resolve(__dirname,'dist'),
 9     filename:'[name].bundle.js'
10   },
11   devtool:"#inline-source-map"
12 };
</code>```

答:
The task pack-strip didn't use the stream return by task strip-test-code, you could combine them into one task:

```<code>gulp.task('task', function(){
    return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
       .pipe(stripCode({
           start_comment: "start-test-block",
           end_comment: "end-test-block"
       }))
       .pipe(webpack(require('./webpack.config.devel.js')))
       .pipe(gulp.dest('dist/'));
});
</code>```

Or you could save the stripped files firstly and read them later:

```<code>gulp.task('strip-test-code', function(){
     return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
         .pipe(stripCode({
             start_comment: "start-test-block",
             end_comment: "end-test-block"
          }));
          .pipe(gulp.dest('dist'));
});

gulp.task('pack-strip',['strip-test-code'],function(){
    return gulp.src(['dist/*.js','dist/gui/*.js'],{base:'dist'})
        .pipe(webpack(require('./webpack.config.devel.js')))
        .pipe(gulp.dest('dist/'));
});
</code>```

Body:
I'm new to gulp and am trying to understand how to set up a gulp recipe to strip out test test code with 'gulp-strip-code' and 'webpack-stream'.

For testing purposes I'm not doing any minification on the file.

gulp.task('strip-test-code', function(){
  return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
    .pipe(stripCode({
      start_comment: "start-test-block",
      end_comment: "end-test-block"
    }));
});

gulp.task('pack-strip',['strip-test-code'],function(){
  return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
    .pipe(webpack(require('./webpack.config.devel.js')))
    .pipe(gulp.dest('dist/'));
});

When I run gulp pack-strip I still see my test bock tags in the bundle.

It seems to be running the strip-test-code.

[10:26:57] Using gulpfile ~/project/gulpfile.js
[10:26:57] Starting 'strip-test-code'...
[10:26:57] Finished 'strip-test-code' after 71 ms
[10:26:57] Starting 'pack-strip'...
[10:26:58] Version: webpack 1.15.0
              Asset    Size  Chunks             Chunk Names
project.bundle.js  141 kB       0  [emitted]  project
[10:26:58] Finished 'pack-strip' after 396 ms

However after execution i grep for the test block

grep -r start-test-block *
dist/project.bundle.js:   /*start-test-block*/

--- EDIT ---

My webpack config file looks like

 1 const path=require('path');
 2 module.exports={
 3   context:path.resolve(__dirname,'src'),
 4   entry:{
 5     project:['./project.js']
 6   },
 7   output:{
 8     path:path.resolve(__dirname,'dist'),
 9     filename:'[name].bundle.js'
10   },
11   devtool:"#inline-source-map"
12 };

Body:
The task pack-strip didn't use the stream return by task strip-test-code, you could combine them into one task:

gulp.task('task', function(){
    return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
       .pipe(stripCode({
           start_comment: "start-test-block",
           end_comment: "end-test-block"
       }))
       .pipe(webpack(require('./webpack.config.devel.js')))
       .pipe(gulp.dest('dist/'));
});

Or you could save the stripped files firstly and read them later:

gulp.task('strip-test-code', function(){
     return gulp.src(['src/*.js','src/gui/*.js'],{base:'src'})
         .pipe(stripCode({
             start_comment: "start-test-block",
             end_comment: "end-test-block"
          }));
          .pipe(gulp.dest('dist'));
});

gulp.task('pack-strip',['strip-test-code'],function(){
    return gulp.src(['dist/*.js','dist/gui/*.js'],{base:'dist'})
        .pipe(webpack(require('./webpack.config.devel.js')))
        .pipe(gulp.dest('dist/'));
});


来源: stackexchange

问:
How do I remove illegal characters from an NSString?
I am parsing a tab seperated list using a NSScanner based upon each line and the tabs. However for some reason the last field in the array (parsed from each row) contains a \r character.

How can I strip this from the NSString that represents the line (or the field)

答: Try using the  +[NSCharacterSet newlineCharacterSet]  method with NSScanner in your various scanning method calls.</p>

OwnerDisplayName: tigermain

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: s-bug


问:
Get context attribute value from console
I'm reading with dev. tools console with this code $('#basis > td')[1] this code line: € 11,85

With $('#basis > td')[1].textContent i read the content of 	, also € 11,85.

How can i read the value of context? - i want to get 11.84689, but i can't find anywhere, how to fetch context attribute value...

答:
JQuery has a function to get the attributes of elements</p>

```<code>console.log( $('#basis td:first-child').attr('context') );
</code>```

ContentLicense: CC BY-SA 3.0

Body:
JQuery has a function to get the attributes of elements

console.log( $('#basis td:first-child').attr('context') );


问:
ReSharper ignore certain folder(s) on TODO explorer
I use SignalR in my solution, their Nuget package brings in java scripts. It's OK, but problem is - there is TODO's in there which now shows up under my TODO list.

So, I'd like to ignore specific folder(s) or file(s) when ReSharper scan's for TODO's

I tried to exclude folder from "Code Inspections" but that doesn't seem to apply to TODO's.

Possible? (latest resharper, vs2015)

答:
ReSharper -> Options

Under Code Inspection/Generated Code add folder/files to be excluded and TODO's from there won't be on a list.


问:
Where and how to create symlink from public/storage to storage/app/public in laravel 5.2 on homestead on window
how to create symlink from public/storage to storage/app/public in homestead on window.
and how do i access my files from browser, so if i visit that image url via browser then it will show that particular image.

actually i'm building an api which accessible from any domain , so i have to return the url of that particular image which is uploaded. so it will be shown of front end.
i'm also saving path to database which is - storage/app/public/image.png . what should i do now..

I'm new to file system so may be i need steps by step instruction.

i will be so thankful for the help

答:
I tried this and it works. Running homestead on VirtualBox on Windows 10:

Open cmd as administrator

Click Start->Run

Type 'cmd', and press ctrl-shift-enter

Select 'yes' from the pop-up window

Type the following command:mklink /D c:\<project_directory>\public\storage "/home/vagrant/<project_directory>/storage/app"

Then the storage/app will be accessible from public/storage in Homestead VM. Note that this is assuming C:\ is shared as /home/vagrant in Homestead VM.


问:
Optimize the number of ng-repeat |angularJS
I want to separate everything in my code according to predefined  levels given , from level 1 to level 6 , now my JSON reads

```<code>$scope.myJson=[{
  id: 1,
  level: 1,
  name: "any name"
},
{
  id: 2,
  level: 2,
  name: "any name"
},
{
  id: 3,
  level: 2,
  name: "any name"
}....]
</code>```

now in my HTML I have written something like

```<code><div>level 1
  <div ng-repeat="prod in myJson"  ng-if="prod.level==1">{{prod.name}}
  </div>
</div>
<div>level 2
  <div ng-repeat="prod in myJson"  ng-if="prod.level==2">{{prod.name}}
  </div>
</div>
</code>```

and so on , I want to use only one ng-repeat to filter all the results in HTML on basis of the levels , as the results number in thousands the app is taking too much of time to respond

答:
To make it more generic, groupBy will solve this for you.

Demo:

angular.module('app', ['angular.filter'])
  .controller('myCtrl', function($scope) {
    $scope.myJson = [{
      id: 1,
      level: 1,
      name: "any name level1"
    }, {
      id: 2,
      level: 2,
      name: "any name level2"
    }, {
      id: 3,
      level: 2,
      name: "any name level2"
    }, {
      id: 4,
      level: 2,
      name: "any name level2"
    }, {
      id: 5,
      level: 1,
      name: "any name level1"
    }, {
      id: 6,
      level: 3,
      name: "any name level3"
    }]
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
</head>

<body>
  <div ng-controller="myCtrl">

    <ul ng-repeat="(key, value) in myJson | groupBy: 'level'">
      Level- {{ key }}
      <li ng-repeat="item in value">
        {{ item.name }}
      </li>
    </ul>
  </div>
</body>

</html></code>```

Body:
I want to separate everything in my code according to predefined  levels given , from level 1 to level 6 , now my JSON reads

$scope.myJson=[{
  id: 1,
  level: 1,
  name: "any name"
},
{
  id: 2,
  level: 2,
  name: "any name"
},
{
  id: 3,
  level: 2,
  name: "any name"
}....]

now in my HTML I have written something like

level 1

{{prod.name}}

level 2

{{prod.name}}

and so on , I want to use only one ng-repeat to filter all the results in HTML on basis of the levels , as the results number in thousands the app is taking too much of time to respond

Body:
To make it more generic, groupBy will solve this for you.

Demo:

angular.module('app', ['angular.filter'])
  .controller('myCtrl', function($scope) {
    $scope.myJson = [{
      id: 1,
      level: 1,
      name: "any name level1"
    }, {
      id: 2,
      level: 2,
      name: "any name level2"
    }, {
      id: 3,
      level: 2,
      name: "any name level2"
    }, {
      id: 4,
      level: 2,
      name: "any name level2"
    }, {
      id: 5,
      level: 1,
      name: "any name level1"
    }, {
      id: 6,
      level: 3,
      name: "any name level3"
    }]
  });

<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/angular-filter/0.4.7/angular-filter.js"></script>
</head>

<body>
  <div ng-controller="myCtrl">

    <ul ng-repeat="(key, value) in myJson | groupBy: 'level'">
      Level- {{ key }}
      <li ng-repeat="item in value">
        {{ item.name }}
      </li>
    </ul>
  </div>
</body>

</html>


问:
nginx 1.5+ file upload -- best practices
I'm looking to upload files through my nginx server. I'm currently running nginx-1.4.6 and am willing up move to the latest stable nginx-1.5* as necessary.

The community favorite is/was Valery Kholodkov's nginx-upload-module, found here. Regrettably Valery is no longer maintaining this module, details here. As of nginx-1.3.9 the module works partially or not at all.

I've compiled the nginx-upload-module into nginx-1.4.6 and am getting a bug (Client cxn closed) that seems to be fixed in the nginx-1.5.3 changeset. However I've applied the patch and had no luck.

Anatoly's slightly dated post, here, offers multiple solutions, includes four solutions

nginx-upload-module

nginx-big-upload

lua-resty-upload

clientbodyinfileonly

As I dive into the second and fourth solutions (I prefer not to make lua a dependency, but I might) I figured that it's appropriate to ask this community:

What are the current best practices for file uploading with nginx-1.5+?

Let me add that I'm uploading files from a python POST command and trying to test with curl. PHP is not on my tech stack.

答:
I realize this is a very old question, but it's on the first page of google search for "nginx upload module" and it's the first Stack Overflow result, so in case this helps anyone else that comes across this question:

I am using the nginx-upload-module on nginx 1.10.3. As the original question mentions, Valery Kholodkov is no longer maintaining the module. However, there are several different forks and other people have modified it to work with newer nginx versions.

This pull request is what I used in order to compile nginx with the upload module.

https://github.com/vkholodkov/nginx-upload-module/pull/88

The upload module, IMO, is still the best solution out there if you're using nginx and php-fpm. This module allows uploads to be handled completely by nginx until they are complete, and then the job of processing the upload is passed onto PHP. So php-fpm processes won't create a bottleneck when your users are uploading lots of files.


问:
Run DELETE cleanup query after a Solr dataimport
I'm working on a Solr dataimport from an Oracle database.  The database system has a set of tables dedicated to storing references to changes in other tables.
 For example, I might have a table named PERSON, and when records are added to this table, their IDs are added to the PERSON_CHANGED table.  I'd like to use this PERSON_CHANGED table when defining my deltaQuery so that Solr only indexes the changed records in subsequent indexes.  As part of this process, I need to remove records that I've read from the PERSON_CHANGED table after Solr finishes its import (either delta or full), so that I don't process them again later.

What's the best way to run this kind of "cleanup" SQL query after a dataimport?

I've tried combining both of the queries like this (simplified for brevity):

```<code><dataConfig>
    <dataSource ... >
    <document>
        <entity name="person"
                query="
                    SELECT ID, FIRST_NAME, LAST_NAME
                    FROM PERSON
                    WHERE '${dataimporter.request.clean}' != 'false'
                        OR PERSON_ID IN (
                            SELECT ID FROM CHANGED_PERSON
                        );

                    DELETE * (
                        SELECT * FROM CHANGED_PERSON
                    );
        " />
    </document>
</dataConfig>
</code>```

But this results in a SQL command not properly ended error.  Does Solr provide a way to do this kind of cleanup?

答:
Once you're using delta import in SOLR, solr won't process twice your record, since you will keep track of this records every time you will run

Ref doc:

When delta-import command is executed, it reads the start time stored
  in conf/dataimport.properties.

link: https://wiki.apache.org/solr/DataImportHandler#Delta-Import_Example

As part of your question, I can imagine that you're trying to perform full import every time that you run the deltaimport (full import runs cleanup in solr indexes ... etc). This is not the proper way to do deltaimport.

What I would recommand you is :
1) perform delta import (and not full import)
2) once every X days, X month, if your need to, perform a clean import
Better to do it in another core, so that your service continues running and you will only replace the cores.

Body:
I'm working on a Solr dataimport from an Oracle database.  The database system has a set of tables dedicated to storing references to changes in other tables.
 For example, I might have a table named PERSON, and when records are added to this table, their IDs are added to the PERSON_CHANGED table.  I'd like to use this PERSON_CHANGED table when defining my deltaQuery so that Solr only indexes the changed records in subsequent indexes.  As part of this process, I need to remove records that I've read from the PERSON_CHANGED table after Solr finishes its import (either delta or full), so that I don't process them again later.

What's the best way to run this kind of "cleanup" SQL query after a dataimport?

I've tried combining both of the queries like this (simplified for brevity):

<dataConfig>
    <dataSource ... >
    <document>
        <entity name="person"
                query="
                    SELECT ID, FIRST_NAME, LAST_NAME
                    FROM PERSON
                    WHERE '${dataimporter.request.clean}' != 'false'
                        OR PERSON_ID IN (
                            SELECT ID FROM CHANGED_PERSON
                        );

                    DELETE * (
                        SELECT * FROM CHANGED_PERSON
                    );
        " />
    </document>
</dataConfig>

But this results in a SQL command not properly ended error.  Does Solr provide a way to do this kind of cleanup?


问:
Accessing nested values in Javascript Object
In an app using react/redux, I made a GET request to Google's Civic Api and received the following object which I added to my state:

{
   "kind":"civicinfo#representativeInfoResponse",
   "normalizedInput":{
      "line1":"11111 Random Address Way",
      "city":"Germantown",
      "state":"MD",
      "zip":"20874"
   },
   "divisions":{
      "ocd-division/country:us/state:md/cd:6":{
         "name":"Maryland's 6th congressional district",
         "officeIndices":[
            0
         ]
      }
   },
   "offices":[
      {
         "name":"United States House of Representatives MD-06",
         "divisionId":"ocd-division/country:us/state:md/cd:6",
         "levels":[
            "country"
         ],
         "roles":[
            "legislatorLowerBody"
         ],
         "officialIndices":[
            0
         ]
      }
   ],
   "officials":[
      {
         "name":"John K. Delaney",
         "address":[
            {
               "line1":"1632 Longworth House Office Building",
               "city":"Washington",
               "state":"DC",
               "zip":"20515"
            }
         ],
         "party":"Democratic",
         "phones":[
            "(202) 225-2721"
         ],
         "urls":[
            "http://delaney.house.gov/"
         ],
         "photoUrl":"http://bioguide.congress.gov/bioguide/photo/D/D000620.jpg",
         "channels":[
            {
               "type":"Facebook",
               "id":"congressmanjohndelaney"
            },
            {
               "type":"Twitter",
               "id":"RepJohnDelaney"
            },
            {
               "type":"YouTube",
               "id":"repjohndelaney"
            }
         ]
      }
   ]
}```
</div>
</div>
</p>

<p>I am attempting to access the value for "name" but am unable to so. I am able to access the objects for "kind", "divisions", "offices", "officials" When I run: </p>

```const repObj = this.props.rep.officials
console.log(repObj);
```

<p>But when I try to access a nested value using:</p>

<p>When I do this.props.rep.officials[0].name, </p>

<p>I receive the error: Uncaught TypeError: Cannot read property '0' of undefined
How do I access this value?</p>

<p>Here is the code where I make the call:</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>export function getRep(){
  return function(dispatch){
    axios.get('https://www.googleapis.com/civicinfo/v2/representatives?key={apikeyremoved}&address=18910+porterfield+way+germantown+md+20874&levels=country&roles=legislatorLowerBody')
      .then(function(response){
        dispatch({type:"GET_REP", payload:response.data})
      })
      .catch(function(err){
        dispatch({type:"GET_REP_REJECTED", payload:err})
        console.log(err);
      })
  }
}</code>```

Code where i make the console log:

class Rep extends React.Component{
  componentDidMount(){
    //Dispatch GET action
    this.props.getRep();
  }
  render(){
    const repObj = this.props.rep.officials[0].name
    console.log(repObj);
    return(
      <Well>
        <Row>
          <Col xs={12}>

Rep name here

          </Col>
        </Row>
      </Well>
    )
  }
}

function mapStateToProps(state){
  return{
    rep:state.rep.rep
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators({
    getRep:getRep,
    //all other actions here
  }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Rep);```

答:
Look at the code. Notice the presence of [] as well as {}.

Officials is an array containing an object. It is not a plain object.

You must first access the property of the array that represents the object.

Then you can access properties of that object.

```<code>this.props.rep.officials[0].name
</code>```

Beware: The naming convention and use an an array indicates that there could be more than one value (and possibly zero). You probably want to use a loop instead of a hard coded 0.

Body:
In an app using react/redux, I made a GET request to Google's Civic Api and received the following object which I added to my state:

{
   "kind":"civicinfo#representativeInfoResponse",
   "normalizedInput":{
      "line1":"11111 Random Address Way",
      "city":"Germantown",
      "state":"MD",
      "zip":"20874"
   },
   "divisions":{
      "ocd-division/country:us/state:md/cd:6":{
         "name":"Maryland's 6th congressional district",
         "officeIndices":[
            0
         ]
      }
   },
   "offices":[
      {
         "name":"United States House of Representatives MD-06",
         "divisionId":"ocd-division/country:us/state:md/cd:6",
         "levels":[
            "country"
         ],
         "roles":[
            "legislatorLowerBody"
         ],
         "officialIndices":[
            0
         ]
      }
   ],
   "officials":[
      {
         "name":"John K. Delaney",
         "address":[
            {
               "line1":"1632 Longworth House Office Building",
               "city":"Washington",
               "state":"DC",
               "zip":"20515"
            }
         ],
         "party":"Democratic",
         "phones":[
            "(202) 225-2721"
         ],
         "urls":[
            "http://delaney.house.gov/"
         ],
         "photoUrl":"http://bioguide.congress.gov/bioguide/photo/D/D000620.jpg",
         "channels":[
            {
               "type":"Facebook",
               "id":"congressmanjohndelaney"
            },
            {
               "type":"Twitter",
               "id":"RepJohnDelaney"
            },
            {
               "type":"YouTube",
               "id":"repjohndelaney"
            }
         ]
      }
   ]
}

I am attempting to access the value for "name" but am unable to so. I am able to access the objects for "kind", "divisions", "offices", "officials" When I run:

const repObj = this.props.rep.officials
console.log(repObj);

But when I try to access a nested value using:

When I do this.props.rep.officials[0].name,

I receive the error: Uncaught TypeError: Cannot read property '0' of undefined
How do I access this value?

Here is the code where I make the call:

export function getRep(){
  return function(dispatch){
    axios.get('https://www.googleapis.com/civicinfo/v2/representatives?key={apikeyremoved}&address=18910+porterfield+way+germantown+md+20874&levels=country&roles=legislatorLowerBody')
      .then(function(response){
        dispatch({type:"GET_REP", payload:response.data})
      })
      .catch(function(err){
        dispatch({type:"GET_REP_REJECTED", payload:err})
        console.log(err);
      })
  }
}

Code where i make the console log:

class Rep extends React.Component{
  componentDidMount(){
    //Dispatch GET action
    this.props.getRep();
  }
  render(){
    const repObj = this.props.rep.officials[0].name
    console.log(repObj);
    return(
      <Well>
        <Row>
          <Col xs={12}>

Rep name here

          </Col>
        </Row>
      </Well>
    )
  }
}

function mapStateToProps(state){
  return{
    rep:state.rep.rep
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators({
    getRep:getRep,
    //all other actions here
  }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Rep);

Body:
Look at the code. Notice the presence of [] as well as {}.

Officials is an array containing an object. It is not a plain object.

You must first access the property of the array that represents the object.

Then you can access properties of that object.

this.props.rep.officials[0].name

Beware: The naming convention and use an an array indicates that there could be more than one value (and possibly zero). You probably want to use a loop instead of a hard coded 0.


问:
This type of CollectionView does not support changes to its SourceCollection from a thread... while using the dispatcher?
So Im developing an addon with a UI that is used inside an application (main application). To make my UI responsive when the main application is working I'm starting my UI in its separate thread like this:

```<code>    public  void ShowDialog(IIFCConverter ifcConverter)
    {

        thread = new Thread(x =>
        {
            thread.Name = "UI-thread";
            window = new MainWindow();
            var mainViewModel = ServiceLocator.Current.GetInstance<MainWindowViewModel>();
            mainViewModel.SetIFCConverter(x as IIFCConverter);
            ViewModelLocator.MainWindow = window;
            window.ShowDialog();

        });
        thread.SetApartmentState(ApartmentState.STA);

        thread.Start(ifcConverter);

    }
</code>```

The first time I start my addon it all works. The second time I start it and it tries to raise events (like OnCollectionChanged) I get a NotSupportedException with the message: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread"

This is one of my methods:

```<code>    private void AddNewFile(AddNewFileMessage obj)
    {
        if (!(obj.Sender is ButtonViewModel)) return;

        if (string.IsNullOrEmpty(obj.Path)) return;

        var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });
        DispatcherHelper.CheckBeginInvokeOnUI(() =>
        {
            ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
        });

    }
</code>```

I get this eventhough Im using the DispatcherHelper from MVVM light.
I have tried using the "normal" dispatcher to, but that gives me the same result.

First of all Im curious to know the mechanics of why its doing this?
I've checked my threads and I can see that the OnOllectionChanged is called from my UI-thread.
I cant seem to find any differences to the thread structure between the first run (that works) and the following.

Second, what can I do about this?

Things that I've tested that didnt help:

Im using the IoC container from MVVM light and its registered as a LocatorProvider, but I create a new IoC container everytime I initialize the UI and set that instance as the LocatorProvider.

Im initializing the DispatcherHelper in the constructor of my window. So that should be on the correct thread.

Something that does actually work is wrapping the action in a try Catch-block like this:

```<code>private void AddNewFile(AddNewFileMessage obj)
{
if (!(obj.Sender is ButtonViewModel)) return;

if (string.IsNullOrEmpty(obj.Path)) return;

var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });

DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    try
    {
        ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
    }
    catch(Exception ex)
    {

    }
});
</code>```

}

However I find this very ugly and would like to avoid it and why does that even work? Everything seems to work fine when I wrap all my actions in try Catch-blocks.

答:
Ok, so I found the real problem.
The viewmodel was indeed created on the same thread as my addon UI.

HOWEVER: I was using the Messenger that is avaliable in the MVVMLight toolkit to handle communication between viewmodels and I forgot to unregister the viewmodel when my windows was closed. So the second time I opened my window and started sending messages between my viewmodels. The first viewmodel reacted and that was what was causing the problem.
That is also why the try-Catch-block worked, because there was a second call from the correct thread that was working.
I added a datetime to the constructor of the viewmodel and there are indeed two different viewmodels being called. I do not understand why I get that exception. If anything the first viewmodel should be connected via datacontext to the first view. Its like the view has hooked up to the events of two different viewmodels.

Anyway, it works now: I just unregister the viewmodel from the message service when my window is closed and it works like a charm.

Body:
So Im developing an addon with a UI that is used inside an application (main application). To make my UI responsive when the main application is working I'm starting my UI in its separate thread like this:

    public  void ShowDialog(IIFCConverter ifcConverter)
    {

        thread = new Thread(x =>
        {
            thread.Name = "UI-thread";
            window = new MainWindow();
            var mainViewModel = ServiceLocator.Current.GetInstance<MainWindowViewModel>();
            mainViewModel.SetIFCConverter(x as IIFCConverter);
            ViewModelLocator.MainWindow = window;
            window.ShowDialog();

        });
        thread.SetApartmentState(ApartmentState.STA);

        thread.Start(ifcConverter);

    }

The first time I start my addon it all works. The second time I start it and it tries to raise events (like OnCollectionChanged) I get a NotSupportedException with the message: "This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread"

This is one of my methods:

    private void AddNewFile(AddNewFileMessage obj)
    {
        if (!(obj.Sender is ButtonViewModel)) return;

        if (string.IsNullOrEmpty(obj.Path)) return;

        var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });
        DispatcherHelper.CheckBeginInvokeOnUI(() =>
        {
            ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
        });

    }

I get this eventhough Im using the DispatcherHelper from MVVM light.
I have tried using the "normal" dispatcher to, but that gives me the same result.

First of all Im curious to know the mechanics of why its doing this?
I've checked my threads and I can see that the OnOllectionChanged is called from my UI-thread.
I cant seem to find any differences to the thread structure between the first run (that works) and the following.

Second, what can I do about this?

Things that I've tested that didnt help:

Im using the IoC container from MVVM light and its registered as a LocatorProvider, but I create a new IoC container everytime I initialize the UI and set that instance as the LocatorProvider.

Im initializing the DispatcherHelper in the constructor of my window. So that should be on the correct thread.

Something that does actually work is wrapping the action in a try Catch-block like this:

private void AddNewFile(AddNewFileMessage obj)
{
if (!(obj.Sender is ButtonViewModel)) return;

if (string.IsNullOrEmpty(obj.Path)) return;

var ifcFileViewModel = new IFCFileViewModel(new Common.Model.IFCFile { Path = obj.Path, Active = true });

DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    try
    {
        ListBoxItems.Insert(ListBoxItems.Count - 1, ifcFileViewModel);
    }
    catch(Exception ex)
    {

    }
});

}

However I find this very ugly and would like to avoid it and why does that even work? Everything seems to work fine when I wrap all my actions in try Catch-blocks.


问:
Excel Export max num of rows to txt file and repeat
It's just one column and each column contains 11 characters, no line breaks.
I found multiple codes on how to export to txt but I can't find how to limit the total amount of rows to 500 and start with a new text file. Can anyone help?

So to be clear. I want to export 500 rows to txt. Then the next 500 to new text file.
All empty lines are already deleted and made sure every line contains exactly 11 characters.

```<code>Sub saveText2()
    Dim filename As String, lineText As String
    Dim myrng As Range, i, j

    filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

    Open filename For Output As #1

    Set myrng = Range("data")

    For i = 1 To myrng.Rows.Count
        For j = 1 To myrng.Columns.Count
            lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
        Next j
        Print #1, lineText
    Next i

    Close #1
End Sub
</code>```

答:
I use this code</p>

```<code>Sub setRangToCsv()
    Dim R As Long, c As Integer
    Dim filename As String, i As Long

    R = Range("a" & Rows.Count).End(xlUp).Row
    c = ActiveSheet.UsedRange.Columns.Count

    For i = 1 To R Step 500
        filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & "_" & Format(i, "0000") & ".txt"
        TransToCSV filename, Range("a" & i).Resize(500, c)
    Next i

End Sub

Sub TransToCSV(myfile As String, rng As Range)

    Dim vDB, vR() As String, vTxt()
    Dim i As Long, n As Long, j As Integer
    Dim objStream
    Dim strFile As String

    Set objStream = CreateObject("ADODB.Stream")
    vDB = rng
    For i = 1 To UBound(vDB, 1)
        n = n + 1
        ReDim vR(1 To UBound(vDB, 2))
        For j = 1 To UBound(vDB, 2)
            vR(j) = vDB(i, j)
        Next j
        ReDim Preserve vTxt(1 To n)
        vTxt(n) = Join(vR, ",")
    Next i
    strtxt = Join(vTxt, vbCrLf)
    With objStream
        '.Charset = "utf-8"
        .Open
        .WriteText strtxt
        .SaveToFile myfile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub
</code>```

Body:
It's just one column and each column contains 11 characters, no line breaks.
I found multiple codes on how to export to txt but I can't find how to limit the total amount of rows to 500 and start with a new text file. Can anyone help?

So to be clear. I want to export 500 rows to txt. Then the next 500 to new text file.
All empty lines are already deleted and made sure every line contains exactly 11 characters.

Sub saveText2()
    Dim filename As String, lineText As String
    Dim myrng As Range, i, j

    filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & ".txt"

    Open filename For Output As #1

    Set myrng = Range("data")

    For i = 1 To myrng.Rows.Count
        For j = 1 To myrng.Columns.Count
            lineText = IIf(j = 1, "", lineText & ",") & myrng.Cells(i, j)
        Next j
        Print #1, lineText
    Next i

    Close #1
End Sub

Body:
I use this code

Sub setRangToCsv()
    Dim R As Long, c As Integer
    Dim filename As String, i As Long

    R = Range("a" & Rows.Count).End(xlUp).Row
    c = ActiveSheet.UsedRange.Columns.Count

    For i = 1 To R Step 500
        filename = ThisWorkbook.Path & "\textfile-" & Format(Now, "ddmmyy-hhmmss") & "_" & Format(i, "0000") & ".txt"
        TransToCSV filename, Range("a" & i).Resize(500, c)
    Next i

End Sub

Sub TransToCSV(myfile As String, rng As Range)

    Dim vDB, vR() As String, vTxt()
    Dim i As Long, n As Long, j As Integer
    Dim objStream
    Dim strFile As String

    Set objStream = CreateObject("ADODB.Stream")
    vDB = rng
    For i = 1 To UBound(vDB, 1)
        n = n + 1
        ReDim vR(1 To UBound(vDB, 2))
        For j = 1 To UBound(vDB, 2)
            vR(j) = vDB(i, j)
        Next j
        ReDim Preserve vTxt(1 To n)
        vTxt(n) = Join(vR, ",")
    Next i
    strtxt = Join(vTxt, vbCrLf)
    With objStream
        '.Charset = "utf-8"
        .Open
        .WriteText strtxt
        .SaveToFile myfile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub


问:
Getting a Unexpected JDWP Error: 103 while trying to upload an image using retrofit to an api server android?
I'm getting the following 103 error message while trying to upload an image on the api server using retrofit multipart, the api receives an api token, "_method":"PUT" and image url as parameters, on response receives the complete JSON but with the previous or default image link, the current selected image does not upload, everything else is optional, any help would be appreciated, code is listed below thanks.

Also main method is POST but "_method":"PUT" parameter lets you upload the image, without _method it becomes a POST message and every other parameter than becomes compulsory, please check the image.

com.sun.jdi.InternalException: Unexpected JDWP Error: 103

Interface:

```<code>public interface UserSignUpClient {

@POST("account")
Call<AuthenticationAccountCreationResponse> createAccount(@Body UserSignUp userSignUp);

@Multipart
@PUT("account")
Call<UserInfo> postImage(@Header("Authorization") String headerValue, @PartMap Map<String, String> map, @PartMap Map<String, File> imageMap, @Part MultipartBody.Part image);

@FormUrlEncoded
@POST("account")
Call<UserInfo> updateUser(@Header("Authorization") String headerValue, @FieldMap Map<String, String> map);
}
</code>```

Retrofit builder class:

```<code>public class RestClient {

private UserSignInClient userSignInClient;
private UserSignUpClient userSignUpClient;
private UserInfoClient userInfoClient;

public RestClient(String baseUrlLink){

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrlLink)
            .addConverterFactory(GsonConverterFactory.create(gson)).build();

    if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_TOKEN)){

        userSignInClient = retrofit.create(UserSignInClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION)) {

        userSignUpClient = retrofit.create(UserSignUpClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_USER_INFO)){

        userInfoClient = retrofit.create(UserInfoClient.class);
    }
}

public UserSignInClient getUserSignInClient() {
    return userSignInClient;
}

public UserSignUpClient getUserSignUpClient() {
    return userSignUpClient;
}

public UserInfoClient getUserInfoClient() {
    return userInfoClient;
}
}
</code>```

Main Class:

```<code>userImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            galleryIntent.setType("*/*");
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

        Uri selectedImageUri = data.getData();
        String filePath = FileUtils.getPath(this, selectedImageUri);
        file = new File(filePath);
        image_name = file.getName();

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            } else {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            }
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);

                sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
                stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));

                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);

                UserUpdate userUpdate = new UserUpdate(file);

                methodMap.put("_method","PUT");
                imageMap.put("image", file);

                Call<UserInfo> uploadImage = new RestClient(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION).getUserSignUpClient()
                        .postImage(stringBuilder.toString(), methodMap, imageMap, body);

                uploadImage.enqueue(new Callback<UserInfo>() {
                    @Override
                    public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {

                        if (response.isSuccessful()) {

                            Picasso.with(DetailActivity.this).load("http://ec2-35-161-195-128.us-west-2.compute.amazonaws.com/" + response.body().getImage()).into(userImage);

                        }
                    }

                    @Override
                    public void onFailure(Call<UserInfo> call, Throwable t) {

                        Toast.makeText(DetailActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

        }
        return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
}
}
</code>```

postman api image = https://i.imgur.com/AoCFZI6.png

答:
I think your problem is you forgot to add a call adapter to the retrofit object. Within your RestClient class you must put something like this:

```<code>Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrlLink)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
</code>```

Also you need to add this dependency inside build.gradle:

```<code>compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
</code>```

I hope it helps.

Cheers.

Body:
I'm getting the following 103 error message while trying to upload an image on the api server using retrofit multipart, the api receives an api token, "_method":"PUT" and image url as parameters, on response receives the complete JSON but with the previous or default image link, the current selected image does not upload, everything else is optional, any help would be appreciated, code is listed below thanks.

Also main method is POST but "_method":"PUT" parameter lets you upload the image, without _method it becomes a POST message and every other parameter than becomes compulsory, please check the image.

com.sun.jdi.InternalException: Unexpected JDWP Error: 103

Interface:

public interface UserSignUpClient {

@POST("account")
Call<AuthenticationAccountCreationResponse> createAccount(@Body UserSignUp userSignUp);

@Multipart
@PUT("account")
Call<UserInfo> postImage(@Header("Authorization") String headerValue, @PartMap Map<String, String> map, @PartMap Map<String, File> imageMap, @Part MultipartBody.Part image);

@FormUrlEncoded
@POST("account")
Call<UserInfo> updateUser(@Header("Authorization") String headerValue, @FieldMap Map<String, String> map);
}

Retrofit builder class:

public class RestClient {

private UserSignInClient userSignInClient;
private UserSignUpClient userSignUpClient;
private UserInfoClient userInfoClient;

public RestClient(String baseUrlLink){

    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrlLink)
            .addConverterFactory(GsonConverterFactory.create(gson)).build();

    if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_TOKEN)){

        userSignInClient = retrofit.create(UserSignInClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION)) {

        userSignUpClient = retrofit.create(UserSignUpClient.class);
    } else if (baseUrlLink.equals(CONSTS.BASE_URL_ADDRESS_USER_INFO)){

        userInfoClient = retrofit.create(UserInfoClient.class);
    }
}

public UserSignInClient getUserSignInClient() {
    return userSignInClient;
}

public UserSignUpClient getUserSignUpClient() {
    return userSignUpClient;
}

public UserInfoClient getUserInfoClient() {
    return userInfoClient;
}
}

Main Class:

userImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            galleryIntent.setType("*/*");
            startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
        }
    });

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {

        Uri selectedImageUri = data.getData();
        String filePath = FileUtils.getPath(this, selectedImageUri);
        file = new File(filePath);
        image_name = file.getName();

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

            } else {

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
            }
        }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {

            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);

                sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
                stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));

                RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
                MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestBody);

                UserUpdate userUpdate = new UserUpdate(file);

                methodMap.put("_method","PUT");
                imageMap.put("image", file);

                Call<UserInfo> uploadImage = new RestClient(CONSTS.BASE_URL_ADDRESS_ACCOUNT_CREATION).getUserSignUpClient()
                        .postImage(stringBuilder.toString(), methodMap, imageMap, body);

                uploadImage.enqueue(new Callback<UserInfo>() {
                    @Override
                    public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {

                        if (response.isSuccessful()) {

                            Picasso.with(DetailActivity.this).load("http://ec2-35-161-195-128.us-west-2.compute.amazonaws.com/" + response.body().getImage()).into(userImage);

                        }
                    }

                    @Override
                    public void onFailure(Call<UserInfo> call, Throwable t) {

                        Toast.makeText(DetailActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }
}

        }
        return;
    }

    // other 'case' lines to check for other
    // permissions this app might request
}
}

postman api image = https://i.imgur.com/AoCFZI6.png

Body:
I think your problem is you forgot to add a call adapter to the retrofit object. Within your RestClient class you must put something like this:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(baseUrlLink)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();

Also you need to add this dependency inside build.gradle:

compile "com.squareup.retrofit2:adapter-rxjava2:2.3.0"

I hope it helps.

Cheers.


问:
force gcc to compile when stack-overflow is detected
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

```<code>#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI
</code>```

and obviously the compiler didnt like that.

答:
If you need to allocate more memory than you have RAM you might do some research on memory mapped files. That way you won't need to worry about the physical memory in your machine (of which you don't have access to all 8GB anyway)

http://msdn.microsoft.com/en-us/library/dd997372.aspx

Body:
How can i force gcc to compile a program in which i declare an array of unsigned integers that is bigger than my ram - without getting the warning warning: "integer overflow in expression"?

eg. i have 8gb of ram and i want do declare an array of 8.5gb.

edit:

thanks everybody, i figured out that the problem wasnt with the datatype but with some preprocessor stuff. it took me quite a while though. :)
i wrote

#define GIBI 1073741824
#define ARRAYSIZE 2*GIBI

and obviously the compiler didnt like that.


问:
HttpWebResponse Status Code 429
I'm doing some integration work with an API which returns a HttpStatusCode 429 when you've hit your daily limit. However the Enum HttpStatusCode in the web response object does not contain this code.

Can some one let me know how I can check for this response code?

Here is some code to show what I'm trying to accomplish:

```<code>try
{
  //do something
}
catch (WebException webExp)
{
     var response = (HttpWebResponse) webExp.Response;

     //here I want to check status code for too many requests but it is not   in the enum.
    if (response.StatusCode == HttpStatusCode.TooManyRequests) throw webExp;
}
</code>```

答:
I had the same problem, you can read the response and then look for 429 or too many requests string:</p>

```<code>string responseStr = "";
Stream responseStream = webEx.Response.GetResponseStream();
if (responseStream != null)
{
    using (StreamReader sr = new StreamReader(responseStream))
    {
       responseStr = sr.ReadToEnd();
    }
}

if (responseStr.Contains("429") || responseStr.Contains("Too many requests"))
Console.WriteLine("Is 429 WebException ");
</code>```

Title: HttpWebResponse Status Code 429

Body:
I'm doing some integration work with an API which returns a HttpStatusCode 429 when you've hit your daily limit. However the Enum HttpStatusCode in the web response object does not contain this code.

Can some one let me know how I can check for this response code?

Here is some code to show what I'm trying to accomplish:

try
{
  //do something
}
catch (WebException webExp)
{
     var response = (HttpWebResponse) webExp.Response;

     //here I want to check status code for too many requests but it is not   in the enum.
    if (response.StatusCode == HttpStatusCode.TooManyRequests) throw webExp;
}

Body:
I had the same problem, you can read the response and then look for 429 or too many requests string:

string responseStr = "";
Stream responseStream = webEx.Response.GetResponseStream();
if (responseStream != null)
{
    using (StreamReader sr = new StreamReader(responseStream))
    {
       responseStr = sr.ReadToEnd();
    }
}

if (responseStr.Contains("429") || responseStr.Contains("Too many requests"))
Console.WriteLine("Is 429 WebException ");


问:
Update references to a submodule in parent repository after submodule's git history is re-written
Following is the script I'm using to rewrite the history of a submodule which is referenced in multiple parent repositories. This runs in Git bash in a windows environment.

```<code>#!/bin/bash

cd submodule_repo

git filter-branch --index-filter 'git rm -q --cached --ignore-unmatch files_to_remove' \--tag-name-filter cat -- --all

git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

git reflog expire --expire=now --all
git gc --prune=now
</code>```

I need to somehow map the SHAs of the old commits to the newly created SHAs, so that I can update the same reference in the parent repositories. Is there a way to do it? I did look at Repository with submodules after rewriting history of submodule, but it's not really helping as I'm updating the original refs to make sure the files I'm removing are not repacked by any chance. I'm relatively new to using git so any guidance would be really appreciated.

Edit:

Following the steps mentioned in comments section of the accepted answer (by @torek) worked for me.

答:
There is no good way to do this (at least with git filter-branch and existing Git tools—the BFG leaves the desired map file around, but still requires constructing something).

When git filter-branch copies commits, it places each new commit's hash into a "map file" (pairing up the old and new IDs—actually a directory in the existing implementation, although this performs very poorly in large filters, so it may someday be altered), so that it's possible to convert from original-commit hash to rewritten-commit hash.  This is how it provides the map function that the git filter-branch documentation refers to here:

A map function is available that takes an "original sha1 id" argument and outputs a "rewritten sha1 id" if the commit has been already rewritten, and "original sha1 id" otherwise; the map function can return several ids on separate lines if your commit filter emitted multiple commits.

Unfortunately, when git filter-branch finishes and cleans up, it removes the mapping table, rather than turning it into a useful database.  If you had the database with the mappings, you could use that with any external items ("gitlink" entries in other repositories, test frameworks, or any other place you might have them saved).  Without the map, there is no good way to handle this. The superproject says, e.g., "use commit 1234567" but that commit no longer exists in the rewritten submodule repository.  The new commit's ID would be in the map, but there is no map.

Body:
Following is the script I'm using to rewrite the history of a submodule which is referenced in multiple parent repositories. This runs in Git bash in a windows environment.

#!/bin/bash

cd submodule_repo

git filter-branch --index-filter 'git rm -q --cached --ignore-unmatch files_to_remove' \--tag-name-filter cat -- --all

git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

git reflog expire --expire=now --all
git gc --prune=now

I need to somehow map the SHAs of the old commits to the newly created SHAs, so that I can update the same reference in the parent repositories. Is there a way to do it? I did look at Repository with submodules after rewriting history of submodule, but it's not really helping as I'm updating the original refs to make sure the files I'm removing are not repacked by any chance. I'm relatively new to using git so any guidance would be really appreciated.

Edit:

Following the steps mentioned in comments section of the accepted answer (by @torek) worked for me.


问:
Find the Key from multiple values array in PHP
I am trying to find the key of which one of the children items exists in. I have this array

```<code>$stdCurl    = array(
    'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
    'blog'      => array('αρθρα', 'blog'),
    'post'      => array('αρθρο', '*post'),
    'products'  => array('προιοντα', 'products'),
    'product'   => array('προιον', 'product'),
    'portfolio' => array('portfolio', 'έργα'),
    'project'   => array('project', 'έργο')
);
</code>```

User have selected the "post" value (marked with *). Now i want to find to which key "post" belongs to. I tried array_search, array_keys but can't make it work..I don't wont to loop, i was wondering if there is any built-in function for arrays for this..

Edited__

Basically i found the answer for my code, i just did not posted it because i wanted to know if there is really any way for this..
The reason i want this is because i parse the url and want to see if any of the keywords "index.php", "home", "product" etc exists in the url and if they exists i wanted to get the section these keywords belong to.

Let's say url is http://domain.gr/gear-s3-samsung/product.  I parse the url and explode it on "/", now i want to know if a keyword exists and if a keyword exists, return me the key that the keyword exists in from $stdCurl array.

```<code>foreach($this->stdCurl as $key => $value):
    foreach($value as $definedSection):
        if(in_array($definedSection, $this->urlStructure)):
            $this->pageKey = $key;
            $this->pageSection = $definedSection;
        else:
            continue;
        endif;
    endforeach;
endforeach;
</code>```

Now i get they $key and shows me the section the keyword exists..But i wanted to know if i give you the value "αρθρο" how can i get the "post" key?

答:
```<code>$needle = '*post';

foreach ($stdCurl as $key => $value) {
    if (array_search($needle, $value))
        echo $key;
}
</code>```

Body:
I am trying to find the key of which one of the children items exists in. I have this array

$stdCurl    = array(
    'homepage'  => array('', '/', 'index.php', 'home', 'arxiki'),
    'blog'      => array('αρθρα', 'blog'),
    'post'      => array('αρθρο', '*post'),
    'products'  => array('προιοντα', 'products'),
    'product'   => array('προιον', 'product'),
    'portfolio' => array('portfolio', 'έργα'),
    'project'   => array('project', 'έργο')
);

User have selected the "post" value (marked with *). Now i want to find to which key "post" belongs to. I tried array_search, array_keys but can't make it work..I don't wont to loop, i was wondering if there is any built-in function for arrays for this..

Edited__

Basically i found the answer for my code, i just did not posted it because i wanted to know if there is really any way for this..
The reason i want this is because i parse the url and want to see if any of the keywords "index.php", "home", "product" etc exists in the url and if they exists i wanted to get the section these keywords belong to.

Let's say url is http://domain.gr/gear-s3-samsung/product.  I parse the url and explode it on "/", now i want to know if a keyword exists and if a keyword exists, return me the key that the keyword exists in from $stdCurl array.

foreach($this->stdCurl as $key => $value):
    foreach($value as $definedSection):
        if(in_array($definedSection, $this->urlStructure)):
            $this->pageKey = $key;
            $this->pageSection = $definedSection;
        else:
            continue;
        endif;
    endforeach;
endforeach;

Now i get they $key and shows me the section the keyword exists..But i wanted to know if i give you the value "αρθρο" how can i get the "post" key?


问:
how can I write a query (SQL Server) that, based on a table, it can return all the tables that it references?
I have a massive procedure which does a ton of deletes. The issue is that:

There are missing tables from this delete (that need to be deleted)

I'm having a hard time with the order of the deletes.

I'm wondering if there is a way to build a query in which I give it a table name and then it shows me all the tables I need to delete from before deleting this table. Anyone can give me a hand?

答:
The following query returns all the tables which have foreign keys pointing into your table in @tablename.

```<code>declare @tablename sysname = 'your table name';
select OBJECT_NAME(parent_object_id) parent_object_name
from sys.foreign_keys
where OBJECT_NAME(referenced_object_id) = @tablename;
</code>```

All these would have to be dropped before dropping your table.

(Tested in SQL Server 2014)

And as an additional thought - if you need to go to thenext level down, and find all foreign keys that reference this list of tables, you can use a common table expression as such:

```<code>declare @tablename sysname = 'your table name';
;with cte as (
    select OBJECT_NAME(parent_object_id) parent_object_name, OBJECT_NAME(referenced_object_id) referenced_object_name
    from sys.foreign_keys
    where OBJECT_NAME(referenced_object_id) = @tablename
    union all
    select OBJECT_NAME(parent_object_id) parent_object_name, OBJECT_NAME(referenced_object_id)
    from sys.foreign_keys fk
    inner join cte on OBJECT_NAME(fk.referenced_object_id) = cte.parent_object_name
)
select * from cte
</code>```

Body:
The following query returns all the tables which have foreign keys pointing into your table in @tablename.

declare @tablename sysname = 'your table name';
select OBJECT_NAME(parent_object_id) parent_object_name
from sys.foreign_keys
where OBJECT_NAME(referenced_object_id) = @tablename;

All these would have to be dropped before dropping your table.

(Tested in SQL Server 2014)

And as an additional thought - if you need to go to thenext level down, and find all foreign keys that reference this list of tables, you can use a common table expression as such:

declare @tablename sysname = 'your table name';
;with cte as (
    select OBJECT_NAME(parent_object_id) parent_object_name, OBJECT_NAME(referenced_object_id) referenced_object_name
    from sys.foreign_keys
    where OBJECT_NAME(referenced_object_id) = @tablename
    union all
    select OBJECT_NAME(parent_object_id) parent_object_name, OBJECT_NAME(referenced_object_id)
    from sys.foreign_keys fk
    inner join cte on OBJECT_NAME(fk.referenced_object_id) = cte.parent_object_name
)
select * from cte


问:
Angular2 - Promise inside a conditional statement
I need to wait an answer from my server to say if the email is already taken or not. But I'm struggling to make this synchronously. In my if statement, typescript says that isCorrectEmail() is a void function (that I can understand but cannot solve). Any idea? </p>

```<code>isEmailAvailable(){

    return new Promise( (resolve, reject) => {

        this.authService.checkemail(this.user.email).then(result => {

                let res = <any> result;
                if (res.code == 0){
                    resolve(true);
                }
                else resolve(false);

              }, (err) => {
               reject(false);
        });

    });

};

isCorrectEmail(){

    this.isEmailAvailable().then( (result) => { return result ; } );

};

 checkPersonalInfos()
 {
   if ( this.isCorrectEmail() == true){...}
   ..
 }
</code>```

答:
You cannot turn an asynchronous call into a synchronous one.

You have two options: move the code which needs the use the resulting value entirely inside a then callback:

```<code> checkPersonalInfos()
 {
   this.isEmailAvailable().then(isAvailable => {
       if (isAvailable) { ... }
   }
 }
</code>```

Or use the async/await syntax to make it look like synchronous code, but remember it is still asynchronous so other code will run during the await and if you return a result from the function it will be wrapped inside a Promise():

```<code> async checkPersonalInfos()
 {
   if (await this.isEmailAvailable()) { ... }
   ...
 }
</code>```

You don't actually need your isCorrectEmail() function here as it does nothing at all to the result, but if it did something more complex so it was actually needed then it has to return the Promise:

```<code>isCorrectEmail(): Promise<boolean> {
    return this.isEmailAvailable().then(result => result);
};
</code>```

Body:
I need to wait an answer from my server to say if the email is already taken or not. But I'm struggling to make this synchronously. In my if statement, typescript says that isCorrectEmail() is a void function (that I can understand but cannot solve). Any idea?

isEmailAvailable(){

    return new Promise( (resolve, reject) => {

        this.authService.checkemail(this.user.email).then(result => {

                let res = <any> result;
                if (res.code == 0){
                    resolve(true);
                }
                else resolve(false);

              }, (err) => {
               reject(false);
        });

    });

};

isCorrectEmail(){

    this.isEmailAvailable().then( (result) => { return result ; } );

};

 checkPersonalInfos()
 {
   if ( this.isCorrectEmail() == true){...}
   ..
 }

Body:
You cannot turn an asynchronous call into a synchronous one.

You have two options: move the code which needs the use the resulting value entirely inside a then callback:

 checkPersonalInfos()
 {
   this.isEmailAvailable().then(isAvailable => {
       if (isAvailable) { ... }
   }
 }

Or use the async/await syntax to make it look like synchronous code, but remember it is still asynchronous so other code will run during the await and if you return a result from the function it will be wrapped inside a Promise():

 async checkPersonalInfos()
 {
   if (await this.isEmailAvailable()) { ... }
   ...
 }

You don't actually need your isCorrectEmail() function here as it does nothing at all to the result, but if it did something more complex so it was actually needed then it has to return the Promise:

isCorrectEmail(): Promise<boolean> {
    return this.isEmailAvailable().then(result => result);
};


问:
Reset button not updating value in AngularJS
I'm pulling blanks on this, it looks like it should work, but...

I have a button:

```<code> <button class="btn btn-warning" type="reset" ng-click="reset()">Clear </button>
</code>```

Condensed version of reset function:

```<code>  $scope.reset = function() {
        $scope.application = {};
        $scope.PostDataResponse = null;
        $scope.errors = null;
        $scope.selectedApplication = null;
        $scope.application.status = true;
        $scope.application.version = 1.0;
        $scope.gridOptions.data.length = 0;
        $scope.ApplicationSettingsForm.$setPristine();
        $scope.ApplicationSettingsForm.$setUntouched();
    };
</code>```

Input I'm trying to reset:

```<code><input type="number" style="font-family: sans-serif" class="form-control" ng-model="application.version" ng-disabled="true" id="Version" name="Version" placeholder="Version..." required>
</code>```

How it seeds when the page is first loaded:

```<code>    $scope.application = {};
    $scope.application.version = 1.0;
</code>```

When the page loads I get a 1 in there, but when I click reset, it reverts to Version... instead of the expected 1.  What am I doing wrong here?

答:
Your code works, but you have to define $scope.application as an object in your controller:

var myApp = angular.module('myApp', []);

myApp.controller('FirstCtrl', function($scope) {
   $scope.application = { version: 1.0 };

   $scope.reset = function() {
     $scope.application = {};
     $scope.application.version = 1.0;
   };
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="FirstCtrl">
    <input type="number" style="font-family: sans-serif" ng-model="application.version" placeholder="Version..." required>
    <button type="reset" ng-click="reset()">Clear </button>
</div></code>```

Body:
I'm pulling blanks on this, it looks like it should work, but...

I have a button:

 <button class="btn btn-warning" type="reset" ng-click="reset()">Clear </button>

Condensed version of reset function:

  $scope.reset = function() {
        $scope.application = {};
        $scope.PostDataResponse = null;
        $scope.errors = null;
        $scope.selectedApplication = null;
        $scope.application.status = true;
        $scope.application.version = 1.0;
        $scope.gridOptions.data.length = 0;
        $scope.ApplicationSettingsForm.$setPristine();
        $scope.ApplicationSettingsForm.$setUntouched();
    };

Input I'm trying to reset:

<input type="number" style="font-family: sans-serif" class="form-control" ng-model="application.version" ng-disabled="true" id="Version" name="Version" placeholder="Version..." required>

How it seeds when the page is first loaded:

    $scope.application = {};
    $scope.application.version = 1.0;

When the page loads I get a 1 in there, but when I click reset, it reverts to Version... instead of the expected 1.  What am I doing wrong here?

Body:
Your code works, but you have to define $scope.application as an object in your controller:

var myApp = angular.module('myApp', []);

myApp.controller('FirstCtrl', function($scope) {
   $scope.application = { version: 1.0 };

   $scope.reset = function() {
     $scope.application = {};
     $scope.application.version = 1.0;
   };
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="FirstCtrl">
    <input type="number" style="font-family: sans-serif" ng-model="application.version" placeholder="Version..." required>
    <button type="reset" ng-click="reset()">Clear </button>
</div>


问:
Spring MVC @PathVariable treated as @RequestParam
I have a spring mvc API (config in XML) with multiple services inside. But when I try to add a service with a @RequestMapping containing a path variable /{theCurrencyCode}, the resource created is not what I expected.

What I expected :

http://localhost:8080/api/v3/parameters/currencies/EUR

What works :

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

This is my mapping :

```<code>import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}
</code>```

Implementation :

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

  private final CurrenciesService service;

  @Autowired
  public ParametersApiController(CurrenciesService service) {
    this.service = service;
  }

  @Override
  public ResponseEntity<List<Currency>> GetCurrencies(String code) {

    final List<Currency> currencies = service.getCurrencies(code);

    return new ResponseEntity<>(currencies, HttpStatus.OK);
  }
}
</code>```

Swagger UI confirmed this, seeing theCurrencyCode as a "Parameter Type" query instead of path.

How do I get my @PathVariable to work ?

答:
Change your interface as:

```<code>import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable String theCurrencyCode);

}
</code>```

Your path variable name and URL path name should match. No need to specify parameter name in the bracket.

Body:
I have a spring mvc API (config in XML) with multiple services inside. But when I try to add a service with a @RequestMapping containing a path variable /{theCurrencyCode}, the resource created is not what I expected.

What I expected :

http://localhost:8080/api/v3/parameters/currencies/EUR

What works :

http://localhost:8080/api/v3/parameters/currencies/{theCurrencyCode}?theCurrencyCode=EUR

This is my mapping :

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable("theCurrencyCode") String theCurrencyCode);

}

Implementation :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;

import java.util.ArrayList;
import java.util.List;

@Controller
public class ParametersApiController implements ParametersApi{

  private final CurrenciesService service;

  @Autowired
  public ParametersApiController(CurrenciesService service) {
    this.service = service;
  }

  @Override
  public ResponseEntity<List<Currency>> GetCurrencies(String code) {

    final List<Currency> currencies = service.getCurrencies(code);

    return new ResponseEntity<>(currencies, HttpStatus.OK);
  }
}

Swagger UI confirmed this, seeing theCurrencyCode as a "Parameter Type" query instead of path.

How do I get my @PathVariable to work ?

Body:
Change your interface as:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@RequestMapping(value = "v3/", produces = { APPLICATION_JSON_VALUE })
public interface ParametersApi {

  @RequestMapping(
      value = "/parameters/currencies/{theCurrencyCode}",
      produces = { "application/json" },
      method = RequestMethod.GET)
  ResponseEntity<List<Currency>> GetCurrencies(@PathVariable String theCurrencyCode);

}

Your path variable name and URL path name should match. No need to specify parameter name in the bracket.


问:
How to check if a table is locked in sql server
I have a large report I am running on sql server. It takes several minutes to run. I don't want users clicking run twice. Since i wrap the whole procedure in a transaction, how do I check to see if the table is locked by a transaction? If so I would want to return an error message saying "report generating, please try again in a few  minutes".

How can this be accomplished?

答:
sys.dm_tran_locks  contains the locking information of the sessions

If you want to know a specific table is locked or not, you can use the following query

```<code>SELECT
 *
from
 sys.dm_tran_locks
where
  resource_associated_entity_id = object_id('schemaname.tablename')
</code>```

if you are interested in finding both login name of the user and the query being run

```<code>SELECT
 DB_NAME(resource_database_id)
 , s.original_login_name
 , s.status
 , s.program_name
 , s.host_name
 , (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
 ,*
from
  sys.dm_tran_locks dbl
     JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
  INNER JOIN  sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
 DB_NAME(dbl.resource_database_id) = 'dbname'
</code>```

For more infomraton locking query

More infor about sys.dm_tran_locks

Body:
sys.dm_tran_locks  contains the locking information of the sessions

If you want to know a specific table is locked or not, you can use the following query

SELECT
 *
from
 sys.dm_tran_locks
where
  resource_associated_entity_id = object_id('schemaname.tablename')

if you are interested in finding both login name of the user and the query being run

SELECT
 DB_NAME(resource_database_id)
 , s.original_login_name
 , s.status
 , s.program_name
 , s.host_name
 , (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
 ,*
from
  sys.dm_tran_locks dbl
     JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
  INNER JOIN  sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
where
 DB_NAME(dbl.resource_database_id) = 'dbname'

For more infomraton locking query

More infor about sys.dm_tran_locks


问:
Is there any way to sync my Visual Studio Code settings between instances?
I'd like to be able to sync my VS Code user settings (File > Preferences > User Settings) to the cloud somehow so I can easily share them between multiple installations, as in Windows 10 and Visual Studio.

Is there a supported way of doing this? Direct support in Code would be great, but otherwise being able to move my settings.json location to a Dropbox or OneDrive folder would work too.

I'm looking specifically for a way of doing this automatically and silently. Manually exporting/importing is too cumbersome and isn't what I'm looking for.

Update: this is now a built-in feature in VS Code.

答:
I place my settings.json in a configuration file that I sync with git (though Dropbox would also work) and use a Python script to symlink it to the correct location for each platform so updating it from the settings menu syncs across my machines. Creating symlinks requires admin privileges on Windows.

```<code>import os
import platform

# Find the settings file in the same directory as this script
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
VS_SETTINGS_SRC_PATH = os.path.join(SCRIPT_DIR, 'settings.json')

# https://code.visualstudio.com/docs/getstarted/settings#_settings-file-locations
if platform.system() == 'Windows':
    VS_SETTINGS_DST_PATH = os.path.expandvars(r"%APPDATA%\Code\User\settings.json")
elif platform.system() == "Darwin":
    VS_SETTINGS_DST_PATH = os.path.expandvars(r"$HOME/Library/Application Support/Code/User/settings.json")
elif platform.system() == "Linux":
    raise NotImplementedError()
else:
    raise NotImplementedError()

# On Windows, there might be a symlink pointing to a different file
# Always remove symlinks
if os.path.islink(VS_SETTINGS_DST_PATH):
    os.remove(VS_SETTINGS_DST_PATH)

choice = input('symlink %r -> %r ? (y/n) ' % (VS_SETTINGS_SRC_PATH, VS_SETTINGS_DST_PATH))
if choice == 'y':
    os.symlink(VS_SETTINGS_SRC_PATH, VS_SETTINGS_DST_PATH)
    print('Done')
else:
    print('aborted')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I place my settings.json in a configuration file that I sync with git (though Dropbox would also work) and use a Python script to symlink it to the correct location for each platform so updating it from the settings menu syncs across my machines. Creating symlinks requires admin privileges on Windows.

import os
import platform

# Find the settings file in the same directory as this script
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
VS_SETTINGS_SRC_PATH = os.path.join(SCRIPT_DIR, 'settings.json')

# https://code.visualstudio.com/docs/getstarted/settings#_settings-file-locations
if platform.system() == 'Windows':
    VS_SETTINGS_DST_PATH = os.path.expandvars(r"%APPDATA%\Code\User\settings.json")
elif platform.system() == "Darwin":
    VS_SETTINGS_DST_PATH = os.path.expandvars(r"$HOME/Library/Application Support/Code/User/settings.json")
elif platform.system() == "Linux":
    raise NotImplementedError()
else:
    raise NotImplementedError()

# On Windows, there might be a symlink pointing to a different file
# Always remove symlinks
if os.path.islink(VS_SETTINGS_DST_PATH):
    os.remove(VS_SETTINGS_DST_PATH)

choice = input('symlink %r -> %r ? (y/n) ' % (VS_SETTINGS_SRC_PATH, VS_SETTINGS_DST_PATH))
if choice == 'y':
    os.symlink(VS_SETTINGS_SRC_PATH, VS_SETTINGS_DST_PATH)
    print('Done')
else:
    print('aborted')


问:
Hide/Show 2 forms in winform
I have two Forms, Login and Form1. When I click btnLogin_Click on the Login form, it opens Form1 with this code:

```<code>private void btnLogin_Click(object sender, EventArgs e)
{
    Form1 pu = new Form1(label2.Text);
    pu.Show();
    pu.FormClosing += Pu_FormClosing;
    Hide();
}

private void Pu_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Show();
}
</code>```

And when I click btnExit_Click on Form1, it closes the form and opens the Login form by using this code:

```<code>private void btnExit_Click(object sender, EventArgs e)
{
    this.Close();
}
</code>```

Now what I want is to find a way that, when I click btnExit it Hides Form1 and opens the Login form, and when I click the login button on the Login Form, it shows Form1 instead of creating a new instance.

答:
You have to find the (hidden) instance via Application.OpenForms:

The OpenForms property represents a read-only collection of forms
  owned by the application. This collection can be searched by index
  position or by the Name of the Form.

```<code>using System.Linq;

...

Form1 form = Application
  .OpenForms
  .OfType<Form1>()
  .LastOrDefault(); // if we have several Form1 instances, let's take the last one

if (from == null)   // no Form1 instance found, have to create one
  form = new Form1();

form.Show();
</code>```

Title: Hide/Show 2 forms in winform

Body:
I have two Forms, Login and Form1. When I click btnLogin_Click on the Login form, it opens Form1 with this code:

private void btnLogin_Click(object sender, EventArgs e)
{
    Form1 pu = new Form1(label2.Text);
    pu.Show();
    pu.FormClosing += Pu_FormClosing;
    Hide();
}

private void Pu_FormClosing(object sender, FormClosingEventArgs e)
{
    this.Show();
}

And when I click btnExit_Click on Form1, it closes the form and opens the Login form by using this code:

private void btnExit_Click(object sender, EventArgs e)
{
    this.Close();
}

Now what I want is to find a way that, when I click btnExit it Hides Form1 and opens the Login form, and when I click the login button on the Login Form, it shows Form1 instead of creating a new instance.

Body:
You have to find the (hidden) instance via Application.OpenForms:

The OpenForms property represents a read-only collection of forms
  owned by the application. This collection can be searched by index
  position or by the Name of the Form.

using System.Linq;

...

Form1 form = Application
  .OpenForms
  .OfType<Form1>()
  .LastOrDefault(); // if we have several Form1 instances, let's take the last one

if (from == null)   // no Form1 instance found, have to create one
  form = new Form1();

form.Show();


问:
Vba making mulitstate symbols disappear
I am using VBA for processbook. I am trying to get the multistate values for a symbol and make it only visible if it is on or in state 2. It is not working and cant figure out what else I need to include in my code. It is giving me an error saying "Object variable or with block variable not set" Any thoughts?</p>

```<code>Option Explicit

Private Sub Display_DataUpdate()
Dim Simplehorizontalconveyor_16 As Symbol
Dim curState16 As MultiState

    Set curState16 = Simplehorizontalconveyor_16.GetMultiState
        If (curState16 = 2) Then
            Simplehorizontalconveyor_16.Visible = True
        Else
            Simplehorizontalconveyor_16.Visible = False
        End If
End Sub
</code>```

答:
You need to create an instance of Simplehorizontalconveyor_16:</p>

```<code>Set Simplehorizontalconveyor_16 = <something>
</code>```

Title: Vba making mulitstate symbols disappear

Body:
I am using VBA for processbook. I am trying to get the multistate values for a symbol and make it only visible if it is on or in state 2. It is not working and cant figure out what else I need to include in my code. It is giving me an error saying "Object variable or with block variable not set" Any thoughts?

Option Explicit

Private Sub Display_DataUpdate()
Dim Simplehorizontalconveyor_16 As Symbol
Dim curState16 As MultiState

    Set curState16 = Simplehorizontalconveyor_16.GetMultiState
        If (curState16 = 2) Then
            Simplehorizontalconveyor_16.Visible = True
        Else
            Simplehorizontalconveyor_16.Visible = False
        End If
End Sub

Body:
You need to create an instance of Simplehorizontalconveyor_16:

Set Simplehorizontalconveyor_16 = <something>


问:
Regex evaluate to true but its not supposed to
I have input field which db is expecting to come as integer. if i type 60 it works fine, but 60.00 doesn't. I did RegExp for validation with the ^[0-9]+/ expession. It works fine for inputs like 60.asdass, 60.0320320, dasdasdas.60 etc. but if i type 60. and it evaluates to true and it passes the validation and i get an error from db. How can i make my regex to sets as false in this situation?

答:
You could test the rest of the array as well and use start and end of the string as well for testing.

function check() {
    var element =document.getElementById('input'),
        value = element.value;

    element.style.color = /^\d+(\.\d+)*$/.test(value) ? '#000000': '#ff0000';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="input" type="text" onkeyup="check()"></code>```

Body:
You could test the rest of the array as well and use start and end of the string as well for testing.

function check() {
    var element =document.getElementById('input'),
        value = element.value;

    element.style.color = /^\d+(\.\d+)*$/.test(value) ? '#000000': '#ff0000';
}

<input id="input" type="text" onkeyup="check()">


问:
Check when script has loaded
I am trying to call a function that, on the load of the script above it, will run some JavaScript.

```<code><script src="../Layout/jquery.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript" src="helperscript.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        var itemid = '1';
        if(itemid)
        {
            idselect(itemid);
        }
    })
</script>
</code>```

helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.

Can anyone help me?

答:
Scripts load in order and are blocking.

There must be a problem with the loading of the script, not the timing.

Most likely you have either a mistake in the URL (resulting in a 404) or a JavaScript error (which would show up on the error console)

Title: Check when script has loaded

Body:
I am trying to call a function that, on the load of the script above it, will run some JavaScript.

helperscript.js contains the function idselect.
When I load the page I get an error saying that 'idselect is undefined', even though it is in the above file. I suspect that this is due to helperscript not being fully loaded yet, but that is just a hunch.

Can anyone help me?


答:
You could do:

```<code>apply(A,1,function(x) all(x %in% B))
</code>```

Or vectorized:

```<code>rowSums(matrix(A %in% B, ncol = ncol(A)))==ncol(A)
</code>```

Title: Filter all rows having all their numbers existing in another matrix

Body:
Having a matrix A like:

    [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12]
  [1,]   11   14   17   20   23   26    7    1   10     4    21     3
  [2,]   12   15    8   21   14   27   17   11   19     2     1     3
  [3,]   13   16   19   22   25   28    7   11   10     5    10     4
  [4,]   11   15   28   21    4   27    7    1   12    20    12    23
  [5,]   14   16    9   22   25   28    7    1   13    21    29     3
  [6,]   11    3    6   23   24   26    7    1   14    12    20     4

and a matrix B like:

  [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14] ,15] [,16] [,17] [,18]
 [1,]     2   17   10    4    5    6    7    1    21    20    23    24    11  14     3    26    12    10

I want to get only the rows that have all their values existing in matrix B.
   The result should be:

  [1] TRUE
  [2] FALSE
  [3] FALSE
  [4] FALSE
  [5] FALSE
  [6] TRUE

Is there an R function I can use to solve it?

Body:
You could do:

apply(A,1,function(x) all(x %in% B))

Or vectorized:

rowSums(matrix(A %in% B, ncol = ncol(A)))==ncol(A)


问:
Accessing nested values in Javascript Object
In an app using react/redux, I made a GET request to Google's Civic Api and received the following object which I added to my state:

{
   "kind":"civicinfo#representativeInfoResponse",
   "normalizedInput":{
      "line1":"11111 Random Address Way",
      "city":"Germantown",
      "state":"MD",
      "zip":"20874"
   },
   "divisions":{
      "ocd-division/country:us/state:md/cd:6":{
         "name":"Maryland's 6th congressional district",
         "officeIndices":[
            0
         ]
      }
   },
   "offices":[
      {
         "name":"United States House of Representatives MD-06",
         "divisionId":"ocd-division/country:us/state:md/cd:6",
         "levels":[
            "country"
         ],
         "roles":[
            "legislatorLowerBody"
         ],
         "officialIndices":[
            0
         ]
      }
   ],
   "officials":[
      {
         "name":"John K. Delaney",
         "address":[
            {
               "line1":"1632 Longworth House Office Building",
               "city":"Washington",
               "state":"DC",
               "zip":"20515"
            }
         ],
         "party":"Democratic",
         "phones":[
            "(202) 225-2721"
         ],
         "urls":[
            "http://delaney.house.gov/"
         ],
         "photoUrl":"http://bioguide.congress.gov/bioguide/photo/D/D000620.jpg",
         "channels":[
            {
               "type":"Facebook",
               "id":"congressmanjohndelaney"
            },
            {
               "type":"Twitter",
               "id":"RepJohnDelaney"
            },
            {
               "type":"YouTube",
               "id":"repjohndelaney"
            }
         ]
      }
   ]
}```
</div>
</div>
</p>

<p>I am attempting to access the value for "name" but am unable to so. I am able to access the objects for "kind", "divisions", "offices", "officials" When I run: </p>

```const repObj = this.props.rep.officials
console.log(repObj);
```

<p>But when I try to access a nested value using:</p>

<p>When I do this.props.rep.officials[0].name, </p>

<p>I receive the error: Uncaught TypeError: Cannot read property '0' of undefined
How do I access this value?</p>

<p>Here is the code where I make the call:</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>export function getRep(){
  return function(dispatch){
    axios.get('https://www.googleapis.com/civicinfo/v2/representatives?key={apikeyremoved}&address=18910+porterfield+way+germantown+md+20874&levels=country&roles=legislatorLowerBody')
      .then(function(response){
        dispatch({type:"GET_REP", payload:response.data})
      })
      .catch(function(err){
        dispatch({type:"GET_REP_REJECTED", payload:err})
        console.log(err);
      })
  }
}</code>```

Code where i make the console log:

class Rep extends React.Component{
  componentDidMount(){
    //Dispatch GET action
    this.props.getRep();
  }
  render(){
    const repObj = this.props.rep.officials[0].name
    console.log(repObj);
    return(
      <Well>
        <Row>
          <Col xs={12}>

Rep name here

          </Col>
        </Row>
      </Well>
    )
  }
}

function mapStateToProps(state){
  return{
    rep:state.rep.rep
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators({
    getRep:getRep,
    //all other actions here
  }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Rep);```

答: As officials is an array, this.props.rep.officials[0].name should return the name property of first obj. In officials.

Body:
In an app using react/redux, I made a GET request to Google's Civic Api and received the following object which I added to my state:

{
   "kind":"civicinfo#representativeInfoResponse",
   "normalizedInput":{
      "line1":"11111 Random Address Way",
      "city":"Germantown",
      "state":"MD",
      "zip":"20874"
   },
   "divisions":{
      "ocd-division/country:us/state:md/cd:6":{
         "name":"Maryland's 6th congressional district",
         "officeIndices":[
            0
         ]
      }
   },
   "offices":[
      {
         "name":"United States House of Representatives MD-06",
         "divisionId":"ocd-division/country:us/state:md/cd:6",
         "levels":[
            "country"
         ],
         "roles":[
            "legislatorLowerBody"
         ],
         "officialIndices":[
            0
         ]
      }
   ],
   "officials":[
      {
         "name":"John K. Delaney",
         "address":[
            {
               "line1":"1632 Longworth House Office Building",
               "city":"Washington",
               "state":"DC",
               "zip":"20515"
            }
         ],
         "party":"Democratic",
         "phones":[
            "(202) 225-2721"
         ],
         "urls":[
            "http://delaney.house.gov/"
         ],
         "photoUrl":"http://bioguide.congress.gov/bioguide/photo/D/D000620.jpg",
         "channels":[
            {
               "type":"Facebook",
               "id":"congressmanjohndelaney"
            },
            {
               "type":"Twitter",
               "id":"RepJohnDelaney"
            },
            {
               "type":"YouTube",
               "id":"repjohndelaney"
            }
         ]
      }
   ]
}

I am attempting to access the value for "name" but am unable to so. I am able to access the objects for "kind", "divisions", "offices", "officials" When I run:

const repObj = this.props.rep.officials
console.log(repObj);

But when I try to access a nested value using:

When I do this.props.rep.officials[0].name,

I receive the error: Uncaught TypeError: Cannot read property '0' of undefined
How do I access this value?

Here is the code where I make the call:

export function getRep(){
  return function(dispatch){
    axios.get('https://www.googleapis.com/civicinfo/v2/representatives?key={apikeyremoved}&address=18910+porterfield+way+germantown+md+20874&levels=country&roles=legislatorLowerBody')
      .then(function(response){
        dispatch({type:"GET_REP", payload:response.data})
      })
      .catch(function(err){
        dispatch({type:"GET_REP_REJECTED", payload:err})
        console.log(err);
      })
  }
}

Code where i make the console log:

class Rep extends React.Component{
  componentDidMount(){
    //Dispatch GET action
    this.props.getRep();
  }
  render(){
    const repObj = this.props.rep.officials[0].name
    console.log(repObj);
    return(
      <Well>
        <Row>
          <Col xs={12}>

Rep name here

          </Col>
        </Row>
      </Well>
    )
  }
}

function mapStateToProps(state){
  return{
    rep:state.rep.rep
  }
}

function mapDispatchToProps(dispatch){
  return bindActionCreators({
    getRep:getRep,
    //all other actions here
  }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(Rep);