问:
How to refresh a single item in a FlatList in React-Native?
I made a Like function with React and Flask API, it works pretty well, it makes the Like action but it only appears when I refresh the whole list. Somehow I want to refresh the Like picture and the Like count at the post. </p>

<p>I tried to put extraData in my FlatList but that does not solve my problem... </p>

```<code>handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    const action = this.props.has_liked?  'unlike':'like'
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
        action: action
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error)
    });
    this.setState({liked: action})
  }
    render() {
      const img = this.props.has_liked?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')
        return(
        <View style={{flex:1, marginTop: 10, marginBottom:16, left: 20}}>
         <View style={{flex: 1, flexDirection: 'row'}}>
         <Image source={this.props.image_uri} style={{height:42, width: 42, borderRadius:21}}/>
          <Text style={{left:20,paddingTop:6}}>{this.props.author}</Text>
          <Text style={{position: 'absolute', right: 40, paddingTop:6,fontSize:12,color:'#babbbc'}}> {this.props.date} </Text>
         </View>
        <View style={{flex:1, left: 60, right:20,width: '70%', marginTop:-10}}>
          <Text style={{fontWeight:'bold',fontSize:18,marginBottom:6}}>{this.props.title} </Text>
          <Text style={{fontSize:16,marginBottom:6 }}>{this.props.content}</Text>
        <View style={{flex: 1, flexDirection: 'row'}}>
          <TouchableOpacity onPress={this.handleClick}>
          <Image style={{width:24, height:24, marginBottom:6, marginTop:6}} source={img} />
          </TouchableOpacity>
          <Text style={{paddingTop:10, marginLeft:6, fontSize:14,color:'#bfbfbf'}}>{this.props.likes}</Text>
        </View>
        </View>
      </View>
      );
    }

  }
</code>```

```<code><FlatList
            data={this.state.dataSource}
            extraData={this.state}
            renderItem={({item}) => <PostView title={item.title}
                                        content={item.content}
                                        author={item.author}
                                        date={item.date_posted}
                                        likes={item.likes}
                                        has_liked={item.has_liked}
                                        jwt = {this.props.screenProps.jwt}
                                        id = {item.id}
                                        image_uri={{uri:'http://127.0.0.1:5000/static/profile_pics/'+item.profile_image}}/> }
                                        refreshing={this.state.refreshing}
                                        onRefresh={this.handleRefresh}
                                        keyExtractor={item => item.id}/>
        </View>
</code>```

答:
extraData :

```<code>extraData={{this.state}}
</code>```

and put this.setState({liked: action}) here:

```<code>.then((response) => {
      console.log(response.data);
      this.setState({liked: action})
    })
</code>```

Body:
I made a Like function with React and Flask API, it works pretty well, it makes the Like action but it only appears when I refresh the whole list. Somehow I want to refresh the Like picture and the Like count at the post.

I tried to put extraData in my FlatList but that does not solve my problem...

handleClick() {
    const headers = {
      'Authorization': 'jwt ' + this.props.jwt
    };
    const action = this.props.has_liked?  'unlike':'like'
    axios.post("http://127.0.0.1:5000/API/likeaction",{
        id: this.props.id,
        action: action
    }, {
      headers: headers
    })
    .then((response) => {
      console.log(response.data);
    })
    .catch((error) => {
      console.log(error)
    });
    this.setState({liked: action})
  }
    render() {
      const img = this.props.has_liked?  require('../assets/icons/heart-filled.png') : require('../assets/icons/heart-no-fill.png')
        return(
        <View style={{flex:1, marginTop: 10, marginBottom:16, left: 20}}>
         <View style={{flex: 1, flexDirection: 'row'}}>
         <Image source={this.props.image_uri} style={{height:42, width: 42, borderRadius:21}}/>
          <Text style={{left:20,paddingTop:6}}>{this.props.author}</Text>
          <Text style={{position: 'absolute', right: 40, paddingTop:6,fontSize:12,color:'#babbbc'}}> {this.props.date} </Text>
         </View>
        <View style={{flex:1, left: 60, right:20,width: '70%', marginTop:-10}}>
          <Text style={{fontWeight:'bold',fontSize:18,marginBottom:6}}>{this.props.title} </Text>
          <Text style={{fontSize:16,marginBottom:6 }}>{this.props.content}</Text>
        <View style={{flex: 1, flexDirection: 'row'}}>
          <TouchableOpacity onPress={this.handleClick}>
          <Image style={{width:24, height:24, marginBottom:6, marginTop:6}} source={img} />
          </TouchableOpacity>
          <Text style={{paddingTop:10, marginLeft:6, fontSize:14,color:'#bfbfbf'}}>{this.props.likes}</Text>
        </View>
        </View>
      </View>
      );
    }

  }

<FlatList
            data={this.state.dataSource}
            extraData={this.state}
            renderItem={({item}) => <PostView title={item.title}
                                        content={item.content}
                                        author={item.author}
                                        date={item.date_posted}
                                        likes={item.likes}
                                        has_liked={item.has_liked}
                                        jwt = {this.props.screenProps.jwt}
                                        id = {item.id}
                                        image_uri={{uri:'http://127.0.0.1:5000/static/profile_pics/'+item.profile_image}}/> }
                                        refreshing={this.state.refreshing}
                                        onRefresh={this.handleRefresh}
                                        keyExtractor={item => item.id}/>
        </View>

Body:
extraData :

extraData={{this.state}}

and put this.setState({liked: action}) here:

.then((response) => {
      console.log(response.data);
      this.setState({liked: action})
    })


来源: stackexchange

问:
How to keep all versions of RESTful interface online?
Our Java EE project has a RESTful interface available at something like http://example.com/rest/. When the development is progressing we create new versions of this interface. In order to enable backward compatibility we'd like to provide them all online, at different URLs, for example:

```<code>http://example.com/rest/1.0/
http://example.com/rest/1.1/
</code>```

The question is how to deploy them? Shall we assemble a number of WARs (we use Maven)? But the project has the latest version in /trunk.. Maybe we should package them all into one WAR by means of some Maven plugin, retrieving them from Subversion /tags? What is your experience?

答:
If by versioning, you are talking about the structure of your resources/content type, you'd have to keep your old implementation and use content negotiation so as older clients can still use your service.

If the only change is on URL structures, then you don't need any versioning, just use 301-Moved Permanently redirects.

ContentLicense: CC BY-SA 3.0

Body:
Our Java EE project has a RESTful interface available at something like http://example.com/rest/. When the development is progressing we create new versions of this interface. In order to enable backward compatibility we'd like to provide them all online, at different URLs, for example:

http://example.com/rest/1.0/
http://example.com/rest/1.1/

The question is how to deploy them? Shall we assemble a number of WARs (we use Maven)? But the project has the latest version in /trunk.. Maybe we should package them all into one WAR by means of some Maven plugin, retrieving them from Subversion /tags? What is your experience?


问:
EF core Access list through Include
I have a Model named as Blog:

```<code>public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }
</code>```

And another model Comment:

```<code>public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }
</code>```

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

```<code>var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);
</code>```

But all I am getting exception is

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.
</code>```

How can I solve this problem?

答:
You must use entity framework projections.</p>

```<code>var blog = await _context.Blog
.Select(p => new Blog
{
    blogComments  = p.blogComments.Where(s => !s.isHidden )
}.FirstOrDefaultAsync(m => m.blogId == id);
</code>```

ContentLicense: CC BY-SA 4.0

Title: EF core Access list through Include

Body:
I have a Model named as Blog:

public class Blog
    {
        [Key]
        public int blogId { get; set; }
        [Required]
        public string blogTitle { get; set; }
        public string imagePath { get; set; }
        [Required, DataType(DataType.Html)]
        public string blogDescription { get; set; }
        [DataType(DataType.DateTime)]
        public DateTime blogDateTime { get; set; }
        [Required]
        public bool isPublished { get; set; }

        [Required]
        public BlogCategory blogCategory { get; set; }
        public List<Comments> blogComments { get; set; }
    }

And another model Comment:

public class Comments
    {
        [Key]
        public int authorId { get; set; }
        [Required]
        public string commentAuthor { get; set; }
        [DataType(DataType.Date)]
        public DateTime commentDate { get; set; }
        public bool isHidden { get; set; }
        [Required, DataType(DataType.EmailAddress)]
        public string commentAuthorEmail { get; set; }
        [Required]
        public string commentDescription { get; set; }
        public Blog Blog { get; set; }
    }

In the blogs controller I want to access all the comments where isHidden = false

What I have tried is:

var blog = await _context.Blog
           .Include(cat => cat.blogCategory)
           .Include(comments => comments.blogComments.Any(c => !c.isHidden))
           .FirstOrDefaultAsync(m => m.blogId == id);

But all I am getting exception is

An unhandled exception occurred while processing the request.
InvalidOperationException: The Include property lambda expression 'comments => comments.blogComments.Find(c => Not(c.isHidden))' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'.

How can I solve this problem?

Body:
You must use entity framework projections.

var blog = await _context.Blog
.Select(p => new Blog
{
    blogComments  = p.blogComments.Where(s => !s.isHidden )
}.FirstOrDefaultAsync(m => m.blogId == id);


问:
Reordering a list from comma sepperated ID's
I have a list of objects I want to reorder. The order is determined in a string.

(I hope my current code explains better than the text)

```<code>List<DataObject> objects = GetDataObjectsFromDatabase();
string order = "1,3,2";
List<DataObject> orderedObjects = new List<DataObject>
foreach(string index in order.Split(',')
{
    orderedObjects.Add(objects.FirstOrDefault(x => x.id == index));
}
</code>```

Is there a single Linq statement or a better way to do this?

答:
Here is example of ordering list based on another list in linq:

```<code>        List<OBJ> Test = new List<OBJ>();
        Test.Add(new OBJ(1));
        Test.Add(new OBJ(2));
        string Order = "1,2,3";
        List<string> OrderBy = Order.Split(new char[] { ',' }).ToList();
        Test = Test.OrderBy(x => OrderBy.IndexOf(x.Field1.ToString())).ToList();
        Console.ReadKey();
</code>```

Assuming that x.Field1 is your ID (or whatever field you want to sort by).

Body:
I have a list of objects I want to reorder. The order is determined in a string.

(I hope my current code explains better than the text)

List<DataObject> objects = GetDataObjectsFromDatabase();
string order = "1,3,2";
List<DataObject> orderedObjects = new List<DataObject>
foreach(string index in order.Split(',')
{
    orderedObjects.Add(objects.FirstOrDefault(x => x.id == index));
}

Is there a single Linq statement or a better way to do this?

Body:
Here is example of ordering list based on another list in linq:

        List<OBJ> Test = new List<OBJ>();
        Test.Add(new OBJ(1));
        Test.Add(new OBJ(2));
        string Order = "1,2,3";
        List<string> OrderBy = Order.Split(new char[] { ',' }).ToList();
        Test = Test.OrderBy(x => OrderBy.IndexOf(x.Field1.ToString())).ToList();
        Console.ReadKey();

Assuming that x.Field1 is your ID (or whatever field you want to sort by).


问:
NPM Install personal node library
I have created a library (country) in gitlab which I want installed in another project. This library uses another library of mine (dataloader). When I run npm i in my project, it installs country but then creates another node_modules inside country with dataloader. I want the dataloader library in the main node_modules. I am not able to understand why the dataloader package does not get included in the project node_modules

Expected Behaviour on npm i inside project:

```<code>Example Project
|
+--node_modules
  |
  +--country
  +--dataLoader`
</code>```

Country Library Package.json

Example Project Package.json

Problem :
Once i use to npm install in my Example project then i get folder structure like

```<code>Observed Behaviour on npm i inside the project:

Example Project
|
+--node_modules
  |
  +--country
     |
     +--node_modules
       |
       +--dataLoader`
</code>```

but when i try to use npm install git+http://xxxxxxxxx/countries.git#master folder structure create as which i want.

eg:

```<code>Example Project
|
+--node_modules
  |
  +--country
  +--dataLoader`
</code>```

答:
Using Verdaccio my issue has been resolve.

What is verdaccio?

Verdaccio is a lightweight private npm proxy registry built in Node.js

we need to create private.
Using verdaccio with any node package manager client is quite straightforward.
You can use a custom registry either setting globally for all your projects

```<code>npm set registry http://localhost:4873
</code>```

then add .npmrc in your private library and your Example project

.npmrc

```<code>registry http://localhost:4873
</code>```

then instead of publishing your private library on npm you need to publish on verdaccio.

using following command

```<code>npm publish
</code>```

then using an your npm install folder structure is create correct which i want

```<code>Example Project
|
+--node_modules
  |
  +--country
  +--dataLoader
</code>```

Title: NPM Install personal node library

Body:
I have created a library (country) in gitlab which I want installed in another project. This library uses another library of mine (dataloader). When I run npm i in my project, it installs country but then creates another node_modules inside country with dataloader. I want the dataloader library in the main node_modules. I am not able to understand why the dataloader package does not get included in the project node_modules

Expected Behaviour on npm i inside project:

Example Project
|
+--node_modules
  |
  +--country
  +--dataLoader`

Country Library Package.json

Example Project Package.json

Problem :
Once i use to npm install in my Example project then i get folder structure like

Observed Behaviour on npm i inside the project:

Example Project
|
+--node_modules
  |
  +--country
     |
     +--node_modules
       |
       +--dataLoader`

but when i try to use npm install git+http://xxxxxxxxx/countries.git#master folder structure create as which i want.

eg:

Example Project
|
+--node_modules
  |
  +--country
  +--dataLoader`

Body:
Using Verdaccio my issue has been resolve.

What is verdaccio?

Verdaccio is a lightweight private npm proxy registry built in Node.js

we need to create private.
Using verdaccio with any node package manager client is quite straightforward.
You can use a custom registry either setting globally for all your projects

npm set registry http://localhost:4873

then add .npmrc in your private library and your Example project

.npmrc

registry http://localhost:4873

then instead of publishing your private library on npm you need to publish on verdaccio.

using following command

npm publish

then using an your npm install folder structure is create correct which i want

Example Project
|
+--node_modules
  |
  +--country
  +--dataLoader


问:
Disable Routing in TYPO3 9
I have 3 Sites on a development server in one TYPO3 Instance with one domain. No option to create another subdoamin. Routing doesnt work because some of the pages have the same names. For now I would like to simply disable routing and work with page IDs but I can not find a setting for this.

So - how can I disable routing in TYPO3 9?

Thank you.

答: There is no option to disable routing. You should think about adding an entry to your etc/hosts file to add a custom domain and use that one.

Title: Disable Routing in TYPO3 9


问:
Scipy.optimize minimize function arguments don't work for multiple vector inputs
I am trying to generate the solutions to PCA weights for some (yield-curve) market-data. However, I am getting an error message in my scipy.optimize.minimize function.

The main error is that it seems to be reading the arguments into the minimization function wrong (error_sum).

I looked up the generic form here, but it doesn't work for my code when I utilize it.
Scipy Minimize - Unable to minimize objective function

```<code>import scipy as sc
import scipy.optimize as optimize
from scipy.optimize import minimize

w1 = 1.0
w2 = 1.0
w3 = 1.0

row_C = np.zeros(len(df_.columns)) # initialize current row as zero
row_T = df_.iloc[-1].values # get the target row, which we have set as the last row of the panda dataframe

row_c = np.array([-0.35865725, 0.52793819, 0.70654759, -0.28909144, 1.08467752, 0.91287324])
row_t = np.array([1.7971, 2.5756, 2.2005, 1.4966, 1.45  , 1.8022])

def error_sum(row_c, row_t, params): # row_c is estimated and row_t is target
    w1 = params[0]
    w2 = params[1]
    w2 = params[2]

    if len(row_c) != len(row_t): return print('error where x and y points are not same length')
    for cnt in range(len(row_c)):
        row_c[cnt] = w1 * row1[cnt] + w2 * row2[cnt] + w3 * row3[cnt]

    return np.sum(np.abs(row_c - row_t))

for cnt in range(len(df_.columns)): # loop to calculate the PCA-based moves
    row_c[cnt] = w1 * row1[cnt] + w2 * row2[cnt] + w3 * row3[cnt]

print(np.sum(np.abs(row_c - row_t))) # this is to get the sum of absolute difference errors
print(error_sum(row_c, row_t, x0))

x0 = np.array([1.0, 1.0, 1.0]) # parameters to optimize
bnds = ((-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0)) # boundary conditions of x0 parameter set
options = {'maxiter': 100}

res = minimize(error_sum, x0 ,(row_c, row_t), bounds = bnds, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})
</code>```

The error message as per below

```<code>error where x and y points are not same length

TypeError                                 Traceback (most recent call last)
<ipython-input-158-8c50b421e58a> in <module>()
     32 options = {'maxiter': 100}
     33
---> 34 res = minimize(error_sum, x0 ,(row_c, row_t), bounds = bnds, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})

C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    473                       callback=callback, **options)
    474     elif meth == 'nelder-mead':
--> 475         return _minimize_neldermead(fun, x0, args, callback, **options)
    476     elif meth == 'powell':
    477         return _minimize_powell(fun, x0, args, callback, **options)

C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in _minimize_neldermead(func, x0, args, callback, maxiter, maxfev, disp, return_all, initial_simplex, xatol, fatol, **unknown_options)
    549         doshrink = 0
    550
--> 551         if fxr < fsim[0]:
    552             xe = (1 + rho * chi) * xbar - rho * chi * sim[-1]
    553             fxe = func(xe)

TypeError: '>' not supported between instances of 'float' and 'NoneType'
</code>```

答:
Try to change the order of the arguments in the definition of error_sum to

```<code>def error_sum(params, row_c, row_t)
</code>```

if you want to get the optimum of params and call the function like this:

```<code>minimize(error_sum, x0, args=(row_c, row_t), bounds = bnds, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})
</code>```

Body:
I am trying to generate the solutions to PCA weights for some (yield-curve) market-data. However, I am getting an error message in my scipy.optimize.minimize function.

The main error is that it seems to be reading the arguments into the minimization function wrong (error_sum).

I looked up the generic form here, but it doesn't work for my code when I utilize it.
Scipy Minimize - Unable to minimize objective function

import scipy as sc
import scipy.optimize as optimize
from scipy.optimize import minimize

w1 = 1.0
w2 = 1.0
w3 = 1.0

row_C = np.zeros(len(df_.columns)) # initialize current row as zero
row_T = df_.iloc[-1].values # get the target row, which we have set as the last row of the panda dataframe

row_c = np.array([-0.35865725, 0.52793819, 0.70654759, -0.28909144, 1.08467752, 0.91287324])
row_t = np.array([1.7971, 2.5756, 2.2005, 1.4966, 1.45  , 1.8022])

def error_sum(row_c, row_t, params): # row_c is estimated and row_t is target
    w1 = params[0]
    w2 = params[1]
    w2 = params[2]

    if len(row_c) != len(row_t): return print('error where x and y points are not same length')
    for cnt in range(len(row_c)):
        row_c[cnt] = w1 * row1[cnt] + w2 * row2[cnt] + w3 * row3[cnt]

    return np.sum(np.abs(row_c - row_t))

for cnt in range(len(df_.columns)): # loop to calculate the PCA-based moves
    row_c[cnt] = w1 * row1[cnt] + w2 * row2[cnt] + w3 * row3[cnt]

print(np.sum(np.abs(row_c - row_t))) # this is to get the sum of absolute difference errors
print(error_sum(row_c, row_t, x0))

x0 = np.array([1.0, 1.0, 1.0]) # parameters to optimize
bnds = ((-10.0, 10.0), (-10.0, 10.0), (-10.0, 10.0)) # boundary conditions of x0 parameter set
options = {'maxiter': 100}

res = minimize(error_sum, x0 ,(row_c, row_t), bounds = bnds, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})

The error message as per below

error where x and y points are not same length

TypeError                                 Traceback (most recent call last)
<ipython-input-158-8c50b421e58a> in <module>()
     32 options = {'maxiter': 100}
     33
---> 34 res = minimize(error_sum, x0 ,(row_c, row_t), bounds = bnds, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})

C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\_minimize.py in minimize(fun, x0, args, method, jac, hess, hessp, bounds, constraints, tol, callback, options)
    473                       callback=callback, **options)
    474     elif meth == 'nelder-mead':
--> 475         return _minimize_neldermead(fun, x0, args, callback, **options)
    476     elif meth == 'powell':
    477         return _minimize_powell(fun, x0, args, callback, **options)

C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py in _minimize_neldermead(func, x0, args, callback, maxiter, maxfev, disp, return_all, initial_simplex, xatol, fatol, **unknown_options)
    549         doshrink = 0
    550
--> 551         if fxr < fsim[0]:
    552             xe = (1 + rho * chi) * xbar - rho * chi * sim[-1]
    553             fxe = func(xe)

TypeError: '>' not supported between instances of 'float' and 'NoneType'

Body:
Try to change the order of the arguments in the definition of error_sum to

def error_sum(params, row_c, row_t)

if you want to get the optimum of params and call the function like this:

minimize(error_sum, x0, args=(row_c, row_t), bounds = bnds, method='nelder-mead', options={'xtol': 1e-8, 'disp': True})


问:
How to get the C# code support in vs2015 editor to work again?
I recently updated my visual studio 2015 to the update 3. But since then I am not getting the C# code support in visual studio any more. I mean that in my code they are no more colors or completion anymore. I received an error about C sharp compiler but now i can't find it is not poppin out anymore.

I realized that in the properties related to the text editor in VS2015 there is and error about Intellisense and advanced code style formatting and it says that there is an error loading these properties.

Please some help. At least help me to get the error message back.

答:
It is not about reinstalling properly visual studio or not it seems like when you moved to visual studio 2015 update 3
3 somethong went wrong.
To get back your C# support in the Editor

Open visual studio.

Open the tool menu

Extension and udpdates

There is most likely somethong in the queue. Do all of pending updates.

Enjoy your C# support


答:
Provided that .Select() will happen in order:

var orderedObjects = order.Split(',').Select(int.Parse).Select(index => objects.FirstOrDefault(obj => obj.id == index).ToList();

Title: Reordering a list from comma sepperated ID's


问:
Is there a way to take a screenshot of a failure automatically during Automation of a website?
All my automation scripts must run during the midnight and I see failures in the report the next day morning and not able to reproduce and my raised issues to developers are getting rejected as non-producible. I want to set up an environment which will be capable of taking screenshots of the web page after a failed step.
* Code is written in Gherkin Language
* We use default Mink functions and some custom PHP functions
* We use Gitlab and Gitlab runners for execution

I'm new to to Behat and PHP. So, I haven't tried anything yet.

Ideally I would love to see the screenshots of failures with the name of the image the particular line or some sort of unique identifier.

The Images can be saved to a repository [Cloud/gitlab/Local system]

答:
This did the job for me:</p>

```<code>public function takeScreenshotAfterFailedStep(AfterStepScope $scope) {

    try {

       $session =  $this->getSession();

       if (99 === $scope->getTestResult()->getResultCode()) {
          $stepName = $scope->getStep()->getText();
          $this->takeScreenshot($stepName);
          echo "\n\nYour test may have failed - ";
          echo "\nCurrent Page URL: ". $session->getCurrentUrl();
       }
    } catch(Exception $e) {

        $e_msg = "Something went wrong when taking screenshots";
        throw new Exception($e_msg, $e->getCode(), $e);
    }

}

public function takeScreenshot($stepName=null) {

    echo "The current working directory:  " . getcwd() . "\n";

    $filePath = getcwd();      // default path

    date_default_timezone_set('America/New_York');
    $fileName =   'screenshot-' . uniqid() . '_' . date('Y-m-d-H-i-s') .'.png';

    # if directory path is specified in Behat yml, use it.
    if (isset($this->parameters['screen_shot_path'])) {
       $filePath = $this->parameters['screen_shot_path'];
    }

    $this->saveScreenshot($fileName, $filePath);
    echo "\nScreenshot taken -> " . $fileName . "\n";
}
</code>```

Body:
This did the job for me:

public function takeScreenshotAfterFailedStep(AfterStepScope $scope) {

    try {

       $session =  $this->getSession();

       if (99 === $scope->getTestResult()->getResultCode()) {
          $stepName = $scope->getStep()->getText();
          $this->takeScreenshot($stepName);
          echo "\n\nYour test may have failed - ";
          echo "\nCurrent Page URL: ". $session->getCurrentUrl();
       }
    } catch(Exception $e) {

        $e_msg = "Something went wrong when taking screenshots";
        throw new Exception($e_msg, $e->getCode(), $e);
    }

}

public function takeScreenshot($stepName=null) {

    echo "The current working directory:  " . getcwd() . "\n";

    $filePath = getcwd();      // default path

    date_default_timezone_set('America/New_York');
    $fileName =   'screenshot-' . uniqid() . '_' . date('Y-m-d-H-i-s') .'.png';

    # if directory path is specified in Behat yml, use it.
    if (isset($this->parameters['screen_shot_path'])) {
       $filePath = $this->parameters['screen_shot_path'];
    }

    $this->saveScreenshot($fileName, $filePath);
    echo "\nScreenshot taken -> " . $fileName . "\n";
}


问:
What exactly is the "as-if" rule?
As the title says:

What exactly is the "as-if" rule?

A typical answer one would get is:

The rule that allows any and all code transformations that do not change the observable behavior of the program

From time to time, we keep getting behaviors from certain implementations, which are attributed to this rule. Many times wrongly.

So, what exactly is this rule? The standard does not clearly mention this rule as a section or paragraph, so what exactly falls under the purview of this rule?

To me, it seems like a grey area which is not defined in detail by the standard. Can someone elaborate on the details, citing the references from the standard?

Note: Tagging this as C and C++ both, because it is relevant to both languages.

答:
In C, C++, Ada, Java, SML... in any programming language well specified by describing the (usually many possible, non-deterministic) behavior(s) of a program (exposed to series of interactions on I/O ports), there is no distinct as-if rule.

An example of distinct rule is the one that says that a division by zero raises an exception (Ada, Caml) or a null dereference raises an exception (Java). You could change the rule to specify something else and you would end up with a different language (that some people would rather call a "dialect"(*). A distinct rule is there to specify some distinct uses of a programming language like a distinct grammatical rule cover some syntax constructs.

(*) A dialect according to some linguists is a language with an "army". in that context, that could mean a programming language without a committee and a specific industry of compiler editors.

The as-if rule is not a distinct rule; it doesn't cover any program in particular and is not even a rule that could be discussed, removed, or altered in any way: the so called "rule" simply reiterates that program semantics is defined, and can only be portably (universally) defined, in term of the visible interactions of an execution of the program with the "external" world.

The external world can be I/O interfaces (stdio), a GUI, even an interactive interpreter that output the resulting value of a pure applicative language. In C and C++ is includes the (vaguely specified) accesses to volatile objects, which is another way of saying that some objects at given point must be represented in memory strictly according to the ABI (Application Binary Interface) without ever mentioning the ABI explicitly.

The definition of what is a trace of execution, also called the visible or observable behavior defines what is meant by "as-if rule". The as-if rule tries to explain it, but by doing so, it confuses people more than it clarifies things as it gives the expression of being an additional semantic rule giving more leeway to the implementation.

Summary:

The so called "as-if rule" does not relax any constraints on implementations.

You cannot remove the as-if rule in any programming language specified in term of visible behavior (execution traces composed for interaction with the external world) to get a distinct dialect.

You cannot add the as-if rule to any programming language not specified in term of visible behavior.

Title: What exactly is the "as-if" rule?


问:
How to "slice" a 2D array into a 3D array
I have an array that looks like:
test = np.zeros (7110, 514)

I need to "unpack" the first 90 values (rows) into the first value of the second dimension, the second 90 values (rows) into the second value of the second dimension, etc, so that the desired output will have shape:

desired_output = np.zeros(90, 79, 514)

I have tried something like:

```<code>a = np.split(test, 90, axis=1)
test1 = np.reshape(a, (79,90, 514))
</code>```

but it just dragged me down a rabbit whole... Thanks for any help!

答:
I don't know if I understand the question, do you have 7110 rows of 514 elements each and want to "group" the 7110 rows into 90 x 79 rows?

Because then you could do something like this:

```<code>>>> np.array(range(24)).reshape((6, 4))
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])
</code>```

These are 6 rows of 4 elements each.

```<code>>>> np.array(range(24)).reshape((6, 4)).reshape(3, 2, 4)
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])
</code>```

We keep the rows as they are, but instead of 6 rows, we get 3x2 rows.

So the code you would need is just:

```<code>desired_output = a.reshape(90, 79, 514)
</code>```

Body:
I have an array that looks like:
test = np.zeros (7110, 514)

I need to "unpack" the first 90 values (rows) into the first value of the second dimension, the second 90 values (rows) into the second value of the second dimension, etc, so that the desired output will have shape:

desired_output = np.zeros(90, 79, 514)

I have tried something like:

a = np.split(test, 90, axis=1)
test1 = np.reshape(a, (79,90, 514))

but it just dragged me down a rabbit whole... Thanks for any help!

Body:
I don't know if I understand the question, do you have 7110 rows of 514 elements each and want to "group" the 7110 rows into 90 x 79 rows?

Because then you could do something like this:

>>> np.array(range(24)).reshape((6, 4))
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

These are 6 rows of 4 elements each.

>>> np.array(range(24)).reshape((6, 4)).reshape(3, 2, 4)
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7]],

       [[ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23]]])

We keep the rows as they are, but instead of 6 rows, we get 3x2 rows.

So the code you would need is just:

desired_output = a.reshape(90, 79, 514)


问:
asmx wsdl loading forever
I have a web service application which has suddenly stopped working.  I have enabled directory browsing in IIS, and can view the application directory.  I can view the xml files within the application directory, but I cannot view the .config files, nor can I view the wsdls of any of the web services.  When I try to browse to http://server/app/service.asmx?wsdl, the browser stays in the "loading" state forever.

Any ideas what might have gone wrong here?

答:
Regarding the first question about loading, are you able to browse to the site on the server?

IIS protects Web.config files by default and will typically return a "This type of page is not served" error message. This is a good thing which will keep your connection strings and what not from being casually viewed. There is more information about allowing exceptions for this here.

Title: asmx wsdl loading forever

OwnerDisplayName: Dustin Venegas

ContentLicense: CC BY-SA 2.5


问:
Vector option in Java
I am using vector of object. My issue is the removal from vector is expensive operation( O(n^2)). What would be the replacement of vector in Java. In my uses addition and removal is extensively happens.

i am C++ person don't know much Java

答: First of all, Vector removal time complexity is O(n) not O(n^2). If you want more performant class, you should choose LinkedList. Its time complexity is constant. </p>

Title: Vector option in Java


问:
Unable to fetch JSON as String from a REST API
I am trying to fetch JSON from a REST API as a string.

I am using retrofit with scalarConverter for that purpose. I am able to pass the URL to fetch and my retrofit instance is also created successfully but I am not getting any response from the server.
PS: there is no request on the server, so that means my request is not going out from my machine.

I am new to android, kindly help me.

Retrofit instance creation:

```<code>Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(base)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
jsonApi jsonapi=retrofit.create(jsonApi.class);
Call<String> stringcall=jsonapi.getStringResponse(speech);
</code>```

jsonApi interface:

```<code>public interface jsonApi {
    @GET
    Call<String> getStringResponse(@Url String url);
}
</code>```

base: it is the base URL

speech: it is a variable containing rest of the URL to be processed.

when I run, the app gets stuck here with this message being displayed in Run Tab:

```<code>W/OpenGLRenderer: Fail to change FontRenderer cache size, it already initialized
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
</code>```

答:
With the below line

```<code>Call<String> stringcall=jsonapi.getStringResponse(speech);
</code>```

you just get a Call object which is a representation of the HTTP request, and just by that, the request isn't executed. You need to use this object and call the execute method to make a synchronous request or the enqueue method to make an asynchronous request.

So in case you want to make a sync request, try the below:

```<code>Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(base)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
jsonApi jsonapi=retrofit.create(jsonApi.class);
Call<String> stringcall=jsonapi.getStringResponse(speech);
try {
    Response<String> response = stringcall.execute();
    String result = response.body();
} catch (Exception ex) {
    //handle exception
}
</code>```

The documentation of Call interface is here, for your reference.

Body:
I am trying to fetch JSON from a REST API as a string.

I am using retrofit with scalarConverter for that purpose. I am able to pass the URL to fetch and my retrofit instance is also created successfully but I am not getting any response from the server.
PS: there is no request on the server, so that means my request is not going out from my machine.

I am new to android, kindly help me.

Retrofit instance creation:

Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(base)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
jsonApi jsonapi=retrofit.create(jsonApi.class);
Call<String> stringcall=jsonapi.getStringResponse(speech);

jsonApi interface:

public interface jsonApi {
    @GET
    Call<String> getStringResponse(@Url String url);
}

base: it is the base URL

speech: it is a variable containing rest of the URL to be processed.

when I run, the app gets stuck here with this message being displayed in Run Tab:

W/OpenGLRenderer: Fail to change FontRenderer cache size, it already initialized
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView

Body:
With the below line

Call<String> stringcall=jsonapi.getStringResponse(speech);

you just get a Call object which is a representation of the HTTP request, and just by that, the request isn't executed. You need to use this object and call the execute method to make a synchronous request or the enqueue method to make an asynchronous request.

So in case you want to make a sync request, try the below:

Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(base)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();
jsonApi jsonapi=retrofit.create(jsonApi.class);
Call<String> stringcall=jsonapi.getStringResponse(speech);
try {
    Response<String> response = stringcall.execute();
    String result = response.body();
} catch (Exception ex) {
    //handle exception
}

The documentation of Call interface is here, for your reference.


问:
Alter table structure without violating primary key and unique constraints
Here is a logical model that I have.

Below are table structures and their constraints

Doctor

```<code>CREATE TABLE doctor (
    doctor_id      NUMBER(4) NOT NULL,
    doctor_title   VARCHAR2(2) NOT NULL,
    doctor_fname   VARCHAR2(50),
    doctor_lname   VARCHAR2(50),
    doctor_phone   CHAR(10) NOT NULL
);
ALTER TABLE doctor ADD CONSTRAINT doctor_pk PRIMARY KEY ( doctor_id );
</code>```

Procedure

```<code>CREATE TABLE procedure (
    proc_code          NUMBER(5) NOT NULL,
    proc_name          VARCHAR2(100) NOT NULL,
    proc_description   VARCHAR2(300) NOT NULL,
    proc_time          NUMBER(3) NOT NULL,
    proc_std_cost      NUMBER(7, 2) NOT NULL
);

ALTER TABLE procedure ADD CONSTRAINT procedure_pk PRIMARY KEY ( proc_code );

ALTER TABLE procedure ADD CONSTRAINT proc_name_unq UNIQUE ( proc_name );
</code>```

Admission

```<code>CREATE TABLE admission (
    adm_no          NUMBER(6) NOT NULL,
    adm_date_time   DATE NOT NULL,
    adm_discharge   DATE,
    patient_id      NUMBER(6) NOT NULL,
    doctor_id       NUMBER(4) NOT NULL
);

ALTER TABLE admission ADD CONSTRAINT admission_pk PRIMARY KEY ( adm_no );    --surrogate key

ALTER TABLE admission ADD CONSTRAINT admission_nk UNIQUE ( patient_id,
                                                           adm_date_time );
</code>```

Admission Procedure

```<code>CREATE TABLE adm_prc (
    adprc_no           NUMBER(7) NOT NULL,
    adprc_date_time    DATE NOT NULL,
    adprc_pat_cost     NUMBER(7, 2) NOT NULL,
    adprc_items_cost   NUMBER(6, 2) NOT NULL,
    adm_no             NUMBER(6) NOT NULL,
    proc_code          NUMBER(5) NOT NULL,
    request_dr_id      NUMBER(4) NOT NULL,
    perform_dr_id      NUMBER(4)
);
ALTER TABLE adm_prc ADD CONSTRAINT adm_prc_pk PRIMARY KEY ( adprc_no );    --surrogate key
ALTER TABLE adm_prc ADD CONSTRAINT adm_prc_nk UNIQUE ( adprc_date_time,
                                                       adm_no );
ALTER TABLE adm_prc
    ADD CONSTRAINT admission_admprc FOREIGN KEY ( adm_no )
        REFERENCES admission ( adm_no );
ALTER TABLE adm_prc
    ADD CONSTRAINT doctor_performadmprc FOREIGN KEY ( perform_dr_id )
        REFERENCES doctor ( doctor_id );
ALTER TABLE adm_prc
    ADD CONSTRAINT doctor_requestadmprc FOREIGN KEY ( request_dr_id )
        REFERENCES doctor ( doctor_id );
</code>```

Item Treatment

```<code>CREATE TABLE item_treatment (
    adprc_no             NUMBER(7) NOT NULL,
    item_code            CHAR(5) NOT NULL,
    it_qty_used          NUMBER(2) NOT NULL,
    it_item_total_cost   NUMBER(8, 2) NOT NULL
);

ALTER TABLE item_treatment
    ADD CONSTRAINT item_treatment_pk PRIMARY KEY ( adprc_no,item_code);
ALTER TABLE item_treatment
    ADD CONSTRAINT admprc_itemtreatment FOREIGN KEY ( adprc_no )
        REFERENCES adm_prc ( adprc_no );
ALTER TABLE item_treatment
    ADD CONSTRAINT admprc_itemtreatment FOREIGN KEY ( adprc_no )
        REFERENCES adm_prc ( adprc_no );
ALTER TABLE item_treatment
    ADD CONSTRAINT item_itemtreatment FOREIGN KEY ( item_code )
        REFERENCES item ( item_code );
</code>```

In a fictitious hospital, every time an admission procedure is completed for a patient admission, the lead doctor who performed the procedure is recorded under the perform_dr_id in adm_prc table. Even if a team of doctors perform the procedure, only the lead doctor is recorded.

The hospital now wishes to record all the doctors who performed in the admission procedure including an Ancillary doctor (assisting doctor).

I have altered the adm_prc table to include ancillary doctors

```<code>ALTER TABLE ADM_PRC ADD ANCILLARY_DR_ID NUMBER(4);
ALTER TABLE ADM_PRC
    ADD CONSTRAINT DOCTOR_PERFORM_ANCILLARY FOREIGN KEY ( ANCILLARY_DR_ID )
        REFERENCES DOCTOR ( DOCTOR_ID );
</code>```

I need to change the structure of the database is such a way that, there should be multiple records for the same admission procedure as there can be many doctors assisting in a single admission procedure. For example, I should be able to insert the following records in adm_prc table

```<code>adprc_no  adprc_date_time  adprc_pat_cost  adprc_items_cost  adm_no  proc_code
 request_dr_id  perform_dr_id  ancillary_dr_id
-----------------------------------------------------------------------------------------------------------------------------
1         14/03/2019       100             100               1234    1234
 10             10             12
1         14/03/2019       100             100               1234    1234
 10             10             13
</code>```

However, this violates primary key constraint adm_prc_pk

I'm stuck at this point and unable to proceed further. Would appreciate if someone could point me in the right direction.

答:
You should create a new satellite table (say ADM_PRC_DR_DTLS) to hold adprc_no and corresponding dr_id details.
adprc_no of ADM_PRC_DR_DTLS would refer to the ADM_PRC's adprc_no as a Foreign Key.</p>

Body:
Here is a logical model that I have.

Below are table structures and their constraints

Doctor

CREATE TABLE doctor (
    doctor_id      NUMBER(4) NOT NULL,
    doctor_title   VARCHAR2(2) NOT NULL,
    doctor_fname   VARCHAR2(50),
    doctor_lname   VARCHAR2(50),
    doctor_phone   CHAR(10) NOT NULL
);
ALTER TABLE doctor ADD CONSTRAINT doctor_pk PRIMARY KEY ( doctor_id );

Procedure

CREATE TABLE procedure (
    proc_code          NUMBER(5) NOT NULL,
    proc_name          VARCHAR2(100) NOT NULL,
    proc_description   VARCHAR2(300) NOT NULL,
    proc_time          NUMBER(3) NOT NULL,
    proc_std_cost      NUMBER(7, 2) NOT NULL
);

ALTER TABLE procedure ADD CONSTRAINT procedure_pk PRIMARY KEY ( proc_code );

ALTER TABLE procedure ADD CONSTRAINT proc_name_unq UNIQUE ( proc_name );

Admission

CREATE TABLE admission (
    adm_no          NUMBER(6) NOT NULL,
    adm_date_time   DATE NOT NULL,
    adm_discharge   DATE,
    patient_id      NUMBER(6) NOT NULL,
    doctor_id       NUMBER(4) NOT NULL
);

ALTER TABLE admission ADD CONSTRAINT admission_pk PRIMARY KEY ( adm_no );    --surrogate key

ALTER TABLE admission ADD CONSTRAINT admission_nk UNIQUE ( patient_id,
                                                           adm_date_time );

Admission Procedure

CREATE TABLE adm_prc (
    adprc_no           NUMBER(7) NOT NULL,
    adprc_date_time    DATE NOT NULL,
    adprc_pat_cost     NUMBER(7, 2) NOT NULL,
    adprc_items_cost   NUMBER(6, 2) NOT NULL,
    adm_no             NUMBER(6) NOT NULL,
    proc_code          NUMBER(5) NOT NULL,
    request_dr_id      NUMBER(4) NOT NULL,
    perform_dr_id      NUMBER(4)
);
ALTER TABLE adm_prc ADD CONSTRAINT adm_prc_pk PRIMARY KEY ( adprc_no );    --surrogate key
ALTER TABLE adm_prc ADD CONSTRAINT adm_prc_nk UNIQUE ( adprc_date_time,
                                                       adm_no );
ALTER TABLE adm_prc
    ADD CONSTRAINT admission_admprc FOREIGN KEY ( adm_no )
        REFERENCES admission ( adm_no );
ALTER TABLE adm_prc
    ADD CONSTRAINT doctor_performadmprc FOREIGN KEY ( perform_dr_id )
        REFERENCES doctor ( doctor_id );
ALTER TABLE adm_prc
    ADD CONSTRAINT doctor_requestadmprc FOREIGN KEY ( request_dr_id )
        REFERENCES doctor ( doctor_id );

Item Treatment

CREATE TABLE item_treatment (
    adprc_no             NUMBER(7) NOT NULL,
    item_code            CHAR(5) NOT NULL,
    it_qty_used          NUMBER(2) NOT NULL,
    it_item_total_cost   NUMBER(8, 2) NOT NULL
);

ALTER TABLE item_treatment
    ADD CONSTRAINT item_treatment_pk PRIMARY KEY ( adprc_no,item_code);
ALTER TABLE item_treatment
    ADD CONSTRAINT admprc_itemtreatment FOREIGN KEY ( adprc_no )
        REFERENCES adm_prc ( adprc_no );
ALTER TABLE item_treatment
    ADD CONSTRAINT admprc_itemtreatment FOREIGN KEY ( adprc_no )
        REFERENCES adm_prc ( adprc_no );
ALTER TABLE item_treatment
    ADD CONSTRAINT item_itemtreatment FOREIGN KEY ( item_code )
        REFERENCES item ( item_code );

In a fictitious hospital, every time an admission procedure is completed for a patient admission, the lead doctor who performed the procedure is recorded under the perform_dr_id in adm_prc table. Even if a team of doctors perform the procedure, only the lead doctor is recorded.

The hospital now wishes to record all the doctors who performed in the admission procedure including an Ancillary doctor (assisting doctor).

I have altered the adm_prc table to include ancillary doctors

ALTER TABLE ADM_PRC ADD ANCILLARY_DR_ID NUMBER(4);
ALTER TABLE ADM_PRC
    ADD CONSTRAINT DOCTOR_PERFORM_ANCILLARY FOREIGN KEY ( ANCILLARY_DR_ID )
        REFERENCES DOCTOR ( DOCTOR_ID );

I need to change the structure of the database is such a way that, there should be multiple records for the same admission procedure as there can be many doctors assisting in a single admission procedure. For example, I should be able to insert the following records in adm_prc table

adprc_no  adprc_date_time  adprc_pat_cost  adprc_items_cost  adm_no  proc_code
 request_dr_id  perform_dr_id  ancillary_dr_id
-----------------------------------------------------------------------------------------------------------------------------
1         14/03/2019       100             100               1234    1234
 10             10             12
1         14/03/2019       100             100               1234    1234
 10             10             13

However, this violates primary key constraint adm_prc_pk

I'm stuck at this point and unable to proceed further. Would appreciate if someone could point me in the right direction.


问:
What is the correct format and sequence to acquire the correct token for LinkedIn API V2?
Our LinkedIn APP no longer works with the evolution of V2.   I have tried a couple of times and failed to create the correct token. I am seeking help to create the correct authorization link to get the token.  Error from the App is currently "Empty oauth2 access token"

I created a new LinkedIn app to replace our old one.  I have tried to follow the instructions from LinkedIn and Microsoft but my efforts have produced the following error

My most recent attempt was:

https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=78xaqf0ereiisy&redirect_uri=https://www.gachina.com&state=gachina&scope=r_emailaddress r_liteprofile w_member_social

I received:  https://www.gachina.com/?code=AQS65Njp1F9-L-mKSrAJKZeQ-ij2OX7wboTc30-hrfQIwwJ0yfWd4FBqxLl-ZXHmL5HurKud4t9WcGeHB62EfPNcy3ddoqT1LztUHhR59iL-Q8f9WLrX03d9e3OCTmY-3vR8a_4ENeIN0GFpeLy7DKRDmuUNcQ82UwScqhApdtwzEBw-_Y0duYG87Lc1KQ&state=gachina

then I used the format shown here:

https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow

https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code={authorization_code_from_step2_response}&redirect_uri=hhttps%3A%2F%2Fdev.example.com%2Fauth%2Flinkedin%2Fcallback&client_id={your_client_id}&client_secret={your_client_secret}

with

https://www.linkedin.com/oauth/v2/accessToken?grant_type=authorization_code&code=AQS65Njp1F9-L-mKSrAJKZeQ-ij2OX7wboTc30-hrfQIwwJ0yfWd4FBqxLl-ZXHmL5HurKud4t9WcGeHB62EfPNcy3ddoqT1LztUHhR59iL-Q8f9WLrX03d9e3OCTmY-3vR8a_4ENeIN0GFpeLy7DKRDmuUNcQ82UwScqhApdtwzEBw-_Y0duYG87Lc1KQ&redirect_uri=https://www.gachina.com/auth/Linkedin/callback&client_id=78xaqf0ereiisy&client_secret={client_secret}

but I receive the following upon submitting the above link with our {client secret} in place

{"error":"invalid_redirect_uri","error_description":"Unable to retrieve access token: appid/redirect uri/code verifier does not match authorization code. Or authorization code expired. Or external member binding exists"}

I am doing all of this within minutes. So, I do not believe there is an expiration of code.

Can you help identify the error of steps or code to receive a Token?

答:
This will return the access token</p>

```<code>$params = array('grant_type' => 'authorization_code',
            'client_id' => $this->api_key,
            'client_secret' => $this->api_secret,
            'code' => $_GET['code'],
            'redirect_uri' => base_url().$this->redirect,
        );
        // Access Token request
        $url = 'https://www.linkedin.com/oauth/v2/accessToken?' . http_build_query($params);
        $data_len = strlen(http_build_query($params));
        // Tell streams to make a POST request
        $context = stream_context_create(
                array('http' =>
                    array('method' => 'POST','header'=> 'Content-Length: 0'
                    )
                )
        );

        // Retrieve access token information
        $response = file_get_contents($url, false, $context);
        $token = json_decode($response);
        return $token->access_token;
</code>```

Body:
This will return the access token

$params = array('grant_type' => 'authorization_code',
            'client_id' => $this->api_key,
            'client_secret' => $this->api_secret,
            'code' => $_GET['code'],
            'redirect_uri' => base_url().$this->redirect,
        );
        // Access Token request
        $url = 'https://www.linkedin.com/oauth/v2/accessToken?' . http_build_query($params);
        $data_len = strlen(http_build_query($params));
        // Tell streams to make a POST request
        $context = stream_context_create(
                array('http' =>
                    array('method' => 'POST','header'=> 'Content-Length: 0'
                    )
                )
        );

        // Retrieve access token information
        $response = file_get_contents($url, false, $context);
        $token = json_decode($response);
        return $token->access_token;


问:
"openssl/ssl.h: No such file or directory" during Installation of Git
Trying to install git on the Unix and Linux machines based on the instructions on Installing Git blog, and it is failing with the below error

```<code>make prefix=/usr/local all
GIT_VERSION = 1.8.3.4
    * new build flags
    CC credential-store.o
In file included from cache.h:4,
                 from credential-store.c:1:
git-compat-util.h:221:25: warning: openssl/ssl.h: No such file or directory
git-compat-util.h:222:25: warning: openssl/err.h: No such file or directory
In file included from credential-store.c:1:
cache.h:11:21: warning: openssl/sha.h: No such file or directory
cache.h:19:18: warning: zlib.h: No such file or directory
In file included from credential-store.c:1:
cache.h:21: syntax error before "z_stream"
cache.h:21: warning: no semicolon at end of struct or union
cache.h:28: syntax error before '}' token
cache.h:28: warning: type defaults to `int' in declaration of `git_zstream'
cache.h:28: warning: data definition has no type or storage class
cache.h:30: syntax error before '*' token
cache.h:31: syntax error before '*' token
cache.h:32: syntax error before '*' token
cache.h:33: syntax error before '*' token
cache.h:35: syntax error before '*' token
cache.h:36: syntax error before '*' token
cache.h:37: syntax error before '*' token
cache.h:38: syntax error before '*' token
cache.h:39: syntax error before '*' token
cache.h:40: syntax error before '*' token
cache.h:41: syntax error before '*' token
cache.h:42: syntax error before '*' token
cache.h:769: syntax error before '*' token
make: *** [credential-store.o] Error 1
</code>```

I know this is because of the missing libraries for openssl, but I am unable to get these libraries.

I do not have yum/apt-get on my machines to run the below commands as suggested:

```<code>$ yum install curl-devel expat-devel gettext-devel \
  openssl-devel zlib-devel

$ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \
  libz-dev libssl-dev
</code>```

What do I do get these libraries on these machines. These machines do not have internet access, I can do a scp if required. Any suggestions.

答:
If you can't access yum, apt-get etc (such as being on a cluster machine with no sudo access), install a new version of openssl locally and manually as follows:

Get the source code, unpack it, enter the directory and make a build directory (very important):

```<code>wget https://www.openssl.org/source/openssl-1.0.2r.tar.gz
tar -xvzf openssl-1.0.2r.tar.gz
cd openssl-1.0.2r
mkdir builddir
</code>```

Configure to your local build destination (make sure its different to your source directory, don't use just /home/yourdir/openssl-1.0.2r/), make and install:

```<code>./config --prefix=/home/yourdir/openssl-1.0.2r/builddir --openssldir=/home/yourdir/openssl-1.0.2r/builddir
make
make install
</code>```

Add the bin and library paths from the build directory to the appropriate variables in your your shell config file (i.e. ~/.bashrc), and source it:

```<code>export PATH=/home/yourdir/openssl-1.0.2r/builddir/bin:$PATH
LD_LIBRARY_PATH="/your/other/dirs/libs:/home/yourdir/openssl-1.0.2r/builddir/lib:"
source ~/.bashrc
</code>```

OpenSSL should now be in your new directory by default:

```<code>which openssl
> /home/yourdir/openssl-1.0.2r/builddir/bin/openssl
</code>```

Now try and reinstall git, perhaps with make distclean.

Body:
Trying to install git on the Unix and Linux machines based on the instructions on Installing Git blog, and it is failing with the below error

make prefix=/usr/local all
GIT_VERSION = 1.8.3.4
    * new build flags
    CC credential-store.o
In file included from cache.h:4,
                 from credential-store.c:1:
git-compat-util.h:221:25: warning: openssl/ssl.h: No such file or directory
git-compat-util.h:222:25: warning: openssl/err.h: No such file or directory
In file included from credential-store.c:1:
cache.h:11:21: warning: openssl/sha.h: No such file or directory
cache.h:19:18: warning: zlib.h: No such file or directory
In file included from credential-store.c:1:
cache.h:21: syntax error before "z_stream"
cache.h:21: warning: no semicolon at end of struct or union
cache.h:28: syntax error before '}' token
cache.h:28: warning: type defaults to `int' in declaration of `git_zstream'
cache.h:28: warning: data definition has no type or storage class
cache.h:30: syntax error before '*' token
cache.h:31: syntax error before '*' token
cache.h:32: syntax error before '*' token
cache.h:33: syntax error before '*' token
cache.h:35: syntax error before '*' token
cache.h:36: syntax error before '*' token
cache.h:37: syntax error before '*' token
cache.h:38: syntax error before '*' token
cache.h:39: syntax error before '*' token
cache.h:40: syntax error before '*' token
cache.h:41: syntax error before '*' token
cache.h:42: syntax error before '*' token
cache.h:769: syntax error before '*' token
make: *** [credential-store.o] Error 1

I know this is because of the missing libraries for openssl, but I am unable to get these libraries.

I do not have yum/apt-get on my machines to run the below commands as suggested:

$ yum install curl-devel expat-devel gettext-devel \
  openssl-devel zlib-devel

$ apt-get install libcurl4-gnutls-dev libexpat1-dev gettext \
  libz-dev libssl-dev

What do I do get these libraries on these machines. These machines do not have internet access, I can do a scp if required. Any suggestions.

Body:
If you can't access yum, apt-get etc (such as being on a cluster machine with no sudo access), install a new version of openssl locally and manually as follows:

Get the source code, unpack it, enter the directory and make a build directory (very important):

wget https://www.openssl.org/source/openssl-1.0.2r.tar.gz
tar -xvzf openssl-1.0.2r.tar.gz
cd openssl-1.0.2r
mkdir builddir

Configure to your local build destination (make sure its different to your source directory, don't use just /home/yourdir/openssl-1.0.2r/), make and install:

./config --prefix=/home/yourdir/openssl-1.0.2r/builddir --openssldir=/home/yourdir/openssl-1.0.2r/builddir
make
make install

Add the bin and library paths from the build directory to the appropriate variables in your your shell config file (i.e. ~/.bashrc), and source it:

export PATH=/home/yourdir/openssl-1.0.2r/builddir/bin:$PATH
LD_LIBRARY_PATH="/your/other/dirs/libs:/home/yourdir/openssl-1.0.2r/builddir/lib:"
source ~/.bashrc

OpenSSL should now be in your new directory by default:

which openssl
> /home/yourdir/openssl-1.0.2r/builddir/bin/openssl

Now try and reinstall git, perhaps with make distclean.


问:
Name of obscuring element changes ID
I'm writing a testcase in Selenium using Visual Studio.

In several testcases I need to wait for a temporary obscuring element to disappear. The problem is that the name of this element changes its "number ID".

This is the name of the obscuring element:

```<code>.mat-snack-bar-container.ng-tns-c36-13.ng-trigger.ng-trigger-state.snack-bar-success.mat-snack-bar-top.ng-star-inserted
</code>```

The part that always changes is this part: 36-13

I'm waiting for it to disappear like this:

```<code>wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector(".mat-snack-bar-container.ng-tns-c36-13.ng-trigger.ng-trigger-state.snack-bar-success.mat-snack-bar-top.ng-star-inserted")));
</code>```

Instead of me writing 9999 lines of code to cover every ID of this element. Is there a way to just write one line of code that looks for this ID in a scope between 00-00 to 99-99?

答:
Here is the solution to use begins with and ends with in css.

```<code>[class^='mat-snack-bar-container ng-tns-c'][class$='ng-trigger ng-trigger-state snack-bar-success mat-snack-bar-top ng-star-inserted']
</code>```

The below code will wait until the element invisible.

```<code>wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector("[class^='mat-snack-bar-container ng-tns-c'][class$='ng-trigger ng-trigger-state snack-bar-success mat-snack-bar-top ng-star-inserted']")));
</code>```

Title: Name of obscuring element changes ID

Body:
I'm writing a testcase in Selenium using Visual Studio.

In several testcases I need to wait for a temporary obscuring element to disappear. The problem is that the name of this element changes its "number ID".

This is the name of the obscuring element:

.mat-snack-bar-container.ng-tns-c36-13.ng-trigger.ng-trigger-state.snack-bar-success.mat-snack-bar-top.ng-star-inserted

The part that always changes is this part: 36-13

I'm waiting for it to disappear like this:

wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector(".mat-snack-bar-container.ng-tns-c36-13.ng-trigger.ng-trigger-state.snack-bar-success.mat-snack-bar-top.ng-star-inserted")));

Instead of me writing 9999 lines of code to cover every ID of this element. Is there a way to just write one line of code that looks for this ID in a scope between 00-00 to 99-99?

Body:
Here is the solution to use begins with and ends with in css.

[class^='mat-snack-bar-container ng-tns-c'][class$='ng-trigger ng-trigger-state snack-bar-success mat-snack-bar-top ng-star-inserted']

The below code will wait until the element invisible.

wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector("[class^='mat-snack-bar-container ng-tns-c'][class$='ng-trigger ng-trigger-state snack-bar-success mat-snack-bar-top ng-star-inserted']")));


问:
Show first ten characters, expand on click (or hover)
I have a HTML snippet which looks like this:

```<code>```
Traceback (most recent call last):
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
    output = self._execute_job_and_create_log()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
    return self.execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
    return self._execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
    port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
    self._session = self._make_session()
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
    session = factory(*args, **kwargs)
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
    raise FTPOSError(*exc_value.args, original_exception=exc_value)
FTPOSError: [Errno 110] Timeout
Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
```
</code>```

Since most users do not care for the details, I would like to hide the traceback and only show the first few characters.

The remaining text should only be visible if you expand the text.

This should be visible as hyperlink: "Traceback ...."

How to do this with?

(I can't modify the html, a JavaScript/jquery/CSS solution is needed)

答:
I just satisfied below conditions

I hide the content in pre tag  and only show the first few
characters.

Remaining text should only be visible if you expand the text.

pre{
 width: 11ch;
 height: 2ch;
 overflow: hidden;
 text-overflow: ellipsis;
 color:blue;
 text-decoration: underline;
}
pre:active{
 width: 100%;
  height: 100%;
  color:black;
 text-decoration: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>```
Traceback (most recent call last):
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
    output = self._execute_job_and_create_log()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
    return self.execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
    return self._execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
    port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
    self._session = self._make_session()
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
    session = factory(*args, **kwargs)
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
    raise FTPOSError(*exc_value.args, original_exception=exc_value)
FTPOSError: [Errno 110] Timeout
Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
```</code>```

Body:
I have a HTML snippet which looks like this:

Traceback (most recent call last):
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
    output = self._execute_job_and_create_log()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
    return self.execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
    return self._execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
    port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
    self._session = self._make_session()
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
    session = factory(*args, **kwargs)
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
    raise FTPOSError(*exc_value.args, original_exception=exc_value)
FTPOSError: [Errno 110] Timeout
Debugging info: ftputil 3.4, Python 2.7.13 (linux2)

Since most users do not care for the details, I would like to hide the traceback and only show the first few characters.

The remaining text should only be visible if you expand the text.

This should be visible as hyperlink: "Traceback ...."

How to do this with?

(I can't modify the html, a JavaScript/jquery/CSS solution is needed)

Body:
I just satisfied below conditions

I hide the content in pre tag  and only show the first few
characters.

Remaining text should only be visible if you expand the text.

pre{
 width: 11ch;
 height: 2ch;
 overflow: hidden;
 text-overflow: ellipsis;
 color:blue;
 text-decoration: underline;
}
pre:active{
 width: 100%;
  height: 100%;
  color:black;
 text-decoration: none;
}

<pre>
Traceback (most recent call last):
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 69, in execute_job_and_create_log
    output = self._execute_job_and_create_log()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 127, in _execute_job_and_create_log
    return self.execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 133, in execute_job_and_create_log__ftp
    return self._execute_job_and_create_log__ftp()
  File "/home/foobar_cok_p/src/foobar/foobar/models/job.py", line 140, in _execute_job_and_create_log__ftp
    port=self.job_group.remote.port, session_factory=SessionOnPort) as host:
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 72, in __init__
    self._session = self._make_session()
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/host.py", line 135, in _make_session
    session = factory(*args, **kwargs)
  File "/home/foobar_cok_p/lib/python2.7/site-packages/ftputil/error.py", line 151, in __exit__
    raise FTPOSError(*exc_value.args, original_exception=exc_value)
FTPOSError: [Errno 110] Timeout
Debugging info: ftputil 3.4, Python 2.7.13 (linux2)
</pre>


问:
jQuery beforeunload
I have been rewriting a classic asp Shopping basket using jQuery and Ajax. My problem is i want a logout functionality when the user closes the browser. this works but if i refresh the page the code to logout fires and i lose everything. I found this jquery code piece:

```<code>    var inFormOrLink = false;
    $('a').live('click', function () { inFormOrLink = true; });
    $('form').bind('submit', function () { inFormOrLink = true; });
    $(window).bind("beforeunload", function () {
        if (inFormOrLink == false) {
            $.post("logout.asp");
        }

    })
</code>```

Does anyone have any ideas how i can perform logout.asp ONLY when the user closes the browser OR indeed changes to a new website. But keep the information while in the Application (in IIS).

答: The beforeunload is fired when you leave/refresh the current page, and you can only successfully run code that blocks the browsing session, such as alert() or prompt().

Title: jQuery beforeunload

Body:
I have been rewriting a classic asp Shopping basket using jQuery and Ajax. My problem is i want a logout functionality when the user closes the browser. this works but if i refresh the page the code to logout fires and i lose everything. I found this jquery code piece:

    var inFormOrLink = false;
    $('a').live('click', function () { inFormOrLink = true; });
    $('form').bind('submit', function () { inFormOrLink = true; });
    $(window).bind("beforeunload", function () {
        if (inFormOrLink == false) {
            $.post("logout.asp");
        }

    })

Does anyone have any ideas how i can perform logout.asp ONLY when the user closes the browser OR indeed changes to a new website. But keep the information while in the Application (in IIS).


问:
Convert Raw Hdd Image From S3 Bucket to EC2 Image
I have raw hdd image in s3 bucket.
I would like to convert that image and deploy vm from that image i EC2 with boto3 or python.</p>

答:
The AWS VM Import documentation is at https://aws.amazon.com/ec2/vm-import/.

It explains the pre-requisites and the steps needed to import a VM.

The awscli supports import-image and boto3 supports import_volume.


问:
Navigate to fragment on FAB click (Navigation Architecture Components)
I have no idea how to, using the new navigation architecture component, navigate from my main screen (with a FloatingActionButton attatched to a BottomAppBar) to another screen without the app bar.

When I click the fab I want my next screen (fragment?) to slide in from the right.  The problem is where do I put my BottomAppBar?  If I put it in my MainActivity then I have the issue of the FloatingActionButton not having a NavController set.  I also cannot put my BottomAppBar in my Fragment.  I am at a loss.

答:
if you wanted to navigate to certain fragment (not the star one) in the beginning for some reason, and also you have to graphs for one activity, here is what I suggest:
this method will start activity

```<code>companion object {

        const val REQUEST_OR_CONFIRM = "request_or_confirm"
        const val IS_JUST_VIEW = "IS_JUST_VIEW"
        const val MODEL = "model"

        fun open(activity: Activity, isRequestOrConfirm: Boolean, isJustView: Boolean = false, model: DataModel? = null) {
            val intent = Intent(activity, HostActivity::class.java)
            intent.putExtra(REQUEST_OR_CONFIRM, isRequestOrConfirm)
            intent.putExtra(IS_JUST_VIEW, isJustView)
            intent.putExtra(MODEL, model)
            activity.startActivity(intent)
        }
    }
</code>```

and then in, onCreate method of Host Activity, first decide which graph to use and then pass the intent extras bundle so the start fragment can decide what to do:

```<code>override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_purchase_nav)
        if (intent.getBooleanExtra(REQUEST_OR_CONFIRM, true)) {
            findNavController(R.id.nav_host_fragment).setGraph(R.navigation.nav_first_scenario, intent.extras)
        } else {
            findNavController(R.id.nav_host_fragment).setGraph(R.navigation.nav_second_scenario, intent.extras)
        }
    }
</code>```

and here's how you can decide what to do in start fragment:

```<code>if (arguments != null && arguments!!.getBoolean(HostActivity.IS_JUST_VIEW)){
    navigateToYourDestinationFrag(arguments!!.getParcelable<DataModel>(HostActivity.MODEL))
}
</code>```

and then navigate like you would do normally:

```<code>private fun navigateToYourDestinationFrag(model: DataModel) {
        val action = StartFragmentDirections.actionStartFragmentToOtherFragment(model)
        findNavController().navigate(action)
    }
</code>```

here's how your graph might look in case you wanted to jump to the third fragment in the beginning

PS: make sure you will handle back button on the third fragment, here's a solution

UPDATE:
as EpicPandaForce mentioned, you can also start activities using Navigation Components:
to do that, first add the Activity to your existing graph, either by the + icon (which didn't work for me) or by manually adding in the xml:

```<code> <activity
        android:id="@+id/secondActivity"
        tools:layout="@layout/activity_second"
        android:name="com.amin.SecondActivity" >
    </activity>
</code>```

you can also add arguments and use them just like you would in a fragment, with navArgs()

```<code> <activity
        android:id="@+id/secondActivity"
        tools:layout="@layout/activity_second"
        android:name="com.amin.SecondActivity" >
        <argument
            android:name="testArgument"
            app:argType="string"
            android:defaultValue="helloWorld" />
    </activity>
</code>```

in koltin,here's how you would use the argument, First declare args with the type of generated class named after you activity, in this case SecondActivityArgs in top of your activity class:

```<code>val args: SecondActivityArgsby by navArgs()
</code>```

and then you can use it like this:

```<code>print(args.testArgument)
</code>```

Body:
if you wanted to navigate to certain fragment (not the star one) in the beginning for some reason, and also you have to graphs for one activity, here is what I suggest:
this method will start activity

companion object {

        const val REQUEST_OR_CONFIRM = "request_or_confirm"
        const val IS_JUST_VIEW = "IS_JUST_VIEW"
        const val MODEL = "model"

        fun open(activity: Activity, isRequestOrConfirm: Boolean, isJustView: Boolean = false, model: DataModel? = null) {
            val intent = Intent(activity, HostActivity::class.java)
            intent.putExtra(REQUEST_OR_CONFIRM, isRequestOrConfirm)
            intent.putExtra(IS_JUST_VIEW, isJustView)
            intent.putExtra(MODEL, model)
            activity.startActivity(intent)
        }
    }

and then in, onCreate method of Host Activity, first decide which graph to use and then pass the intent extras bundle so the start fragment can decide what to do:

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_purchase_nav)
        if (intent.getBooleanExtra(REQUEST_OR_CONFIRM, true)) {
            findNavController(R.id.nav_host_fragment).setGraph(R.navigation.nav_first_scenario, intent.extras)
        } else {
            findNavController(R.id.nav_host_fragment).setGraph(R.navigation.nav_second_scenario, intent.extras)
        }
    }

and here's how you can decide what to do in start fragment:

if (arguments != null && arguments!!.getBoolean(HostActivity.IS_JUST_VIEW)){
    navigateToYourDestinationFrag(arguments!!.getParcelable<DataModel>(HostActivity.MODEL))
}

and then navigate like you would do normally:

private fun navigateToYourDestinationFrag(model: DataModel) {
        val action = StartFragmentDirections.actionStartFragmentToOtherFragment(model)
        findNavController().navigate(action)
    }

here's how your graph might look in case you wanted to jump to the third fragment in the beginning

PS: make sure you will handle back button on the third fragment, here's a solution

UPDATE:
as EpicPandaForce mentioned, you can also start activities using Navigation Components:
to do that, first add the Activity to your existing graph, either by the + icon (which didn't work for me) or by manually adding in the xml:

 <activity
        android:id="@+id/secondActivity"
        tools:layout="@layout/activity_second"
        android:name="com.amin.SecondActivity" >
    </activity>

you can also add arguments and use them just like you would in a fragment, with navArgs()

 <activity
        android:id="@+id/secondActivity"
        tools:layout="@layout/activity_second"
        android:name="com.amin.SecondActivity" >
        <argument
            android:name="testArgument"
            app:argType="string"
            android:defaultValue="helloWorld" />
    </activity>

in koltin,here's how you would use the argument, First declare args with the type of generated class named after you activity, in this case SecondActivityArgs in top of your activity class:

val args: SecondActivityArgsby by navArgs()

and then you can use it like this:

print(args.testArgument)


问:
Error deploying IAM role in Google Deployment Manager
I am trying to assign a custom IAM role to a user (google account) in a GCP Project via Deployment Manager but received a 403 Error code.
I have followed the sample provided in the Google Cloud Platform repo:
https://github.com/GoogleCloudPlatform/deploymentmanager-samples/tree/master/community/cloud-foundation/templates/iam_member

Basically I created a configuration YAML file with the following content:

```<code>  - path: ../iam_member.py
    name: iam_member.py

resources:
  - name: iam-member-oval-unity-test-0
    type: iam_member.py
    properties:
      projectId: oval-unity-88908
      type: string
      roles:
        - role: roles/GARawDataViewer
          members:
            - user:<USER_EMAIL>
</code>```

GARawDataViewer is a custom role created in the project oval-unity-88908 and  is the value of the user email address to whom I am trying to assign the custom IAM role.

Finally, I deployed running the following command:

```<code>gcloud deployment-manager deployments create deployment-oval-unity-member-test --config examples/oval_unity_member.yaml
</code>```

After running the gcloud deployment-manager I received the following error message:

```<code>- code: CONDITION_NOT_MET
  location: /deployments/deployment-oval-unity-member-test/resources/get-iam-policy-iam-member-oval-unity-test-0-0-0->$.properties->$.policy
  message: |-
    InputMapping for field [policy] for method [setIamPolicy] could not be set from input, mapping was: [$.gcpIamMemberBinding($.intent, $.inputs.policy.response, $.resource.properties)], and evaluation context was:
    {
      "deployment" : {
        "id" : 4858392305054927640,
        "name" : "deployment-oval-unity-member-test"
      },
      "extensions" : {
        "EnableAdditionalJsonPathFunctions" : true,
        "EnableGoogleTypeProviderFunctionsExperiment" : true
      },
      "inputs" : {
        "policy" : {
          "error" : {
            "code" : "403",
            "message" : "{\"code\":403,\"message\":\"The caller does not have permission\",\"status\":\"PERMISSION_DENIED\",\"statusMessage\":\"Forbidden\",\"requestPath\":\"https://cloudresourcemanager.googleapis.com/v1/projects/oval-unity-88908:getIamPolicy\",\"httpMethod\":\"POST\"}"
          }
        }
      },
      "intent" : "CREATE",
      "matches" : [ ],
      "project" : "dm-creation-project-0",
      "requestId" : "f3c7f0c4-1ff7-3e26-a060-b0adc068866d",
      "resource" : {
        "name" : "get-iam-policy-iam-member-oval-unity-test-0-0-0",
        "previous" : { },
        "properties" : {
          "member" : "<USER_EMAIL_ADDRESS!>",
          "resource" : "oval-unity-88908",
          "role" : "roles/GARawDataViewer"
        },
        "self" : { }
      }
    }
    Error was:
    Parameter for gcpIamMemberBinding at position 1 is not of type map, value was [null]
</code>```

The interesting thing is that I have been able to deploy successfully assigning a predefined role like 'editor': roles/editor, but it is failing using a custom role.

I have even tried using the full path to the custom role: projects/oval-unity-88908/roles/GARawDataViewer
but still showing the same error.

Do you have any idea how could I solve this issue?
Thanks in advance!

答:
The issue might be, that you did not gave the service account which is used by the deployment manager the proper rights to handle IAM things. As described here you can possibly fix this issue by completing the following steps:

Go to the IAM page in the GCP Console of your project.

If prompted, select your project from the list.

Look for the Google APIs service account, which has the email address in the following format: [PROJECT_NUMBER]@cloudservices.gserviceaccount.com.

Grant the APIs service account the roles/owner roles

Let me know if you need further help!

Body:
I am trying to assign a custom IAM role to a user (google account) in a GCP Project via Deployment Manager but received a 403 Error code.
I have followed the sample provided in the Google Cloud Platform repo:
https://github.com/GoogleCloudPlatform/deploymentmanager-samples/tree/master/community/cloud-foundation/templates/iam_member

Basically I created a configuration YAML file with the following content:

  - path: ../iam_member.py
    name: iam_member.py

resources:
  - name: iam-member-oval-unity-test-0
    type: iam_member.py
    properties:
      projectId: oval-unity-88908
      type: string
      roles:
        - role: roles/GARawDataViewer
          members:
            - user:<USER_EMAIL>

GARawDataViewer is a custom role created in the project oval-unity-88908 and  is the value of the user email address to whom I am trying to assign the custom IAM role.

Finally, I deployed running the following command:

gcloud deployment-manager deployments create deployment-oval-unity-member-test --config examples/oval_unity_member.yaml

After running the gcloud deployment-manager I received the following error message:

- code: CONDITION_NOT_MET
  location: /deployments/deployment-oval-unity-member-test/resources/get-iam-policy-iam-member-oval-unity-test-0-0-0->$.properties->$.policy
  message: |-
    InputMapping for field [policy] for method [setIamPolicy] could not be set from input, mapping was: [$.gcpIamMemberBinding($.intent, $.inputs.policy.response, $.resource.properties)], and evaluation context was:
    {
      "deployment" : {
        "id" : 4858392305054927640,
        "name" : "deployment-oval-unity-member-test"
      },
      "extensions" : {
        "EnableAdditionalJsonPathFunctions" : true,
        "EnableGoogleTypeProviderFunctionsExperiment" : true
      },
      "inputs" : {
        "policy" : {
          "error" : {
            "code" : "403",
            "message" : "{\"code\":403,\"message\":\"The caller does not have permission\",\"status\":\"PERMISSION_DENIED\",\"statusMessage\":\"Forbidden\",\"requestPath\":\"https://cloudresourcemanager.googleapis.com/v1/projects/oval-unity-88908:getIamPolicy\",\"httpMethod\":\"POST\"}"
          }
        }
      },
      "intent" : "CREATE",
      "matches" : [ ],
      "project" : "dm-creation-project-0",
      "requestId" : "f3c7f0c4-1ff7-3e26-a060-b0adc068866d",
      "resource" : {
        "name" : "get-iam-policy-iam-member-oval-unity-test-0-0-0",
        "previous" : { },
        "properties" : {
          "member" : "<USER_EMAIL_ADDRESS!>",
          "resource" : "oval-unity-88908",
          "role" : "roles/GARawDataViewer"
        },
        "self" : { }
      }
    }
    Error was:
    Parameter for gcpIamMemberBinding at position 1 is not of type map, value was [null]

The interesting thing is that I have been able to deploy successfully assigning a predefined role like 'editor': roles/editor, but it is failing using a custom role.

I have even tried using the full path to the custom role: projects/oval-unity-88908/roles/GARawDataViewer
but still showing the same error.

Do you have any idea how could I solve this issue?
Thanks in advance!


问:
How to change the color of a CheckBox?
How do I change the default CheckBox color in Android?

By default the CheckBox color is green, and I want to change this color.

If it is not possible please tell me how to make a custom CheckBox?

答:
You can use the below lines of code to change the background of the Checkbox dynamically in your java code.

```<code>//Setting up background color on checkbox.
 checkbox.setBackgroundColor(Color.parseColor("#00e2a5"));
</code>```

This answer was from this site. You can also use this site to convert your RGB color to the Hex value, you need to feed the parseColor

Title: How to change the color of a CheckBox?

Body:
You can use the below lines of code to change the background of the Checkbox dynamically in your java code.

//Setting up background color on checkbox.
 checkbox.setBackgroundColor(Color.parseColor("#00e2a5"));

This answer was from this site. You can also use this site to convert your RGB color to the Hex value, you need to feed the parseColor


问:
boost::geometry::intersection of Polygon and "directed" Polyline
I need to find all intersection points of polyline and polygon such that polyline intersects polygon from outside. I marked such points with bold dots on an attached picture.

The problem is that a boost::geometry::intersection returns all intersection points and I need to check the intersection type somehow.

Here is some small example of using boost::geometry::intersection:

```<code>BOOST_GEOMETRY_REGISTER_POINT_2D(Eigen::Vector2d, double, cs::cartesian, x(), y())
BOOST_GEOMETRY_REGISTER_POINT_3D(Eigen::Vector3d, double, cs::cartesian, x(), y(), z())
BOOST_GEOMETRY_REGISTER_LINESTRING(std::vector<Eigen::Vector2d>)
BOOST_GEOMETRY_REGISTER_MULTI_LINESTRING(std::vector<std::vector<Eigen::Vector2d>>)

using Point = Eigen::Vector2d;
using Polyline = std::vector<Point>;
using Polygon = boost::geometry::model::polygon<Point>;

Polyline polyline{{0, -10}, {0, 10}};

Polygon polygon;
std::vector<Point> polygon_points{{-1., 1.}, {1., 1.}, {1, -1}, {-1, -1}, {-1, 1}};
boost::geometry::assign_points(polygon, polygon_points);

std::vector<Point> intersection_points;

boost::geometry::intersection(polygon, polyline, intersection_points);

for (const auto& p : intersection_points) {
  std::cout << p << std::endl << std::endl; //  here we have 2 points, but I need only one (0, -1)
}
</code>```

答:
This is how I'd do it:

Do for each segment of the polyline:

get the intersection's of this segment only and the polygon; (If none then continue).

use within to check if the start terminal is inside or outside the polygon;

if inside, then append every intersection with an odd-numbered index to the output;

if outside, then append every intersection with an even-numbered index (and zero) to the output.

Done.

Body:
I need to find all intersection points of polyline and polygon such that polyline intersects polygon from outside. I marked such points with bold dots on an attached picture.

The problem is that a boost::geometry::intersection returns all intersection points and I need to check the intersection type somehow.

Here is some small example of using boost::geometry::intersection:

BOOST_GEOMETRY_REGISTER_POINT_2D(Eigen::Vector2d, double, cs::cartesian, x(), y())
BOOST_GEOMETRY_REGISTER_POINT_3D(Eigen::Vector3d, double, cs::cartesian, x(), y(), z())
BOOST_GEOMETRY_REGISTER_LINESTRING(std::vector<Eigen::Vector2d>)
BOOST_GEOMETRY_REGISTER_MULTI_LINESTRING(std::vector<std::vector<Eigen::Vector2d>>)

using Point = Eigen::Vector2d;
using Polyline = std::vector<Point>;
using Polygon = boost::geometry::model::polygon<Point>;

Polyline polyline{{0, -10}, {0, 10}};

Polygon polygon;
std::vector<Point> polygon_points{{-1., 1.}, {1., 1.}, {1, -1}, {-1, -1}, {-1, 1}};
boost::geometry::assign_points(polygon, polygon_points);

std::vector<Point> intersection_points;

boost::geometry::intersection(polygon, polyline, intersection_points);

for (const auto& p : intersection_points) {
  std::cout << p << std::endl << std::endl; //  here we have 2 points, but I need only one (0, -1)
}


问:
how to handle webhook validation requests with MSgraph?
I'm trying to register my web app  in Microsoft azure ,to get notification about users one-drive change . to do so I need to register my app for getting notification.

I've been following these instructions:Create subscription

and here Handling webhook validation requests

but I need some help with the validation of the webhook.
When a new subscription is created, OneDrive will POST a request to the registered URL(my web app or maybe I'll use azure function) in the following format:

```<code>POST https://contoso.azurewebsites.net/your/webhook/service?validationtoken={randomString}

Content-Length: 0
</code>```

For the subscription to be created successfully, my service must respond to this request by returning the value of the validationtoken query string parameter as a plain-text response.

```<code>HTTP/1.1 200 OK
Content-Type: text/plain

{randomString}
</code>```

I'm using django , how do I make response in python like they asked?

this is how I send the first post request

```<code>def create_subscription(token):
  payload = {
    "changeType": "updated",
    "notificationUrl": notification_url,
    "resource": "/me/drive/root",
    "expirationDateTime": "2030-01-01T11:23:00.000Z",
    "clientState": "client-specific string"
  }

  headers = {
    "Authorization": token['access_token'],
    "Host": "graph.microsoft.com",
    "Content-Type": "application/json"
  }

  response = requests.post("https://graph.microsoft.com/v1.0/subscriptions".format(graph_url),
                           data=json.dumps(payload), headers=headers)

</code>```

this is how I make the response for the POST request of Microsoft

```<code>def validate_subscription(request):

    if request.method == 'POST':
      url = request.get_full_path()
      parsed = urlparse.urlparse(url)
      validation_string = parsed.query['validationtoken']

      headers = {
        "Host": "graph.microsoft.com",
        "Content-Type": "text/plain"
      }
      r = requests.post("{0}/subscriptions".format(graph_url),
                           data=validation_string, headers=headers)
      if (r.status_code == 200):
        return HttpResponse("Subscription suceeded")
</code>```

we keep getting error that says 'validation error'

thank you guys

答:
so what I did was to to use a capital 'v' for 'validationtoken' so the request should look like this :</p>

```<code>def validate_subscription(request):

if request.method == 'POST':
  url = request.get_full_path()
  parsed = urlparse.urlparse(url)
  validation_string = parsed.query['Validationtoken']

  headers = {
    "Host": "graph.microsoft.com",
    "Content-Type": "text/plain"
  }
  r = requests.post("{0}/subscriptions".format(graph_url),
                       data=validation_string, headers=headers)
  if (r.status_code == 200):
    return HttpResponse("Subscription suceeded")
</code>```

Body:
I'm trying to register my web app  in Microsoft azure ,to get notification about users one-drive change . to do so I need to register my app for getting notification.

I've been following these instructions:Create subscription

and here Handling webhook validation requests

but I need some help with the validation of the webhook.
When a new subscription is created, OneDrive will POST a request to the registered URL(my web app or maybe I'll use azure function) in the following format:

POST https://contoso.azurewebsites.net/your/webhook/service?validationtoken={randomString}

Content-Length: 0

For the subscription to be created successfully, my service must respond to this request by returning the value of the validationtoken query string parameter as a plain-text response.

HTTP/1.1 200 OK
Content-Type: text/plain

{randomString}

I'm using django , how do I make response in python like they asked?

this is how I send the first post request

def create_subscription(token):
  payload = {
    "changeType": "updated",
    "notificationUrl": notification_url,
    "resource": "/me/drive/root",
    "expirationDateTime": "2030-01-01T11:23:00.000Z",
    "clientState": "client-specific string"
  }

  headers = {
    "Authorization": token['access_token'],
    "Host": "graph.microsoft.com",
    "Content-Type": "application/json"
  }

  response = requests.post("https://graph.microsoft.com/v1.0/subscriptions".format(graph_url),
                           data=json.dumps(payload), headers=headers)

this is how I make the response for the POST request of Microsoft

def validate_subscription(request):

    if request.method == 'POST':
      url = request.get_full_path()
      parsed = urlparse.urlparse(url)
      validation_string = parsed.query['validationtoken']

      headers = {
        "Host": "graph.microsoft.com",
        "Content-Type": "text/plain"
      }
      r = requests.post("{0}/subscriptions".format(graph_url),
                           data=validation_string, headers=headers)
      if (r.status_code == 200):
        return HttpResponse("Subscription suceeded")

we keep getting error that says 'validation error'

thank you guys

Body:
so what I did was to to use a capital 'v' for 'validationtoken' so the request should look like this :

def validate_subscription(request):

if request.method == 'POST':
  url = request.get_full_path()
  parsed = urlparse.urlparse(url)
  validation_string = parsed.query['Validationtoken']

  headers = {
    "Host": "graph.microsoft.com",
    "Content-Type": "text/plain"
  }
  r = requests.post("{0}/subscriptions".format(graph_url),
                       data=validation_string, headers=headers)
  if (r.status_code == 200):
    return HttpResponse("Subscription suceeded")