问:
Correct way to assign fields in constructor in a derived class using typescript and babel with tc39
So I ran in to an issue where after a constructor was run the values assigned to a field in a class were over written with undefined.

It was related to this issue https://github.com/babel/babel/issues/9105 which references https://github.com/tc39/proposal-class-fields

The repro code is below.

I sort of understand some of the reasoning behind why this was chosen, and people who are far more familiar with javascript and the nuances of choices have argued this extensively, so I assume their choice was a better one than I could make.

But this seems really horrible and leads to code that looks like it should work, and if you debug it everything seems to work until the constructor finishes then everything is undefined. So my question is what is the correct way to properly handle this kind of scenario? You can work around this by doing this myField: string = this.myField, but that code is confusing as hell to someone who doesn't understand everything that's happening, and most people would remove it as clearly useless.

I'm trying to figure out what the idiomatic code is to assign fields in a constructor and everything I've come up with so far looks horrible and seems like an anti-pattern.

```<code>class Base {
    constructor(dto?){
        if(dto){
            this.updateFromDTO(dto);
        }
    }

    updateFromDTO(dto) : this{
        return this;
    }
}

class Extends extends Base {
    myField: string;

    updateFromDTO(dto) {
        super.updateFromDTO(dto);
        console.log('I was called');
        this.myField = "weee";
        console.log(this.myField);
        return this;
    }
}

console.log(new Extends("123"));//logs 'I was called', 'weee', then the extends object which has myField as undefined.
</code>```

Babel config to get this behavior

```<code>const DEVELOPMENT = 'production' !== process.env.NODE_ENV

module.exports = {
    presets: [
        ["@babel/preset-env", {useBuiltIns: "entry"}],
        "@babel/preset-react",
        "@babel/typescript"
    ],
    plugins: [
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-export-default-from",
        "@babel/plugin-syntax-dynamic-import",
        ["@babel/plugin-transform-runtime", {"regenerator": true}],
        "@babel/plugin-transform-classes",
    ],
}
</code>```

答:
A workaround to https://github.com/babel/babel/issues/9105 that works both with tsc and babel is declaration merging.

in your case:

```<code>  class Base {
    constructor(dto?: any) {
      if (dto) {
        this.updateFromDTO(dto);
      }
    }

    updateFromDTO(dto: any): this {
      return this;
    }
  }

  // using declaration merging
  interface Extends {
    myField: string;
  }
  class Extends extends Base {
    updateFromDTO(dto: any) {
      super.updateFromDTO(dto);
      console.log("I was called");
      this.myField = "weee";
      console.log(this.myField);
      return this;
    }
  }
</code>```

in a simpler example:

```<code>  interface A {}
  interface B {}

  class Base {
    prop: A | B | null = null;
  }

  class Sub1 extends Base {
    prop!: A | null; // type narrowed
  }

  // using declaration merging
  interface Sub2 {
    prop: A | null; // type narrowed
  }
  class Sub2 extends Base {
  }
  console.log("without declaration merging");
  console.log(`${new Sub1().prop}`); // tsc: null, babel: undefined
  console.log("with declaration merging");
  console.log(`${new Sub2().prop}`); // tsc: null, babel: null
</code>```

The declaration merging here makes typecript aware of the narrowed type but does not add a property to Sub2, which @babel/typescript inits to undefined.

Body:
So I ran in to an issue where after a constructor was run the values assigned to a field in a class were over written with undefined.

It was related to this issue https://github.com/babel/babel/issues/9105 which references https://github.com/tc39/proposal-class-fields

The repro code is below.

I sort of understand some of the reasoning behind why this was chosen, and people who are far more familiar with javascript and the nuances of choices have argued this extensively, so I assume their choice was a better one than I could make.

But this seems really horrible and leads to code that looks like it should work, and if you debug it everything seems to work until the constructor finishes then everything is undefined. So my question is what is the correct way to properly handle this kind of scenario? You can work around this by doing this myField: string = this.myField, but that code is confusing as hell to someone who doesn't understand everything that's happening, and most people would remove it as clearly useless.

I'm trying to figure out what the idiomatic code is to assign fields in a constructor and everything I've come up with so far looks horrible and seems like an anti-pattern.

class Base {
    constructor(dto?){
        if(dto){
            this.updateFromDTO(dto);
        }
    }

    updateFromDTO(dto) : this{
        return this;
    }
}

class Extends extends Base {
    myField: string;

    updateFromDTO(dto) {
        super.updateFromDTO(dto);
        console.log('I was called');
        this.myField = "weee";
        console.log(this.myField);
        return this;
    }
}

console.log(new Extends("123"));//logs 'I was called', 'weee', then the extends object which has myField as undefined.

Babel config to get this behavior

const DEVELOPMENT = 'production' !== process.env.NODE_ENV

module.exports = {
    presets: [
        ["@babel/preset-env", {useBuiltIns: "entry"}],
        "@babel/preset-react",
        "@babel/typescript"
    ],
    plugins: [
        "@babel/plugin-proposal-class-properties",
        "@babel/plugin-proposal-export-default-from",
        "@babel/plugin-syntax-dynamic-import",
        ["@babel/plugin-transform-runtime", {"regenerator": true}],
        "@babel/plugin-transform-classes",
    ],
}

Body:
A workaround to https://github.com/babel/babel/issues/9105 that works both with tsc and babel is declaration merging.

in your case:

  class Base {
    constructor(dto?: any) {
      if (dto) {
        this.updateFromDTO(dto);
      }
    }

    updateFromDTO(dto: any): this {
      return this;
    }
  }

  // using declaration merging
  interface Extends {
    myField: string;
  }
  class Extends extends Base {
    updateFromDTO(dto: any) {
      super.updateFromDTO(dto);
      console.log("I was called");
      this.myField = "weee";
      console.log(this.myField);
      return this;
    }
  }

in a simpler example:

  interface A {}
  interface B {}

  class Base {
    prop: A | B | null = null;
  }

  class Sub1 extends Base {
    prop!: A | null; // type narrowed
  }

  // using declaration merging
  interface Sub2 {
    prop: A | null; // type narrowed
  }
  class Sub2 extends Base {
  }
  console.log("without declaration merging");
  console.log(`${new Sub1().prop}`); // tsc: null, babel: undefined
  console.log("with declaration merging");
  console.log(`${new Sub2().prop}`); // tsc: null, babel: null

The declaration merging here makes typecript aware of the narrowed type but does not add a property to Sub2, which @babel/typescript inits to undefined.


来源: stackexchange

问:
What is the use case of Styled-Components' .attrs() function?
I came across the .attrs() function in styled components, but I do not understand what it does, or what it does differently?

I tried to understand the example in their docs, but as far as I am concerned, I can do the exact same thing without the attrs() function.

Could somebody please explain this to me or give a simple example?

答:
The goal of .attrs is so it can be passed down from your props.
So you can use props inside your styled, and you can create placeholders, or change colors depending of the props etc...

For example :

```<code>const InputText = styled.input.attrs({
  type: 'text',
  placeholder: props => props.placeholder || 'Please fill',
})`
  padding: 6px 12px;
`;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The goal of .attrs is so it can be passed down from your props.
So you can use props inside your styled, and you can create placeholders, or change colors depending of the props etc...

For example :

const InputText = styled.input.attrs({
  type: 'text',
  placeholder: props => props.placeholder || 'Please fill',
})`
  padding: 6px 12px;
`;


问:
Performance difference between Insert and Insert Where Not Exists
I know its better to use INSERT WHERE NOT EXISTS than INSERT as it leads to duplicated records or unique key violation issues.
But with respect to performance, will it create any big difference ?

INSERT WHERE NOT EXISTS will internally triggers extra SELECT statement to check the record is existing or not. In case of large tables, which is recommended to use INSERT vs INSERT WHERE NOT EXITS ?
And someone pls explain cost of execution difference between the both.

答:
INSERT will check inserted data against any existing schema constraints, PK, FK, Unique Indexes, not nulls and any other custom constraints - whatever the table schema demands. If those checks are ok, the row will be inserted and loop on to the next row.

INSERT WHERE NOT EXISTS, prior to the above check, will check data of all columns of the row against data of all rows of the table. Even if 1 column is different it is ok and then it will move on exactly as INSERT above.

The performance impact mostly depends:
1. number of existing rows at the table
2. size of row

So as the table gets larger followed by larger row size the difference grows.


问:
How to keep sources locally when using 'Linux development with C++' in VisualStudio?
I have some sources that I intend to compile/debug for Windows/Linux and other platforms in the future.

So far it runs on Windows so I installed the 'Linux development with C++' package in VisualStudio to compile/debug it for Linux.

I tried a small example that worked but it uploads the sources prior to compilation and that is not what I want.

I would like to compile the sources locally on my Windows PC (using LLVM) instead of having VisualStudio copying source files to a linux vm/server for remote compiling.

I prefer having the sources only in one 'secured' location, and keeping everything locally like the compiler(s) and the linux system file headers.  So my main reasons for not uploading the sources is security and also source control.

So VisualStudio would compile locally (using LLVM) and then upload the executable on the linux vm/server and run it for a debugging.  Or if the executable is already present or running, it could just launch it or attach to the process for a remote debugging session.

I am not sure if this is possible. All the examples I saw assumed that the sources were on the linux target.

答:
That's not going to work. The Linux VM is not just for running/debugging, but also for building — technically you could cross-compile but it's far more complicated and the feature designers have opted not to do that.

It is possible to turn off the copying of sources, but only if you're already copying/syncing them by other means:

The Copy Sources property page allows you to specify whether to copy sources to the remote Linux system. You may not want to copy sources if you are working with a share or are managing your own synchronization through other means.

If you cannot secure the VM or the path between it and your primary development environment, you should switch to a fully enclosed, Linux-based development environment.


问:
greater/less than signs are not escaped
i am trying to escape strings in server side (Node.js & Express.js) which contains greater/less than signs (<, >) and i use this code on server side

```<code>socket.on('message', function(data) {
   data.message = data.message.replace(/\</g,"<")   //for <
   data.message = data.message.replace(/\>/g,">")   //for >
   io.in(socket.current_room).emit('message',{message :data.message, id: socket.id});
});
</code>```

and on client side (inside socket.on('message') function)

```<code>output.innerHTML += `<div class="mymessage-container"><div class="mymessage"><p class="me">` + message + '</p></div></div>'
</code>```

it replaces the signs but it displays them as replaced, for example: user send message: <hello>, message will displayeed as <hello>.
How can i fix it? Thank you!

答:
The reason you are getting <hello> is because of data.message.replace the second argument you passed is the string that will take place for the one that was found.

You can find here an explanation on what replace does.

If you want it blank you can do this data.message = data.message.replace(/\</g,"").

Sidenote: You don't need to add the backslash before < or > because is not a special character. This works fine for me data.message.replace(/</g,"").

Title: greater/less than signs are not escaped

Body:
i am trying to escape strings in server side (Node.js & Express.js) which contains greater/less than signs (<, >) and i use this code on server side

socket.on('message', function(data) {
   data.message = data.message.replace(/\</g,"<")   //for <
   data.message = data.message.replace(/\>/g,">")   //for >
   io.in(socket.current_room).emit('message',{message :data.message, id: socket.id});
});

and on client side (inside socket.on('message') function)

output.innerHTML += `<div class="mymessage-container"><div class="mymessage"><p class="me">` + message + '

'

it replaces the signs but it displays them as replaced, for example: user send message: <hello>, message will displayeed as <hello>.
How can i fix it? Thank you!

Body:
The reason you are getting &lt;hello&gt; is because of data.message.replace the second argument you passed is the string that will take place for the one that was found.

You can find here an explanation on what replace does.

If you want it blank you can do this data.message = data.message.replace(/\</g,"").

Sidenote: You don't need to add the backslash before < or > because is not a special character. This works fine for me data.message.replace(/</g,"").


问:
Evaluation of condition failed. Rule item ID: Unknown, condition item ID: Unknown - Operation not valid due to the current state of the object
I'm reviewing the Sitecore logs in my site and I'm getting a huge number of the following error:

ERROR Evaluation of condition failed. Rule item ID: Unknown, condition item ID: Unknown

Exception: System.InvalidOperationException

Message: Operation is not valid due to the current state of the object.

Source: Sitecore.ExperienceAnalytics
     at Sitecore.ExperienceAnalytics.Aggregation.Rules.AggregationAdaptor.HistoricalVisitContextBase.GetPages()
     at Sitecore.Analytics.Rules.Conditions.HasVisitedPageCondition1.Execute(T ruleContext)
     at Sitecore.Rules.Conditions.WhenCondition1.Evaluate(T ruleContext.......

In the past week, this error has occurred >10,500 times

I don't know what to do to figure out what is causing the error or to resolve it. I don't know if it's affecting site performance or not, but I'd like to resolve this issue so I don't have >10k errors happening each week.

答:
This helped me solve the issue: https://sitecoreart.martinrayenglish.com/2017/10/sitecore-xdb-mechanics-guide-to.html

The most common cause of the error is due to old tests that are still part of the content item's configuration, that are either not stopped correctly, inactive or have been removed.

Fixing the Issue
The fix is to remove the bad/old test references from the item in question's Final Renderings XML field.

-Determine what item is throwing the testing exception.
-Enable raw values and standard fields in the “View” section of the “View” tab.
-Copy the Final Renderings XML value of the item and format it so that it is easy to read. This site does a nice job: https://www.freeformatter.com/xml-formatter.html
-Paste you’re the XML into Visual Studio or another editor.
-Locate the attributes in the XML that have a s:pt and remove the attributes.
-Copy and paste the updated XML back into the item's Final Renderings field.
-Save and publish.

After this, the errors will stop appearing in your logs. You will however need to launch your test again.


问:
How to handle null value in JSON in SWIFT
I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:

```<code>struct UpdateNicknameMessage: Codable {
 let id: Int
 let nickname: String
 let email: String
}

struct UpdateNickname: Codable {
 var Status: Int
 var Result: String
 var Message: UpdateNicknameMessage

enum CodingKeys: String, CodingKey {
    case Status = "Status"
    case Result = "Result"
    case Message = "Message"
}

init?(from jsonObject: AnyObject) {
    guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
        let Result1: String = jsonObject.object(forKey: "Result") as? String,
        let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
        else { return nil }

    Status = Status1
    Result = Result1
    Message = Message1
  }
}
</code>```

and JSON looks like this:

```<code>{"Message": {
    email = "123@123.com";
    id = 56;
    nickname = testNickname;
},
 "Status": 200,
 "Result": success}
</code>```

And this is my code for decoding JSON in swift. I use try catch to handle my error.

```<code>            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(UpdateNickname.self, from: data)
                let serverStatus = model.Status

                if serverStatus == 200 {
                     //EVERYTHING IS FINE
                } else {
                     //server not working
                }
            } catch {
               //cant convert JSON into struct
               print(error.localizedDescription)
            }
</code>```

so my variable Message can return null if something goes wrong with the server.

```<code>{"Message": null,
 "Status": 400,
 "Result": problem}
</code>```

When i try to decode JSON when Message is null i get an error

The data couldn’t be read because it is missing.

How can i fix this problem and handle null value?

答:
You can handle it making as optional. Please refer below model class.

```<code>struct UpdateNicknameMessage : Codable {
    let email : String?
    let id : Int?
    let nickname : String?

    enum CodingKeys: String, CodingKey {
        case email = "email"
        case id = "id"
        case nickname = "nickname"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        email = try values.decodeIfPresent(String.self, forKey: .email)
        id = try values.decodeIfPresent(Int.self, forKey: .id)
        nickname = try values.decodeIfPresent(String.self, forKey: .nickname)
    }

}

struct UpdateNickname : Codable {
    let message : UpdateNicknameMessage?
    let status : Int?
    let result : String?

    enum CodingKeys: String, CodingKey {

        case message = "Message"
        case status = "Status"
        case result = "Result"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        message = try values.decodeIfPresent(Message.self, forKey: .Message)
        status = try values.decodeIfPresent(Int.self, forKey: .Status)
        result = try values.decodeIfPresent(String.self, forKey: .Result)
    }

}
</code>```

I suggest to use json4swift to create model class from JSON response.

Update:

I think you need to more clear about the usage codable protocol first. Consider, Your server is giving Internal server error due to any XYZ reason. I think your approach is not worked for it.

I am sure it will give a same error.

The data couldn’t be read because it is missing.

So my first question is

How you could manage in such type of situation?

That's it from my end!!

Happy codding!!

Body:
I have a problem with JSON decoding. I have UpdateNickname and UpdateNicknameMessage structs and variable Message inside UpdateNickname could be a null. I got an error whenever it is a null. I want to handle this problem. Here is my struct:

struct UpdateNicknameMessage: Codable {
 let id: Int
 let nickname: String
 let email: String
}

struct UpdateNickname: Codable {
 var Status: Int
 var Result: String
 var Message: UpdateNicknameMessage

enum CodingKeys: String, CodingKey {
    case Status = "Status"
    case Result = "Result"
    case Message = "Message"
}

init?(from jsonObject: AnyObject) {
    guard let Status1: Int = jsonObject.object(forKey: "Status") as? Int,
        let Result1: String = jsonObject.object(forKey: "Result") as? String,
        let Message1: UpdateNicknameMessage = jsonObject.object(forKey: "Message") as? UpdateNicknameMessage
        else { return nil }

    Status = Status1
    Result = Result1
    Message = Message1
  }
}

and JSON looks like this:

{"Message": {
    email = "123@123.com";
    id = 56;
    nickname = testNickname;
},
 "Status": 200,
 "Result": success}

And this is my code for decoding JSON in swift. I use try catch to handle my error.

            let decoder = JSONDecoder()
            do {
                let model = try decoder.decode(UpdateNickname.self, from: data)
                let serverStatus = model.Status

                if serverStatus == 200 {
                     //EVERYTHING IS FINE
                } else {
                     //server not working
                }
            } catch {
               //cant convert JSON into struct
               print(error.localizedDescription)
            }

so my variable Message can return null if something goes wrong with the server.

{"Message": null,
 "Status": 400,
 "Result": problem}

When i try to decode JSON when Message is null i get an error

The data couldn’t be read because it is missing.

How can i fix this problem and handle null value?

Body:
You can handle it making as optional. Please refer below model class.

struct UpdateNicknameMessage : Codable {
    let email : String?
    let id : Int?
    let nickname : String?

    enum CodingKeys: String, CodingKey {
        case email = "email"
        case id = "id"
        case nickname = "nickname"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        email = try values.decodeIfPresent(String.self, forKey: .email)
        id = try values.decodeIfPresent(Int.self, forKey: .id)
        nickname = try values.decodeIfPresent(String.self, forKey: .nickname)
    }

}

struct UpdateNickname : Codable {
    let message : UpdateNicknameMessage?
    let status : Int?
    let result : String?

    enum CodingKeys: String, CodingKey {

        case message = "Message"
        case status = "Status"
        case result = "Result"
    }

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        message = try values.decodeIfPresent(Message.self, forKey: .Message)
        status = try values.decodeIfPresent(Int.self, forKey: .Status)
        result = try values.decodeIfPresent(String.self, forKey: .Result)
    }

}

I suggest to use json4swift to create model class from JSON response.

Update:

I think you need to more clear about the usage codable protocol first. Consider, Your server is giving Internal server error due to any XYZ reason. I think your approach is not worked for it.

I am sure it will give a same error.

The data couldn’t be read because it is missing.

So my first question is

How you could manage in such type of situation?

That's it from my end!!

Happy codding!!


问:
Cannot find module @ionic/angular (ionic 4) from test-file
I'm trying to use jest to test an Ionic app. My jest configuration is:

```<code>preset: 'jest-preset-angular',
setupTestFrameworkScriptFile: '<rootDir>/src/setupJest.ts',
transformIgnorePatterns: ['node_modules/(?!@ngrx|@ionic-native|@ionic)'],
globals: {
  __TRANSFORM_HTML__: true,
},
</code>```

The setupJest.js file has import 'jest-preset-angular';.

I have a very simple test where I use TestBed to create an instance of the App component and check that it's truthy. In this code I have import { Platform } from '@ionic/angular';.

Jest errors with:

Cannot find module '@ionic/angular' from 'app.component.test.ts'

If I just remove the import { Platform } from '@ionic/angular' from the test file, Jest gives me the same error from the component file:

Cannot find module '@ionic/angular' from 'app.component.ts'

Using ionic serve / building works, jest is just giving me this error that it can't import X from Y.

How can I get jest to import from @ionic files?

答:
```<code>npm install --save rxjs-compat or do
npm update
</code>```

Body:
I'm trying to use jest to test an Ionic app. My jest configuration is:

preset: 'jest-preset-angular',
setupTestFrameworkScriptFile: '<rootDir>/src/setupJest.ts',
transformIgnorePatterns: ['node_modules/(?!@ngrx|@ionic-native|@ionic)'],
globals: {
  __TRANSFORM_HTML__: true,
},

The setupJest.js file has import 'jest-preset-angular';.

I have a very simple test where I use TestBed to create an instance of the App component and check that it's truthy. In this code I have import { Platform } from '@ionic/angular';.

Jest errors with:

Cannot find module '@ionic/angular' from 'app.component.test.ts'

If I just remove the import { Platform } from '@ionic/angular' from the test file, Jest gives me the same error from the component file:

Cannot find module '@ionic/angular' from 'app.component.ts'

Using ionic serve / building works, jest is just giving me this error that it can't import X from Y.

How can I get jest to import from @ionic files?


问:
How to use the output from sed command as a string and use that string in the grep command?
I have a file with only one string per row, "File1", and a file that has two strings per row, "File2". I wan't go through File1 and check for every row/string in how many of the rows in File2 it appear.

I would like to use something like this:

```<code>grep '{sed -n 1p File1}' File2
</code>```

But it doesn't work. Why and what should I do?

//Thanks!

答:
It seems to me that you're asking two completely different questions: one in the title and one in the body. I'll try to summarize them and answer both.

First question:

How to use the output from sed command as a string and use that string in the grep command?

First answer:

The unix way is to pipe a command's output as input to another program. If you instead want to use the first program's output as e.g. a parameter to the subsequent command (not as its input), there's a handy program that allows you to do just that: xargs.

Example of piping the sed output as input to grep:

```<code>sed -n 1p File1 | grep 'needle'
</code>```

Example of using the sed output as a search string for grep:

```<code>sed -n 1p File1 | xargs -I{} grep {} File2
</code>```

Second question:

I have a file with only one string per row, "File1", and a file that has two strings per row, "File2". I wan't go through File1 and check for every row/string in how many of the rows in File2 it appear.

Second answer:

```<code>awk 'NR==FNR{!a[$0]++;next} $1 in a{a[$1]++} END{for(i in a){print i" "a[i]-1}}' File1 File2
</code>```

Test files:

```<code>==> File1 <==
one
two
three

==> File2 <==
one apple
two bananas
two strawberries
three kiwis
three pomegrenades
three lychees
</code>```

Test run output:

```<code>three 3
two 2
one 1
</code>```

That's only if you mean the string from File1 to appear as the first column of File2. For a more general approach, where you want to count every File2 row containing the string from File1:

```<code>awk 'NR==FNR{!a[$0]++;next} {for(i in a){if(match($0,i)){a[i]++}}} END{for(i in a){print i" "a[i]-1}}' File1 File2
</code>```

Test files:

```<code>==> File1 <==
one
two
three

==> File2 <==
one one
two one
two two
three three
three two
three one
</code>```

Test run output:

```<code>three 3
two 3
one 3
</code>```

Body:
I have a file with only one string per row, "File1", and a file that has two strings per row, "File2". I wan't go through File1 and check for every row/string in how many of the rows in File2 it appear.

I would like to use something like this:

grep '{sed -n 1p File1}' File2

But it doesn't work. Why and what should I do?

//Thanks!

Body:
It seems to me that you're asking two completely different questions: one in the title and one in the body. I'll try to summarize them and answer both.

First question:

How to use the output from sed command as a string and use that string in the grep command?

First answer:

The unix way is to pipe a command's output as input to another program. If you instead want to use the first program's output as e.g. a parameter to the subsequent command (not as its input), there's a handy program that allows you to do just that: xargs.

Example of piping the sed output as input to grep:

sed -n 1p File1 | grep 'needle'

Example of using the sed output as a search string for grep:

sed -n 1p File1 | xargs -I{} grep {} File2

Second question:

I have a file with only one string per row, "File1", and a file that has two strings per row, "File2". I wan't go through File1 and check for every row/string in how many of the rows in File2 it appear.

Second answer:

awk 'NR==FNR{!a[$0]++;next} $1 in a{a[$1]++} END{for(i in a){print i" "a[i]-1}}' File1 File2

Test files:

==> File1 <==
one
two
three

==> File2 <==
one apple
two bananas
two strawberries
three kiwis
three pomegrenades
three lychees

Test run output:

three 3
two 2
one 1

That's only if you mean the string from File1 to appear as the first column of File2. For a more general approach, where you want to count every File2 row containing the string from File1:

awk 'NR==FNR{!a[$0]++;next} {for(i in a){if(match($0,i)){a[i]++}}} END{for(i in a){print i" "a[i]-1}}' File1 File2

Test files:

==> File1 <==
one
two
three

==> File2 <==
one one
two one
two two
three three
three two
three one

Test run output:

three 3
two 3
one 3


问:
Add a computed column in Datatable based on string columns
I import data from a CSV file into a datatable.

Existing vendors send period as '201901' in one column.
A new vendor sends period as 2 columns like year '2019' and month 'JAN'.

I want to combine the 2 columns into '201901' so that the rest of the code logic works as earlier.

When I looked at the documentation for Datatable.Columns.Add , I see all the examples are just numeric expressions only, nothing related to string or dates in the column expressions.

Here is my Code..
These are from CSV file so when imported to datatable, these columns have 2019 and JAN data.

```<code>DT.Columns.Add("MAT_YEAR", typeof(string));

DT.Columns.Add("MAT_MONTH", typeof(string));
</code>```

I want to get the computed value based on above 2 columns

```<code>DT.Columns.Add("MONTHNUM", typeof(int),"DateTime.ParseExact(MAT_MONTH,\"MMM\",null).Month");

DT.Columns.Add("MAT_PERIOD", typeof(string), "MAT_YEAR + Convert.ToString(MONTHNUM)");
</code>```

I am getting error on DateTime.Parse

How can I create computed columns in Datatable based on string or dates?

答:
Perhaps try the following.

```<code>DT.Columns.Add("MAT_YEAR", typeof(string));
DT.Columns.Add("MAT_MONTH", typeof(string));

DT.Columns.Add("MONTHNUM", typeof(string),"DateTime.ParseExact(\"MAT_MONTH + \"01 2000\", \"MMM dd yyyy\", CultureInfo.InvariantCulture).Month.ToString(\"00\");
DT.Columns.Add("MAT_PERIOD", typeof(string), "MAT_YEAR + MONTHNUM");
</code>```

All credit to Charles May, completely correct

Body:
I import data from a CSV file into a datatable.

Existing vendors send period as '201901' in one column.
A new vendor sends period as 2 columns like year '2019' and month 'JAN'.

I want to combine the 2 columns into '201901' so that the rest of the code logic works as earlier.

When I looked at the documentation for Datatable.Columns.Add , I see all the examples are just numeric expressions only, nothing related to string or dates in the column expressions.

Here is my Code..
These are from CSV file so when imported to datatable, these columns have 2019 and JAN data.

DT.Columns.Add("MAT_YEAR", typeof(string));

DT.Columns.Add("MAT_MONTH", typeof(string));

I want to get the computed value based on above 2 columns

DT.Columns.Add("MONTHNUM", typeof(int),"DateTime.ParseExact(MAT_MONTH,\"MMM\",null).Month");

DT.Columns.Add("MAT_PERIOD", typeof(string), "MAT_YEAR + Convert.ToString(MONTHNUM)");

I am getting error on DateTime.Parse

How can I create computed columns in Datatable based on string or dates?

Body:
Perhaps try the following.

DT.Columns.Add("MAT_YEAR", typeof(string));
DT.Columns.Add("MAT_MONTH", typeof(string));

DT.Columns.Add("MONTHNUM", typeof(string),"DateTime.ParseExact(\"MAT_MONTH + \"01 2000\", \"MMM dd yyyy\", CultureInfo.InvariantCulture).Month.ToString(\"00\");
DT.Columns.Add("MAT_PERIOD", typeof(string), "MAT_YEAR + MONTHNUM");

All credit to Charles May, completely correct


问:
difference among "Density-compatibility" and "Size-compatibility" android
Can someone explaing the difference among "Density-compatibility" and "Size-compatibility" please?

Thanks

答: I think you will find this overview of Screen information to be useful.</p>

ContentLicense: CC BY-SA 3.0


问:
How to capitalize the first letter of a String in Java?
I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

```<code>String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));
</code>```

which led to these compiler errors:

Type mismatch: cannot convert from InputStreamReader to BufferedReader

Cannot invoke toUppercase() on the primitive type char

答:
If Input is UpperCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();

If Input is LowerCase ,then Use following :

str.substring(0, 1).toUpperCase() + str.substring(1);

Body:
I am using Java to get a String input from the user. I am trying to make the first letter of this input capitalized.

I tried this:

String name;

BufferedReader br = new InputStreamReader(System.in);

String s1 = name.charAt(0).toUppercase());

System.out.println(s1 + name.substring(1));

which led to these compiler errors:

Type mismatch: cannot convert from InputStreamReader to BufferedReader

Cannot invoke toUppercase() on the primitive type char


问:
create two differents variables from the same array
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working : </p>

```<code>    var letters = ['b', 'c', 'a']; // datas

    const lettersUnsorted = letters;        // i want the array like the var "letters"
    const letterSorted = letters.sort();    // i want the array like the var "letters" but sorted

    console.log(letterSorted);    // OK => returns: ["a", "b", "c"]
    console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']
</code>```

答:
you can use concat also.

```<code>var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterssorted = ([].concat(letters)).sort();
</code>```

Body:
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working :

    var letters = ['b', 'c', 'a']; // datas

    const lettersUnsorted = letters;        // i want the array like the var "letters"
    const letterSorted = letters.sort();    // i want the array like the var "letters" but sorted

    console.log(letterSorted);    // OK => returns: ["a", "b", "c"]
    console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']

Body:
you can use concat also.

var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterssorted = ([].concat(letters)).sort();


问:
Laravel Auth return to index
Can I redirect to the previous page someone if not logged in? Also, is it possible to create a hierarchy system for users?

I tried this:

```<code>if(!(Auth::check())) {
            header("Location: {{ route('cooperado.index') }});
}
</code>```

But i not even got an error message, just doesn't work. I'm starting at laravel so it's kind of hard to fully understand how it works.

答:
```<code>if(!(Auth::check())) {
           return redirect()->route('cooperado.index');
}
</code>```

You mention in your question also wants to return previous page then use following but i'm not recommended this because if your first login effort fails then login failed' page becomes your previous page and second login effort succeeds then you are redirected to login page again because it's your previous page.

```<code>return Redirect::to(URL::previous());
</code>```

Title: Laravel Auth return to index

Body:
Can I redirect to the previous page someone if not logged in? Also, is it possible to create a hierarchy system for users?

I tried this:

if(!(Auth::check())) {
            header("Location: {{ route('cooperado.index') }});
}

But i not even got an error message, just doesn't work. I'm starting at laravel so it's kind of hard to fully understand how it works.

Body:
if(!(Auth::check())) {
           return redirect()->route('cooperado.index');
}

You mention in your question also wants to return previous page then use following but i'm not recommended this because if your first login effort fails then login failed' page becomes your previous page and second login effort succeeds then you are redirected to login page again because it's your previous page.

return Redirect::to(URL::previous());


问:
Avoid dynamically injecting the same script multiple times when using chrome.tabs.executeScript(...)
I'm building a Google Chrome extension.  The basic setup is I have a Browser action button that injects jQuery and another bit of JavaScript into the active tab when it is clicked to do it's thing.

This is my first Chrome extension, but it seems like if the user clicks the button to take action a second time the scripts will be re-injected.  This is a problem because the main pages this is going to work with are all AJAX, so the page content changes significantly but the actual page URL never changes.

Is this a legitimate concern, or am I over thinking it and is there a simple way to prevent the scripts from being injected multiple times into the same page?  Should I perhaps be specifying these as content scripts instead?

答:
I believe the better way might be to do it on extension level. If you include third party libraries, then you would be re-including them as well, and never know what happens then.

contentScript.js

```<code>(function () {

  var Sz = Sizzle;

  //listen for events from the extension
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

    if (!request._extension || request._extension !== 'my-extension-name') {
      console.log('Non extension request');
      return;
    }

    var channel = (request._channel) ? request._channel : false;

    if (channel === 'is-loaded') {

      sendResponse({isLoaded: true});
      return true;

    } else if (channel === 'example') {
      //do stuff
    }

    return true;

  });

  //other code goes here

});
</code>```

Background.js

```<code>var util = {};

util.sendMessage = function (data, cb) {

  chrome.tabs.query({active: true, currentWindow: true}, tabsQuery_cb);

  data['_extension'] = 'my-extension-name';

  function tabsQuery_cb(tabs) {

    var tab = tabs[0];

    console.log('sending message to ' + tab.id);
    console.log(data);

    //let the content script know to open the ad page
    chrome.tabs.sendMessage(tabs[0].id, data, cb);

  }

}

util.loadContentScript = function(cb) {

  var attempts = 0;

  checkIfLoaded();

   //checks if ContentScript is loaded by sending a message to the current
  function checkIfLoaded() {

    util.sendMessage({ _channel: 'is-loaded'}, sendMessage_cb);

  }

  function sendMessage_cb(response) {

    console.log('isLoadedCheck')
    console.log(response);

    if (response && response.isLoaded === true) {
      console.log('Script already loaded!');
      cb(true);
    } else {
      console.log('loading scripts');
      loadScripts();
    }

  }

  function loadScripts() {

    attempts++;
    console.log('loadScripts, attempt no. ' + attempts);

    if (attempts > 1) {
      console.log('Script couldnt be loaded');
      return cb(false);
    }

    var scripts = [
      "assets/sizzle-2.3.4.min.js",
      "app/contentScript.js"
    ];

    var i = -1;

    scriptLoaded();

    function scriptLoaded() {

      i++;

      if (i > scripts.length) {
        //all scripts have loaded at this point, check if replies with message
        checkIfLoaded();
      } else {
        console.log('Loading script ' + scripts[i]);
        chrome.tabs.executeScript(null, { file: scripts[i] }, scriptLoaded);
      }

    }

  }

}
</code>```

Of course including third party libraries seems like a bad practice anyway, because it can skew with website's scripts. But what other way is there. Perhaps you could go to the extreme, and create a bootstrap content script which would check for presence of libraries and tell the extension script what exactly needs to be included. That's what I would consider on a more serious project.

Body:
I believe the better way might be to do it on extension level. If you include third party libraries, then you would be re-including them as well, and never know what happens then.

contentScript.js

(function () {

  var Sz = Sizzle;

  //listen for events from the extension
  chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {

    if (!request._extension || request._extension !== 'my-extension-name') {
      console.log('Non extension request');
      return;
    }

    var channel = (request._channel) ? request._channel : false;

    if (channel === 'is-loaded') {

      sendResponse({isLoaded: true});
      return true;

    } else if (channel === 'example') {
      //do stuff
    }

    return true;

  });

  //other code goes here

});

Background.js

var util = {};

util.sendMessage = function (data, cb) {

  chrome.tabs.query({active: true, currentWindow: true}, tabsQuery_cb);

  data['_extension'] = 'my-extension-name';

  function tabsQuery_cb(tabs) {

    var tab = tabs[0];

    console.log('sending message to ' + tab.id);
    console.log(data);

    //let the content script know to open the ad page
    chrome.tabs.sendMessage(tabs[0].id, data, cb);

  }

}

util.loadContentScript = function(cb) {

  var attempts = 0;

  checkIfLoaded();

   //checks if ContentScript is loaded by sending a message to the current
  function checkIfLoaded() {

    util.sendMessage({ _channel: 'is-loaded'}, sendMessage_cb);

  }

  function sendMessage_cb(response) {

    console.log('isLoadedCheck')
    console.log(response);

    if (response && response.isLoaded === true) {
      console.log('Script already loaded!');
      cb(true);
    } else {
      console.log('loading scripts');
      loadScripts();
    }

  }

  function loadScripts() {

    attempts++;
    console.log('loadScripts, attempt no. ' + attempts);

    if (attempts > 1) {
      console.log('Script couldnt be loaded');
      return cb(false);
    }

    var scripts = [
      "assets/sizzle-2.3.4.min.js",
      "app/contentScript.js"
    ];

    var i = -1;

    scriptLoaded();

    function scriptLoaded() {

      i++;

      if (i > scripts.length) {
        //all scripts have loaded at this point, check if replies with message
        checkIfLoaded();
      } else {
        console.log('Loading script ' + scripts[i]);
        chrome.tabs.executeScript(null, { file: scripts[i] }, scriptLoaded);
      }

    }

  }

}

Of course including third party libraries seems like a bad practice anyway, because it can skew with website's scripts. But what other way is there. Perhaps you could go to the extreme, and create a bootstrap content script which would check for presence of libraries and tell the extension script what exactly needs to be included. That's what I would consider on a more serious project.


问:
Show Payment options showing blank loading screen
I have initiated Stripe Payment Context on my view controller as below

```<code>customerContext = STPCustomerContext(keyProvider:
StripeClient.shared)
paymentContext = STPPaymentContext(customerContext:
customerContext!)
</code>```

I have set the publishable keys in the app delegate
I am trying to show the payment options view controller as below

```<code>paymentContext?.pushPaymentOptionsViewController()
</code>```

The problem is the presented view controller is just a blank view controller titled "Loading"
It stays loading forever

答: So the customer ID was blank. Added it and it loaded properly </p>

Body:
I have initiated Stripe Payment Context on my view controller as below

customerContext = STPCustomerContext(keyProvider:
StripeClient.shared)
paymentContext = STPPaymentContext(customerContext:
customerContext!)

I have set the publishable keys in the app delegate
I am trying to show the payment options view controller as below

paymentContext?.pushPaymentOptionsViewController()

The problem is the presented view controller is just a blank view controller titled "Loading"
It stays loading forever


问:
How to run commands in parallel in bash?
This has been asked before and there are a lot of answers but my needs are bit more specific:

The processes I need to run are all long-running processes that won't end (normally).

I don't want to just run them on background since I need to see their output.

If any of the processes exits I want the rest to be automatically killed as well.

If I use Ctrl+C or other signal on the main command used to run them, I want to kill all the processes.

For example using & + wait does not satisfy the last point. GNU parallel seems quite complicated and is possibly able to do this but I can't find a good example how to use it.

答:
After fiddling with GNU parallel for a while this seems to work as I need.

Added the scripts I need to run to my Makefile so that that are available as make consume, make project and make run.

Now I run them in parallel like this:

```<code>parallel --ungroup --halt now,success=1,fail=1 make ::: consume project run
</code>```

With --ungroup I can see the output and killing seems to work as expected too. The only difference from my initial post is that when one of the program ends the others are not killed. But that doesn't really matter.

Body:
After fiddling with GNU parallel for a while this seems to work as I need.

Added the scripts I need to run to my Makefile so that that are available as make consume, make project and make run.

Now I run them in parallel like this:

parallel --ungroup --halt now,success=1,fail=1 make ::: consume project run

With --ungroup I can see the output and killing seems to work as expected too. The only difference from my initial post is that when one of the program ends the others are not killed. But that doesn't really matter.


问:
UnrecognizedClientException while testing API Gateway with integration type Kinesis
I have created an API using API gateway with integration type 'Kinesis'. I am trying to access ListStreams method. I have created a role with AmazonKinesisFullAccess policy and trusted identity is set to apigateway.amazonaws.com. I have provided arn to the execution role field but while testing this API using console, getting following error:

```<code><UnrecognizedClientException>
  <Message>The security token included in the request is invalid</Message>
</UnrecognizedClientException>
</code>```

Thanks

答:
This was a classic example of wrong/incomplete exception detail.

My fault was that I was looking for kinesis in a wrong region. But rather than returning some error like "Resource not found", api gateway returned "Invalid security token".

Body:
I have created an API using API gateway with integration type 'Kinesis'. I am trying to access ListStreams method. I have created a role with AmazonKinesisFullAccess policy and trusted identity is set to apigateway.amazonaws.com. I have provided arn to the execution role field but while testing this API using console, getting following error:

<UnrecognizedClientException>
  <Message>The security token included in the request is invalid</Message>
</UnrecognizedClientException>

Thanks


问:
Can I filter the export of telemetry from app center to application insights?
For a particular Android app in App Center, we are collecting all events and exception. Now i want to export the app telemetry to Azure Application Insights but separately for exceptions and separately for all other events.

Is there some way to have separate exports on the basis of defined events?

If all the data went into a single instance of Application Insights, then is it possible to make 2 separate storage as blobs from single Application Insights instance?

答:
I would suggest this approach:

Export all telemetry from App Center to Azure Application Insights first using the procedure detailed here, as George suggested above.

Set up Continuous Export in Application Insights to then pump your telemetry to Azure Storage.

For Application Insights, data is continuously exported from App Center the moment export is configured along with 2 days of backfilled data. And once continuous export is enabled on your App Insights instance, you will be able to see your raw exported telemetry in a single Storage account auto-categorized into blobs as per the data types selected (Exceptions, Requests, Traces etc.).


问:
Stopping a service after Intent -Android
In my android application, I have an activity called A .From A, I call a background service.In that services onStartCommand I will do some AsyncTask and Provided an Intent to move to another activity called B. Where I am stuck is,

1. How can I stop the service itself after calling the Intent?

EDIT: I tried calling StopSelf(); but it not ending my service.

2. After reaching B the back button should not work. Currently if press backbutton I can still go to Activity A.

My Intent

```<code>Intent dialogIntent = new Intent(UserLoginValidationService.this,SplashScreen.class);
                        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        stopSelf();
                        startActivity(dialogIntent);
</code>```

EDIT: How to call finishAffinity(); in service?

Any help is appreciated.

答:
1. How can I stop the service itself after calling the Intent?

You can stop service using stopSelf().

2. After reaching B the back button should not work. Currently if press backbutton I can still go to Activity A.

If you want to close the application on back button press then you should open at Activity B clearing previous activity.

Body:
In my android application, I have an activity called A .From A, I call a background service.In that services onStartCommand I will do some AsyncTask and Provided an Intent to move to another activity called B. Where I am stuck is,

1. How can I stop the service itself after calling the Intent?

EDIT: I tried calling StopSelf(); but it not ending my service.

2. After reaching B the back button should not work. Currently if press backbutton I can still go to Activity A.

My Intent

Intent dialogIntent = new Intent(UserLoginValidationService.this,SplashScreen.class);
                        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        stopSelf();
                        startActivity(dialogIntent);

EDIT: How to call finishAffinity(); in service?

Any help is appreciated.


问:
What is the purpose of text preceded with @ in comments
I've seen comments that contain @some text in it. This is an example from express.js:

```<code>/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */
</code>```

These @comments are also color coded differently by the Visual Studio Code.

What is the purpose of @ preceded comments?

答:
These are JSDoc comments. They are useful for explaining what a function does, what parameters and types it takes, and what it outputs, when hovering or using a function in your IDE.

For example, in VSCode, this code:

Will produce this tool-tip:

Body:
I've seen comments that contain @some text in it. This is an example from express.js:

/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */

These @comments are also color coded differently by the Visual Studio Code.

What is the purpose of @ preceded comments?


问:
Git changelog: how to get all changes up to a specific tag?
Is there an easy way or command to get all git commits up to a specific tag to generate an automatic changelog for a project? I always tag my git repos with a version number like v0.1.0 and for instance would like all commits up to tag v0.1.0.

I've looked through the docs but don't seem to find a useful option or command for it: http://git-scm.com/docs/git-log (is down at the moment by the way)

For instance:

```<code>$ git log --oneline --decorate
</code>```

Shows the tags next to commits. I'd like the same, but only up to specific tag.

答:
You may use Git Changelog Command Line to do this:</p>

```<code>npx git-changelog-command-line -std -tr v0.1.0 -tec "
# Changelog

Changelog for {{ownerName}} {{repoName}}.

{{#tags}}
## {{name}}
 {{#issues}}
  {{#hasIssue}}
   {{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
   {{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
  {{/hasIssue}}
  {{^hasIssue}}
### {{name}}
  {{/hasIssue}}

  {{#commits}}
**{{{messageTitle}}}**

{{#messageBodyItems}}
 * {{.}}
{{/messageBodyItems}}

[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*

  {{/commits}}

 {{/issues}}
{{/tags}}
"
</code>```

Body:
Is there an easy way or command to get all git commits up to a specific tag to generate an automatic changelog for a project? I always tag my git repos with a version number like v0.1.0 and for instance would like all commits up to tag v0.1.0.

I've looked through the docs but don't seem to find a useful option or command for it: http://git-scm.com/docs/git-log (is down at the moment by the way)

For instance:

$ git log --oneline --decorate

Shows the tags next to commits. I'd like the same, but only up to specific tag.

Body:
You may use Git Changelog Command Line to do this:

npx git-changelog-command-line -std -tr v0.1.0 -tec "
# Changelog

Changelog for {{ownerName}} {{repoName}}.

{{#tags}}
## {{name}}
 {{#issues}}
  {{#hasIssue}}
   {{#hasLink}}
### {{name}} [{{issue}}]({{link}}) {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
   {{^hasLink}}
### {{name}} {{issue}} {{title}} {{#hasIssueType}} *{{issueType}}* {{/hasIssueType}} {{#hasLabels}} {{#labels}} *{{.}}* {{/labels}} {{/hasLabels}}
   {{/hasLink}}
  {{/hasIssue}}
  {{^hasIssue}}
### {{name}}
  {{/hasIssue}}

  {{#commits}}
**{{{messageTitle}}}**

{{#messageBodyItems}}
 * {{.}}
{{/messageBodyItems}}

[{{hash}}](https://github.com/{{ownerName}}/{{repoName}}/commit/{{hash}}) {{authorName}} *{{commitTime}}*

  {{/commits}}

 {{/issues}}
{{/tags}}
"


问:
the maximum limit of items a 'In' clause can handle
what are the limits of data i can pass to a database in a programing language(like php).
suppose i have 1 million records in my database and I have 1 million data in my hand which i want to do a exist checking. if i used a query like

```<code> select id from table where id in (array of 1 million data)
</code>```

what will happen? will this request even reach database?
if it reaches, what are the posibilities ,will it returns a data a better speed than a million querys to db searching id's or a full select data call with  millions of  for loops.

just for curiosity!.

答:
There isn't a specific number, however, the documentation specifies you'll likely to have problems once you have "thousands" of values. IN (Transact-SQL) - Remarks:

Explicitly including an extremely large number of values (many
  thousands of values separated by commas) within the parentheses, in an
  IN clause can consume resources and return errors 8623 or 8632. To
  work around this problem, store the items in the IN list in a table,
  and use a SELECT subquery within an IN clause.

Error 8623:

The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for
  extremely complex queries or queries that reference a very large
  number of tables or partitions. Please simplify the query. If you
  believe you have received this message in error, contact Customer
  Support Services for more information.

Error 8632:

Internal error: An expression services limit has been reached. Please look for potentially complex expressions in your query, and try
  to simplify them.

To quote my comment I made:

If you need to pass a large number of values to a query, I suggest a Table-Type parameter. But if you really need to pass 1M+ values then it sounds like something is wrong with your design. You may even be better off listing the values you don't want.

Edit: To add to my comment, many (including myself) prefer to use EXISTS instead of IN. So instead of a query like:

```<code>FROM YourTable YT
WHERE YT.YourColumn IN (SELECT OT.YourColumn
                        FROM OtherTable OT)
</code>```

You would have the query:

```<code>FROM YourTable YT
WHERE EXISTS (SELECT 1
              FROM OtherTable OT
              WHERE OT.YourColumn = YT.YourColumn)
</code>```

Body:
what are the limits of data i can pass to a database in a programing language(like php).
suppose i have 1 million records in my database and I have 1 million data in my hand which i want to do a exist checking. if i used a query like

 select id from table where id in (array of 1 million data)

what will happen? will this request even reach database?
if it reaches, what are the posibilities ,will it returns a data a better speed than a million querys to db searching id's or a full select data call with  millions of  for loops.

just for curiosity!.

Body:
There isn't a specific number, however, the documentation specifies you'll likely to have problems once you have "thousands" of values. IN (Transact-SQL) - Remarks:

Explicitly including an extremely large number of values (many
  thousands of values separated by commas) within the parentheses, in an
  IN clause can consume resources and return errors 8623 or 8632. To
  work around this problem, store the items in the IN list in a table,
  and use a SELECT subquery within an IN clause.

Error 8623:

The query processor ran out of internal resources and could not produce a query plan. This is a rare event and only expected for
  extremely complex queries or queries that reference a very large
  number of tables or partitions. Please simplify the query. If you
  believe you have received this message in error, contact Customer
  Support Services for more information.

Error 8632:

Internal error: An expression services limit has been reached. Please look for potentially complex expressions in your query, and try
  to simplify them.

To quote my comment I made:

If you need to pass a large number of values to a query, I suggest a Table-Type parameter. But if you really need to pass 1M+ values then it sounds like something is wrong with your design. You may even be better off listing the values you don't want.

Edit: To add to my comment, many (including myself) prefer to use EXISTS instead of IN. So instead of a query like:

FROM YourTable YT
WHERE YT.YourColumn IN (SELECT OT.YourColumn
                        FROM OtherTable OT)

You would have the query:

FROM YourTable YT
WHERE EXISTS (SELECT 1
              FROM OtherTable OT
              WHERE OT.YourColumn = YT.YourColumn)


问:
Invalid URL GoError: invalid URL value in K6 Performance Testing
I am running the API via K6 http.url and getting the below exception but not sure what is being missed in the URL;

```<code>export default function() {
    let url = http.get("http://test.loadimpact.com");
    let res = http.get(url);
    check(res, {
        "status was 200": (r) => r.status == 200,
        "transaction time OK": (r) => r.timings.duration < 200
    });
    sleep(1);
}
</code>```

WARN[0063] Request Failed                                error="Get http://test.loadimpact.com: dial tcp "ip":80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."

ERRO[0063] GoError: invalid URL value '&http.Response{ctx:(*context.valueCtx)(0xc003dfbb00), RemoteIP:"", RemotePort:0, URL:"http://test.loadimpact.com", Status:0, Proto:"", Headers:map[string]string(nil), Cookies:map[string][]*httpext.HTTPCookie(nil), Body:interface {}(nil), Timings:httpext.ResponseTimings{Duration:0, Blocked:0, LookingUp:0, Connecting:0, TLSHandshaking:0, Sending:0, Waiting:0, Receiving:0}, TLSVersion:"", TLSCipherSuite:"", OCSP:netext.OCSP{ProducedAt:0, ThisUpdate:0, NextUpdate:0, RevokedAt:0, RevocationReason:"", Status:""}, Error:"dial tcp "ip":80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.", ErrorCode:1210, Request:httpext.Request{Method:"GET", URL:"http://test.loadimpact.com", Headers:map[string][]string{"User-Agent":[]string{"k6/0.24.0 (https://k6.io/)"}}, Body:"", Cookies:map[string][]*httpext.HTTPRequestCookie{}}, cachedJSON:interface {}(nil), validatedJSON:false}'

答:
You are setting the URL to be the result of the http.get function call, I think you intended to do:

```<code>export default function() {
  let url = "http://test.loadimpact.com";
  let res = http.get(url);
  check(res, {
    "status was 200": (r) => r.status == 200,
        "transaction time OK": (r) => r.timings.duration < 200
    });
    sleep(1);
}
</code>```

Body:
I am running the API via K6 http.url and getting the below exception but not sure what is being missed in the URL;

export default function() {
    let url = http.get("http://test.loadimpact.com");
    let res = http.get(url);
    check(res, {
        "status was 200": (r) => r.status == 200,
        "transaction time OK": (r) => r.timings.duration < 200
    });
    sleep(1);
}

WARN[0063] Request Failed                                error="Get http://test.loadimpact.com: dial tcp "ip":80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."

ERRO[0063] GoError: invalid URL value '&http.Response{ctx:(*context.valueCtx)(0xc003dfbb00), RemoteIP:"", RemotePort:0, URL:"http://test.loadimpact.com", Status:0, Proto:"", Headers:map[string]string(nil), Cookies:map[string][]*httpext.HTTPCookie(nil), Body:interface {}(nil), Timings:httpext.ResponseTimings{Duration:0, Blocked:0, LookingUp:0, Connecting:0, TLSHandshaking:0, Sending:0, Waiting:0, Receiving:0}, TLSVersion:"", TLSCipherSuite:"", OCSP:netext.OCSP{ProducedAt:0, ThisUpdate:0, NextUpdate:0, RevokedAt:0, RevocationReason:"", Status:""}, Error:"dial tcp "ip":80: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.", ErrorCode:1210, Request:httpext.Request{Method:"GET", URL:"http://test.loadimpact.com", Headers:map[string][]string{"User-Agent":[]string{"k6/0.24.0 (https://k6.io/)"}}, Body:"", Cookies:map[string][]*httpext.HTTPRequestCookie{}}, cachedJSON:interface {}(nil), validatedJSON:false}'

Body:
You are setting the URL to be the result of the http.get function call, I think you intended to do:

export default function() {
  let url = "http://test.loadimpact.com";
  let res = http.get(url);
  check(res, {
    "status was 200": (r) => r.status == 200,
        "transaction time OK": (r) => r.timings.duration < 200
    });
    sleep(1);
}


问:
Yocto rebuild image after modifying source code
How can I rebuild the image after making some modifications to driver source code?

I have tried bitbake -f -c compile and bitbake but I coudn't find the modified settings in the driver. Can someone tell me how can i rebuild the image with the modified code.

答:
Since changes in ${WORKDIR} will be rewritten after cleaning, you can put your code to external workspace by command devtool modify <recipe-name>

By default your recipe code will be put into tmp/workspace/source/ directory
Now you can freely modify your code and simply build using bitbake <recipe-name> as usual.

When your modification are OK you can easily save your changes as patches to original recipe code (as far as it is likely open-source and downloaded):

commit your changes in your workspace

in order to automatically create patches and append they to recipe use command devtool recipe-update -a <layer-path> <recipe-name>


问:
C++: Cloud computing library: is there such a library where I don't need to write much network stuff?
I want my server app to be able to send data to be processed by a bunch of various clients, and then have the processed data returned to the server.

Ideally, I'd have some call like some_process = send_to_client_for_calculating(connection, data)

I just need to be able to send a bunch of data to a client, tell the client what to do (preferably in the same message, which can be done with an array [command, data]), and then return the data...

I'm breaking up pieces of a neural network (tis very large), and then assembling them all later.

If I need to be clearer, let me know how.

答: You could try using beanstalkd, a fast working queue. I don't know if it fits your purposes. There is a client library written in C, which you should be able to use from C++.</p>


问:
Running a single test file
Is there a way to run ng test for a single file instead of for the entire test suite?  Ideally, I'd like to get the quickest possible feedback loop when I'm editing a file, but karma executes the whole suite on each save, which is a bit slow when you build up a big enough test suite.

This is different from How to execute only one test spec with angular-cli in that that question is about running an individual spec.  This is about running an individual file.  The solution involves the same Jasmine spec feature, but the nature of the question is slightly different.

答:
Using</p>
```<code>ng test --main file.spec.ts
</code>```

Title: Running a single test file

Body:
Using

ng test --main file.spec.ts


问:
How can I use SpeechSynthesizer in ASP.NET Core 2.0
I'm trying to save a text to Audio file in my web app developed in ASP.NET Core 2.0.

I'm trying to find the support for the System.Speech, but the namespace seems not available in .NET Core.

Can anyone give me any alternate class libraries to save a text to audio file (MP3).

I found some ScriptCs code samples but they are not working for me.

Does anyone has any suggestions?

答:
Not sure if this is an option for you, but you could set your ASP.NET Core app to target the .NET Framework.

Edit yourapp.csproj and change:

```<code><TargetFramework>netcoreapp2.2</TargetFramework>
</code>```

to

```<code><TargetFramework>net472</TargetFramework>
</code>```

Now you should be able to add the reference to System.Speech and do something like:

```<code>System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();
synth.SetOutputToDefaultAudioDevice();
synth.Speak("Your awesome web site is starting!!");
</code>```

Another cool way to get this done would be to use some on-line API, such as Azure Speech Services (text-to-speech) that is pretty much platform independent and provides plenty of configuration options (https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/text-to-speech).

Body:
Not sure if this is an option for you, but you could set your ASP.NET Core app to target the .NET Framework.

Edit yourapp.csproj and change:

<TargetFramework>netcoreapp2.2</TargetFramework>

to

<TargetFramework>net472</TargetFramework>

Now you should be able to add the reference to System.Speech and do something like:

System.Speech.Synthesis.SpeechSynthesizer synth = new System.Speech.Synthesis.SpeechSynthesizer();
synth.SetOutputToDefaultAudioDevice();
synth.Speak("Your awesome web site is starting!!");

Another cool way to get this done would be to use some on-line API, such as Azure Speech Services (text-to-speech) that is pretty much platform independent and provides plenty of configuration options (https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/text-to-speech).


答:
It's called JSDoc, and it's an auto-generated documentation (in the form of comments) that can be used in your JavaScript files.

It interacts with many IDEs (Integrated Development Interfaces), such as VSCode, and it's useful for showing type annotations as well. Here's a type-annotated function:

```<code>/**
 * Represents a person
 * @constructor
 * @param {string} name - The name of the person
 * @param {number} age - The age of the person
 */
function Person(name, age) {
    this.name = name;
    this.age = age;
}
</code>```

As you can see, the JSDoc documentation goes above the function it's describing, and it knows that:

The function represents a person

The function is a constructor (@constructor)

The function takes a parameter (@param) of type string, named name, which represents the name of the person

The function takes a parameter (@param) of type number, named age, which represents the age of the person

In this sense it's kind of like TypeScript - it uses type annotations (except because they're just comments, it's not enforced like it would be by the TypeScript compiler).

Title: What is the purpose of text preceded with @ in comments

Body:
It's called JSDoc, and it's an auto-generated documentation (in the form of comments) that can be used in your JavaScript files.

It interacts with many IDEs (Integrated Development Interfaces), such as VSCode, and it's useful for showing type annotations as well. Here's a type-annotated function:

/**
 * Represents a person
 * @constructor
 * @param {string} name - The name of the person
 * @param {number} age - The age of the person
 */
function Person(name, age) {
    this.name = name;
    this.age = age;
}

As you can see, the JSDoc documentation goes above the function it's describing, and it knows that:

The function represents a person

The function is a constructor (@constructor)

The function takes a parameter (@param) of type string, named name, which represents the name of the person

The function takes a parameter (@param) of type number, named age, which represents the age of the person

In this sense it's kind of like TypeScript - it uses type annotations (except because they're just comments, it's not enforced like it would be by the TypeScript compiler).


问:
How to Maintain the State of CollectionView over different Segments (Tab)
I'm having a collection View flow layout added as a subview inside segmented control. The Segment is Categorised into All, New, Used.
My problem is how can I maintain the state of the collection view over different Segments.

I'm Making API Calls for Loading the Data on All, New, Used segments

Also Each time when I switch the Tab I'm calling [collectionView reloadData] Which reloads the collection view but not exactly the position where I left earlier in that particular segment

For example in All Segment I have Scrolled 10 - 15 items then i'm switching to New Segment and scrolling 3 Items and Now if I again Switch the Tab to All Segment then the Position of All Segment also goes to 3rd position

How can this be resolved. Thank you for reading patiently. Any Help would help me a lot.

Here is the sample code which I use for switching the Segment

```<code>-(IBAction)changeSeg:(id)sender{
    [collectionView reloadData];

    if(segmentedControl.selectedSegmentIndex == 0){
atScrollPosition:UICollectionViewScrollPositionNone animated:false];
        typeFlag = 0;
        if ([inventoryDetails count] == 0 && totalInventoryCountForAll != 0) {
            [self loadMore];
        } else if (totalInventoryCountForAll == 0) {
            [self setNoCarVisibility: true];
        }
    }
    else if(segmentedControl.selectedSegmentIndex == 1){
        typeFlag = 1;
        if ([newInventory count] == 0 && totalInventoryCountForNew != 0) {
            [self loadMore];
        } else if (totalInventoryCountForNew == 0) {
            [self setNoCarVisibility: true];
        }
    }
    else if(segmentedControl.selectedSegmentIndex == 2){
        typeFlag = 2;
        if([usedInventory count] == 0 && totalInventoryCountForUsed != 0){
            [self loadMore];
        } else if (totalInventoryCountForUsed == 0) {
            [self setNoCarVisibility: true];
        }
    }

}
</code>```

答:
May be you can save the indexpath of currently visisble cell when you you switch tab scrolltoIndepath after reloadData.
Hope it helps....

Edit
Current indexpath each for 3 tabs separately. So there wont be one variable instead there will be 3 variables of indexpath individual to each tab, once tab switched manage the values in respective var and then relaod in same way.

For example currentAllIndexpath, currentNewIndexpath etc.

Body:
I'm having a collection View flow layout added as a subview inside segmented control. The Segment is Categorised into All, New, Used.
My problem is how can I maintain the state of the collection view over different Segments.

I'm Making API Calls for Loading the Data on All, New, Used segments

Also Each time when I switch the Tab I'm calling [collectionView reloadData] Which reloads the collection view but not exactly the position where I left earlier in that particular segment

For example in All Segment I have Scrolled 10 - 15 items then i'm switching to New Segment and scrolling 3 Items and Now if I again Switch the Tab to All Segment then the Position of All Segment also goes to 3rd position

How can this be resolved. Thank you for reading patiently. Any Help would help me a lot.

Here is the sample code which I use for switching the Segment

-(IBAction)changeSeg:(id)sender{
    [collectionView reloadData];

    if(segmentedControl.selectedSegmentIndex == 0){
atScrollPosition:UICollectionViewScrollPositionNone animated:false];
        typeFlag = 0;
        if ([inventoryDetails count] == 0 && totalInventoryCountForAll != 0) {
            [self loadMore];
        } else if (totalInventoryCountForAll == 0) {
            [self setNoCarVisibility: true];
        }
    }
    else if(segmentedControl.selectedSegmentIndex == 1){
        typeFlag = 1;
        if ([newInventory count] == 0 && totalInventoryCountForNew != 0) {
            [self loadMore];
        } else if (totalInventoryCountForNew == 0) {
            [self setNoCarVisibility: true];
        }
    }
    else if(segmentedControl.selectedSegmentIndex == 2){
        typeFlag = 2;
        if([usedInventory count] == 0 && totalInventoryCountForUsed != 0){
            [self loadMore];
        } else if (totalInventoryCountForUsed == 0) {
            [self setNoCarVisibility: true];
        }
    }

}


问:
How to sync Property in ObservableCollection in ViewModel and ListBox Item in View
I want sync string Dependency Property of UserControl's ViewModel and ListBox's Item in View.I tried to bind, but it didn't work.

I want to make todo manager like Trello.

The apps has nest structure.
MainWindow has 2 SampleContainerView s.
Each SampleContainerView has ListBox(ObservableCollection in ViewModel).
and the ListBox has SampleControls (This is UserControl which has TextBox).

Below is codes.

SampleControl.xaml

```<code><Grid
    Background="Gray"
    >
    <TextBox
        Margin="10"
        Text="{Binding Title}"
        >
    </TextBox>
</Grid>
</code>```

SampleVM.cs

```<code>public class SampleVM :DependencyObject
{
    public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title",
                            typeof(string),
                            typeof(SampleVM));

    public string Title
    {
        get { return (string)GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }

    public SampleVM(string title="init")
    {
        SetValue(TitleProperty, title);
    }
}
</code>```

SampleContainer.xaml

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="2*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <ListBox
        ItemsSource="{Binding SampleList}"
        HorizontalContentAlignment="Stretch"
        VerticalContentAlignment="Stretch"
        Grid.Row="0"
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:SampleControl></local:SampleControl>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button
        Command="{Binding AddCommand}"
        Grid.Row="1"
        Margin="10">
        add Sample...
    </Button>
</Grid>
</code>```

SampleContainverVM.cs (omit DelegateCommand Implement here)

```<code>    public class SampleContainerVM : DependencyObject
    {
        public static readonly DependencyProperty SampleListProperty =
DependencyProperty.Register("SampleList",
                        typeof(ObservableCollection<SampleVM>),
                        typeof(SampleContainerVM));

        public ObservableCollection<SampleVM> SampleList
        {
            get { return (ObservableCollection<SampleVM>)GetValue(SampleListProperty); }
            set { SetValue(SampleListProperty, value); }
        }

        public DelegateCommand AddCommand { get; set; }

        public SampleContainerVM()
        {
            SetValue(SampleListProperty, new ObservableCollection<SampleVM>());
            AddCommand = new DelegateCommand(
                AddSample,
                () => { return true; });
        }

        private void AddSample()
        {
            SampleList.Add(new SampleVM());
        }
    }
</code>```

DataContext = new VM() in every xaml.cs

Now I can add SampleControl to ListBox in SampleContainer by clicking button.

The problem is:
Instances(Title Property) in SampleList of SampleContainer don't change even when I change text in View.

Should I add any eventhandler?

答:
I thought too much about DependencyProperty and I should think simply.
I didn't need DependencyProperty.

I could achieve what I want as follows:

SampleVM.cs

```<code>public class SampleVM : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _title;
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            NotifyPropertyChanged();
        }
    }

    public SampleVM(string title="init")
    {
        Title = title;
    }
}
</code>```

SampleContainerVM.cs

```<code>public class SampleContainerVM
{
    public ObservableCollection<SampleVM> SampleList { get; set; }

    public DelegateCommand AddCommand { get; set; }

    public SampleContainerVM()
    {
        SampleList = new ObservableCollection<SampleVM>();
        AddCommand = new DelegateCommand(
            AddSample,
            () => { return true; });
    }

    private void AddSample()
    {
        SampleList.Add(new SampleVM());
    }
}
</code>```

SampleContainer.xaml(Delete Sample.xaml and write into <ListBox.ItemTemplate>)

```<code><UserControl x:Class="Sample.SampleContainer"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Sample"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <ListBox
            ItemsSource="{Binding SampleList}"
            HorizontalContentAlignment="Stretch"
            VerticalContentAlignment="Stretch"
            Grid.Row="0"
            >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBox
                        Margin="10"
                        Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"
                     >
                    </TextBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button
            Command="{Binding AddCommand}"
            Grid.Row="1"
            Margin="10">
            add Sample...
        </Button>
    </Grid>
</UserControl>
</code>```

Body:
I want sync string Dependency Property of UserControl's ViewModel and ListBox's Item in View.I tried to bind, but it didn't work.

I want to make todo manager like Trello.

The apps has nest structure.
MainWindow has 2 SampleContainerView s.
Each SampleContainerView has ListBox(ObservableCollection in ViewModel).
and the ListBox has SampleControls (This is UserControl which has TextBox).

Below is codes.

SampleControl.xaml

<Grid
    Background="Gray"
    >
    <TextBox
        Margin="10"
        Text="{Binding Title}"
        >
    </TextBox>
</Grid>

SampleVM.cs

public class SampleVM :DependencyObject
{
    public static readonly DependencyProperty TitleProperty =
DependencyProperty.Register("Title",
                            typeof(string),
                            typeof(SampleVM));

    public string Title
    {
        get { return (string)GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }

    public SampleVM(string title="init")
    {
        SetValue(TitleProperty, title);
    }
}

SampleContainer.xaml

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="2*" />
        <RowDefinition Height="1*" />
    </Grid.RowDefinitions>
    <ListBox
        ItemsSource="{Binding SampleList}"
        HorizontalContentAlignment="Stretch"
        VerticalContentAlignment="Stretch"
        Grid.Row="0"
        >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <local:SampleControl></local:SampleControl>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <Button
        Command="{Binding AddCommand}"
        Grid.Row="1"
        Margin="10">
        add Sample...
    </Button>
</Grid>

SampleContainverVM.cs (omit DelegateCommand Implement here)

    public class SampleContainerVM : DependencyObject
    {
        public static readonly DependencyProperty SampleListProperty =
DependencyProperty.Register("SampleList",
                        typeof(ObservableCollection<SampleVM>),
                        typeof(SampleContainerVM));

        public ObservableCollection<SampleVM> SampleList
        {
            get { return (ObservableCollection<SampleVM>)GetValue(SampleListProperty); }
            set { SetValue(SampleListProperty, value); }
        }

        public DelegateCommand AddCommand { get; set; }

        public SampleContainerVM()
        {
            SetValue(SampleListProperty, new ObservableCollection<SampleVM>());
            AddCommand = new DelegateCommand(
                AddSample,
                () => { return true; });
        }

        private void AddSample()
        {
            SampleList.Add(new SampleVM());
        }
    }

DataContext = new VM() in every xaml.cs

Now I can add SampleControl to ListBox in SampleContainer by clicking button.

The problem is:
Instances(Title Property) in SampleList of SampleContainer don't change even when I change text in View.

Should I add any eventhandler?

Body:
I thought too much about DependencyProperty and I should think simply.
I didn't need DependencyProperty.

I could achieve what I want as follows:

SampleVM.cs

public class SampleVM : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string _title;
    public string Title
    {
        get { return _title; }
        set
        {
            _title = value;
            NotifyPropertyChanged();
        }
    }

    public SampleVM(string title="init")
    {
        Title = title;
    }
}

SampleContainerVM.cs

public class SampleContainerVM
{
    public ObservableCollection<SampleVM> SampleList { get; set; }

    public DelegateCommand AddCommand { get; set; }

    public SampleContainerVM()
    {
        SampleList = new ObservableCollection<SampleVM>();
        AddCommand = new DelegateCommand(
            AddSample,
            () => { return true; });
    }

    private void AddSample()
    {
        SampleList.Add(new SampleVM());
    }
}

SampleContainer.xaml(Delete Sample.xaml and write into <ListBox.ItemTemplate>)

<UserControl x:Class="Sample.SampleContainer"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:Sample"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="2*" />
            <RowDefinition Height="1*" />
        </Grid.RowDefinitions>
        <ListBox
            ItemsSource="{Binding SampleList}"
            HorizontalContentAlignment="Stretch"
            VerticalContentAlignment="Stretch"
            Grid.Row="0"
            >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBox
                        Margin="10"
                        Text="{Binding Title, UpdateSourceTrigger=PropertyChanged}"
                     >
                    </TextBox>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button
            Command="{Binding AddCommand}"
            Grid.Row="1"
            Margin="10">
            add Sample...
        </Button>
    </Grid>
</UserControl>


问:
unable take input from a text file in python crawler
I have created a basic crawler in python, I want to take input from a text file.

I used open/raw_input but there was an error.

When I used input("") function it is prompting for input and was working fine.
The problem only with reading a file

```<code>     import re

     import urllib.request

     url = open('input.txt', 'r')

     data =  urllib.request.urlopen(url).read()
     data1 = data.decode("utf8")
     print(data1)

     file =open('output.txt' , 'w')
     file.write(data1)
     file.close()
</code>```

error output below.

```<code>Traceback (most recent call last):
  File "scrape.py", line 8, in <module>
    data =  urllib.request.urlopen(url).read()
  File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.6/urllib/request.py", line 518, in open
    protocol = req.type
AttributeError: '_io.TextIOWrapper' object has no attribute 'type'
</code>```

答:
the method open returns a file object, and not the content of the file as a string. if you want url to contain the content as a string, change the line to:

url = open('input.txt', 'r').read()

Body:
I have created a basic crawler in python, I want to take input from a text file.

I used open/raw_input but there was an error.

When I used input("") function it is prompting for input and was working fine.
The problem only with reading a file

     import re

     import urllib.request

     url = open('input.txt', 'r')

     data =  urllib.request.urlopen(url).read()
     data1 = data.decode("utf8")
     print(data1)

     file =open('output.txt' , 'w')
     file.write(data1)
     file.close()

error output below.

Traceback (most recent call last):
  File "scrape.py", line 8, in <module>
    data =  urllib.request.urlopen(url).read()
  File "/usr/lib/python3.6/urllib/request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.6/urllib/request.py", line 518, in open
    protocol = req.type
AttributeError: '_io.TextIOWrapper' object has no attribute 'type'


问:
How do I return an integer that is the sum of the integer values input in an ArrayList for Java at the indices 19, 9, and 14? So far I have:
How do I return an integer that is the sum of the integer values input in an ArrayList for Java at the indices 19, 9, and 14? So far I have:<br>
Write a public static method named q3 that takes an ArrayList of Integers as a       * parameter and returns an int. The returned int should be the sum of the values int the       * input ArrayList at indices 19, 9, and 14. You can assume the input ArrayList has size       * large enough to avoid an index out of bounds exception at these indices      </p>

```<code>public static int q3(ArrayList<Integers>) {
ArrayList<Integers> thisList = new ArrayList<Integers>();
thisList.add(9, "3");
thisList.add(14, "0");
thisList.add(19, "33");

int sum = 0;
int i = 0;
</code>```

答:
Explanation

Let me try to explain what a list is and how it works.
Imagine a list/array like a drawer cabinet, where each drawer has a number (index).

with list.add(content) you increase the size of the list and put content to the new drawer at the very last end (the automatically new created one).

with list.add(index, content) you put content into the drawer with the number index (and overwritwe any content in there before).

with list.get(index) you will get the content from the drawer with the number index.

ArrayList<Integer> numbers = new ArrayList<>(); // Create a empty list of numbers
numbers.add(8); // appends the number 8 to the list (the list gets bigger)
numbers.add(7); // appends the number 7 to the list (the list gets bigger)
numbers.add(6); // appends the number 6 to the list (the list gets bigger)

System.out.println(numbers); // {8,7,6}

numbers.add(0,11);
System.out.println(numbers); // {11,7,6}

System.out.println(numbers.get(0)); // 11
```
<hr />
<h2>Answer</h2>
<p>Long simple readable version:</p>
<pre class="lang-java prettyprint-override"><code>public static int q3(ArrayList<Integer> list) {
   int sum = 0;
   sum = sum + list.get(19);
   sum = sum + list.get(9);
   sum = sum + list.get(14);
   return sum;
}
</code>```

Version in short:

public static int q3(ArrayList<Integer> list) {
   return (list.get(19) + list.get(9) + list.get(14));
}
```

Body:
How do I return an integer that is the sum of the integer values input in an ArrayList for Java at the indices 19, 9, and 14? So far I have:

Write a public static method named q3 that takes an ArrayList of Integers as a       * parameter and returns an int. The returned int should be the sum of the values int the       * input ArrayList at indices 19, 9, and 14. You can assume the input ArrayList has size       * large enough to avoid an index out of bounds exception at these indices

public static int q3(ArrayList<Integers>) {
ArrayList<Integers> thisList = new ArrayList<Integers>();
thisList.add(9, "3");
thisList.add(14, "0");
thisList.add(19, "33");

int sum = 0;
int i = 0;

Body:
Explanation

Let me try to explain what a list is and how it works.
Imagine a list/array like a drawer cabinet, where each drawer has a number (index).

with list.add(content) you increase the size of the list and put content to the new drawer at the very last end (the automatically new created one).

with list.add(index, content) you put content into the drawer with the number index (and overwritwe any content in there before).

with list.get(index) you will get the content from the drawer with the number index.

ArrayList<Integer> numbers = new ArrayList<>(); // Create a empty list of numbers
numbers.add(8); // appends the number 8 to the list (the list gets bigger)
numbers.add(7); // appends the number 7 to the list (the list gets bigger)
numbers.add(6); // appends the number 6 to the list (the list gets bigger)

System.out.println(numbers); // {8,7,6}

numbers.add(0,11);
System.out.println(numbers); // {11,7,6}

System.out.println(numbers.get(0)); // 11

Answer

Long simple readable version:

public static int q3(ArrayList<Integer> list) {
   int sum = 0;
   sum = sum + list.get(19);
   sum = sum + list.get(9);
   sum = sum + list.get(14);
   return sum;
}

Version in short:

public static int q3(ArrayList<Integer> list) {
   return (list.get(19) + list.get(9) + list.get(14));
}


问:
How can I use For, While, Repeat functions with changing rep times
How can i print following code with For, While and Repeat functions in R?

[1] 9 9 9 9 9

[1] 7 7 7

[1] 5

[1] 3 3 3

[1] 1 1 1 1 1

With 2 hours of trial, I've discovered following code works to print above result

x<-c(5,0,3,0,1,0,3,0,5,0)

for(i in 10:1) {   if(!i %%2) {    next   }

print(rep(i,x[i]))

}

while func

t<-c(5,0,3,0,1,0,3,0,5)

i<-9

while(i>=1)

{print(rep(i,t[i]))

i<-i-2}

repeat

i<-9

  repeat{if(i<1)

  break
   print(rep(i,t[i]))

  i<- i-2}

but it seems so unnatural for me.
Is there any more compact or easier way to solve the problem?

Body:
We can pass a vector of input to replicate in rep

x1 <- rep(c(9, 7, 5, 3, 1), c(5, 3 ,1, 3, 5))
#[1] 9 9 9 9 9 7 7 7 5 3 3 3 1 1 1 1 1

and then split based on the replicate

split(x1, factor(x1, levels = unique(x1)))
#$`9`
#[1] 9 9 9 9 9

#$`7`
#[1] 7 7 7

#$`5`
#[1] 5

#$`3`
#[1] 3 3 3

#$`1`
#[1] 1 1 1 1 1


问:
Spring data repository with empty IN clause
I'm using Spring data JPA like this:

```<code>    public interface SampleRepository extends CrudRepository<Sample, Integer>{

    @Query("SELECT s FROM Sample s WHERE ((:ids) IS NULL OR s.id IN (:ids))")
            List<Sample> queryIn(@Param("ids") List<Integer> ids);
    }
</code>```

But when ids is not empty, I got (1,2,3) is null which is incorrect in mysql.

If I write like this:

```<code>    public interface SampleRepository extends CrudRepository<Sample, Integer>{
    @Query("SELECT s FROM Sample s WHERE s.id IN (:ids)")
            List<Sample> queryIn(@Param("ids") List<Integer> ids);
    }
</code>```

When ids is empty, I got s.id in (null)

If I must use native query to do this. Any suggestions?

答:
I guess you want to use ISNULL function to see if :ids has a value or not</p>

```<code>SELECT s FROM Sample s WHERE s.id IN (:ids)) or ISNULL(:ids) = 1
</code>```

Body:
I'm using Spring data JPA like this:

    public interface SampleRepository extends CrudRepository<Sample, Integer>{

    @Query("SELECT s FROM Sample s WHERE ((:ids) IS NULL OR s.id IN (:ids))")
            List<Sample> queryIn(@Param("ids") List<Integer> ids);
    }

But when ids is not empty, I got (1,2,3) is null which is incorrect in mysql.

If I write like this:

    public interface SampleRepository extends CrudRepository<Sample, Integer>{
    @Query("SELECT s FROM Sample s WHERE s.id IN (:ids)")
            List<Sample> queryIn(@Param("ids") List<Integer> ids);
    }

When ids is empty, I got s.id in (null)

If I must use native query to do this. Any suggestions?

Body:
I guess you want to use ISNULL function to see if :ids has a value or not

SELECT s FROM Sample s WHERE s.id IN (:ids)) or ISNULL(:ids) = 1


问:
Check constraint in MongoDb
Is it possible in MongoDb to add a check constraint that a value should be in a range? Like in SQL you would say

ALTER TABLE GpsData ADD CONSTRAINT CK_X_not_0 CHECK (X <> 0)

答:
Yes, there is a Schema Validation feature in Mongodb since 3.2

Although I believe it's not as versatile as SQL constraints in most popular engines, it should be more than enough for most use cases.

Title: Check constraint in MongoDb