问:
Clipping a networkx graph according to georeferenced polygon
I am running a loop that computes a networkx.classes.multidigraph.MultiDiGraph for each row (neighbourhood) of a list of GeoDataFrames (cities). It then computes some statistics for each row and writes the file out to disk. The problem is that the loop is extremely long to compute because the graph is computed for each row.

The way I want to quicken the loop is by computing the graph for the whole GeoDataFrame and then clipping the graph into each row (each row has a polygon). You can do this for GeoSeries with geopandas.clip. It seems, however, that no equivalent to geopandas.clip exists for networkx graphs.

Does anyone know of a way to clip a networkx graph?

Alternatively, what other methods exist to speed up my loop.

Note: clipping would work if I could convert the networkx graph to a pandas object. Unfortunately, I think it is not possible to keep the properties which osmnx acts on when the graph is converted to a pandas object. If I'm wrong, please say so.

Here is my initial code:

```<code>import osmnx as ox
import pandas as pd
import geopandas as gpd
import os

path="C:/folder/"
files=[os.path.join(path, f) for f in os.listdir(path)]

for i in range(0,2):
    city=gpd.read_file(files[i])
    circ=[]

    for i in range(0,181):
        graph_for_row=ox.graph_from_polygon(city.geometry[i])
        #above is the long command
        stat = ox.basic_stats(graph_for_row)
        circ.append(stat['circuity_avg'])

    circ=pd.Series(circ)
    merged.append(pd.concat([city, circ], axis=1))

for i in (range(0,len(merged))):
    with open(geofiles[i], 'w') as f:
        f.write(merged[i].to_json())

</code>```

Here is the new loop I'm aiming for:

```<code>clipped_graph=[]

for i in range(0,2):
    city=gpd.read_file(files[i])
    whole_city=city.unary_union
    graph=ox.graph_from_polygon(whole_city)
    clipped_graph.append(gpd.clip(graph, city.geometry))#this line
    #does not work since 'graph' is a networkx object, not
    #a GeoDataFrame or GeoSeries
    circ=[]

    for i in range(0,181)
        stat = ox.basic_stats(clipped_graph[i])
        circ.append(stat['circuity_avg'])

    circ=pd.Series(circ)
    merged.append(pd.concat([city, circ], axis=1))

for i in (range(0,len(merged))):
    with open(geofiles[i], 'w') as f:
        f.write(merged[i].to_json())
</code>```

答:
You can use your individual polygons to (spatially) intersect the graph nodes, then use those nodes to induce a subgraph. MWE:</p>

```<code>import osmnx as ox
ox.config(use_cache=True, log_console=True)

# load a shapefile of polygons as geodataframe using geopandas
# here i just get 3 cities from OSM to make example reproducible without a shapefile
places = ['Cudahy, CA, USA', 'Bell, CA, USA', 'Maywood, CA, USA']
gdf = ox.gdf_from_places(places)

# get a graph of the union of their boundaries, then extract nodes as geodataframe
G = ox.graph_from_polygon(gdf.unary_union, network_type='drive')
nodes = ox.graph_to_gdfs(G, edges=False)

# for each city polygon, find intersecting nodes then induce subgraph
for polygon in gdf['geometry']:
    intersecting_nodes = nodes[nodes.intersects(polygon)].index
    G_sub = G.subgraph(intersecting_nodes)
    fig, ax = ox.plot_graph(G_sub)
</code>```

Body:
I am running a loop that computes a networkx.classes.multidigraph.MultiDiGraph for each row (neighbourhood) of a list of GeoDataFrames (cities). It then computes some statistics for each row and writes the file out to disk. The problem is that the loop is extremely long to compute because the graph is computed for each row.

The way I want to quicken the loop is by computing the graph for the whole GeoDataFrame and then clipping the graph into each row (each row has a polygon). You can do this for GeoSeries with geopandas.clip. It seems, however, that no equivalent to geopandas.clip exists for networkx graphs.

Does anyone know of a way to clip a networkx graph?

Alternatively, what other methods exist to speed up my loop.

Note: clipping would work if I could convert the networkx graph to a pandas object. Unfortunately, I think it is not possible to keep the properties which osmnx acts on when the graph is converted to a pandas object. If I'm wrong, please say so.

Here is my initial code:

import osmnx as ox
import pandas as pd
import geopandas as gpd
import os

path="C:/folder/"
files=[os.path.join(path, f) for f in os.listdir(path)]

for i in range(0,2):
    city=gpd.read_file(files[i])
    circ=[]

    for i in range(0,181):
        graph_for_row=ox.graph_from_polygon(city.geometry[i])
        #above is the long command
        stat = ox.basic_stats(graph_for_row)
        circ.append(stat['circuity_avg'])

    circ=pd.Series(circ)
    merged.append(pd.concat([city, circ], axis=1))

for i in (range(0,len(merged))):
    with open(geofiles[i], 'w') as f:
        f.write(merged[i].to_json())

Here is the new loop I'm aiming for:

clipped_graph=[]

for i in range(0,2):
    city=gpd.read_file(files[i])
    whole_city=city.unary_union
    graph=ox.graph_from_polygon(whole_city)
    clipped_graph.append(gpd.clip(graph, city.geometry))#this line
    #does not work since 'graph' is a networkx object, not
    #a GeoDataFrame or GeoSeries
    circ=[]

    for i in range(0,181)
        stat = ox.basic_stats(clipped_graph[i])
        circ.append(stat['circuity_avg'])

    circ=pd.Series(circ)
    merged.append(pd.concat([city, circ], axis=1))

for i in (range(0,len(merged))):
    with open(geofiles[i], 'w') as f:
        f.write(merged[i].to_json())

Body:
You can use your individual polygons to (spatially) intersect the graph nodes, then use those nodes to induce a subgraph. MWE:

import osmnx as ox
ox.config(use_cache=True, log_console=True)

# load a shapefile of polygons as geodataframe using geopandas
# here i just get 3 cities from OSM to make example reproducible without a shapefile
places = ['Cudahy, CA, USA', 'Bell, CA, USA', 'Maywood, CA, USA']
gdf = ox.gdf_from_places(places)

# get a graph of the union of their boundaries, then extract nodes as geodataframe
G = ox.graph_from_polygon(gdf.unary_union, network_type='drive')
nodes = ox.graph_to_gdfs(G, edges=False)

# for each city polygon, find intersecting nodes then induce subgraph
for polygon in gdf['geometry']:
    intersecting_nodes = nodes[nodes.intersects(polygon)].index
    G_sub = G.subgraph(intersecting_nodes)
    fig, ax = ox.plot_graph(G_sub)


来源: stackexchange

问:
try-catch blocks with the return type
If I have a method that returns something, like

```<code>public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}
</code>```

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

答:
You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.

Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.

For my example, this would be coded as follows...

```<code>private void DoSomething() {
    try {
        DataTable dt = ReturnSomething();
    }
    catch (Exception ex) {
    }
}

public DataTable ReturnSomething() {
    DataTable dt = new DataTable();

    // logic here
    return dt;
}
</code>```

OwnerDisplayName: Julia

LastEditorDisplayName: Daniel L

ContentLicense: CC BY-SA 2.5

Title: try-catch blocks with the return type

Body:
If I have a method that returns something, like

public DataTable ReturnSomething()
{
   try
   {
      //logic here
     return ds.Tables[0];
   }
   catch (Exception e)
   {
      ErrorString=e.Message;
   }
}

This produces compiler error, obviously because catch{} block does not return anything.

So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?

Body:
You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.

Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.

For my example, this would be coded as follows...

private void DoSomething() {
    try {
        DataTable dt = ReturnSomething();
    }
    catch (Exception ex) {
    }
}

public DataTable ReturnSomething() {
    DataTable dt = new DataTable();

    // logic here
    return dt;
}

OwnerDisplayName: Bryan Sebastian

LastEditorDisplayName: Bryan Sebastian


问:
Refreshing a JS coutndown timer after pressing the back button?
My server runs some database maintenance scripts each night at midnight.  In order to prevent interference from the end user all sessions are terminated a few minutes before execution.  So that the user isn't rudely interrupted in the middle of doing something important, a countdown timer shows the remaining time.  This is done by exporting the server time during preprocessing (php) to a JS variable and cycling down the seconds in a simple looping display routine.

This works as intended most of the time, however, if the user navigates to the page by pressing the back button the time displayed will be out of sync.  Is there a way I can make sure the script is getting the most current server time each time the page is viewed, even when being viewed after having pressed the back button?

It's very simple...

```<code>var seconds = <?php echo $time_left; ?>;
function display_timer ()
{
    seconds--;
    minutes = parseInt((seconds / 60) % 60);
    hours = parseInt(seconds / 3600);

    ds = seconds % 60;
    ds = ds > 9 ? ds.toString() : '0' + ds.toString();
    dm = minutes > 9 ? minutes.toString() : '0' + minutes.toString();
    dh = hours > 9 ? hours.toString() : '0' + hours.toString();

    document.getElementById('countdown').innerHTML = 'Time left: ' + dh + ':' + dm + ':' + ds;

    if (seconds)
    {
        setTimeout("display_timer()", 1000);
    }
}

display_timer();
</code>```

答: Ummar's suggestion would work. Maybe for something a little more basic: If the time remaining is calculated on the server side, then how about you pass the time remaining through to client side, then start the count-down timer from there. Everytime the user loads the page it will get an accurate time, to start from, then doesnt have to continually send calls to the server</p>

ContentLicense: CC BY-SA 3.0

Body:
My server runs some database maintenance scripts each night at midnight.  In order to prevent interference from the end user all sessions are terminated a few minutes before execution.  So that the user isn't rudely interrupted in the middle of doing something important, a countdown timer shows the remaining time.  This is done by exporting the server time during preprocessing (php) to a JS variable and cycling down the seconds in a simple looping display routine.

This works as intended most of the time, however, if the user navigates to the page by pressing the back button the time displayed will be out of sync.  Is there a way I can make sure the script is getting the most current server time each time the page is viewed, even when being viewed after having pressed the back button?

It's very simple...

var seconds = <?php echo $time_left; ?>;
function display_timer ()
{
    seconds--;
    minutes = parseInt((seconds / 60) % 60);
    hours = parseInt(seconds / 3600);

    ds = seconds % 60;
    ds = ds > 9 ? ds.toString() : '0' + ds.toString();
    dm = minutes > 9 ? minutes.toString() : '0' + minutes.toString();
    dh = hours > 9 ? hours.toString() : '0' + hours.toString();

    document.getElementById('countdown').innerHTML = 'Time left: ' + dh + ':' + dm + ':' + ds;

    if (seconds)
    {
        setTimeout("display_timer()", 1000);
    }
}

display_timer();


问:
using h3 properly since it's a sensitive tag
So imagine i have the following scenario:

```<code><h3 className="service-card__body__title">
    <Icon name={service.icon} size="xl" />
    <span>{service.title}</span>
</h3>
</code>```

Shouldn't this be better?

```<code><span className="service-card__body__title">
  <Icon name={service.icon} size="lg" />
  <span>{service.title}</span>
</span>
</code>```

or

```<code><div className="service-card__body__title">
      <Icon name={service.icon} size="lg" />
      <span>{service.title}</span>
</div>
</code>```

So the h tag is a sensitive tag. Right now the design may no be affected, but if we add other elements to the design it could be affected, since you can not place everything inside of a h tag.

https://dotnetdaily.net/web-development/tutorials/html-tags-place-a-h1-tag

答:
If it's a heading (or actually a lower-level heading - third level) and if (like in your example) it only contains inline elements that are part of the heading, the way it's used in your first example is correct.

Screen readers, assistive technology and search engines will know that way that it's a third-level heading, which they wouldn't know when you use a styled span

ContentLicense: CC BY-SA 4.0

Body:
So imagine i have the following scenario:

    <Icon name={service.icon} size="xl" />
    {service.title}

Shouldn't this be better?

  <Icon name={service.icon} size="lg" />
  {service.title}

or

      <Icon name={service.icon} size="lg" />
      {service.title}

So the h tag is a sensitive tag. Right now the design may no be affected, but if we add other elements to the design it could be affected, since you can not place everything inside of a h tag.

https://dotnetdaily.net/web-development/tutorials/html-tags-place-a-h1-tag


问:
Is there a way to assign object in a for loop python
I have a class called MediaFiles, and I am getting a path from the user from which I get the full path, name of the file and the file extension, what I am trying to do is store each of these </p>

答:
It sounds like you should use a list of MediaFile objects. First you need to create the list:

```<code>media_files = []
</code>```

Then you append elements to the list in your for loop:

```<code>media_files.append(MediaFile(name, filepath, extention))
</code>```

Body:
It sounds like you should use a list of MediaFile objects. First you need to create the list:

media_files = []

Then you append elements to the list in your for loop:

media_files.append(MediaFile(name, filepath, extention))


问:
ElasticSearch query to find values greater than a certain length in an array field
ElasticSearch 6.4.2.

We have documents with a field called customCategories which is an array field of many 5-character codes.

Today we discovered by accident that several documents inadvertently have that field without any commas, and the 5-character codes were all mashed together as one long string.

So I need to find all documents that have this issue.  So how do I run a query to return any documents where customCategories has any value in it that's longer than 5 characters?

答:
you can try:</p>

```<code>{
  "query": {
    "script": {
      "script": {
        "inline": "for(int i=0; i < doc['customCategories'].length; i++) {  if ( doc['customCategories'][i].length() > 5 ) { return true; }  }  return false;",
        "lang": "painless"
      }
    }
  }
}
</code>```

Body:
you can try:

{
  "query": {
    "script": {
      "script": {
        "inline": "for(int i=0; i < doc['customCategories'].length; i++) {  if ( doc['customCategories'][i].length() > 5 ) { return true; }  }  return false;",
        "lang": "painless"
      }
    }
  }
}


问:
Deleting data that all users use but only for one user in Cloud Firestore
I am trying to structure my data such that when someone adds a new product to the database, all users receive the new product in their list and therefore the new product appears on their screen.
But if a user decides to delete that product, they can delete it but only for themselves. Is there a Cloud Firestore sorting/ordering/filtering that I should be using to accomplish this?

I thought I could use something like the following:

```<code>final theProduct = Provider.of<Products>(context);

products = await firestore.collection('products').getDocuments()

for (product in products.documents) {
await firestore.collection('products').add({
'nameOfProduct': theProduct.nameOfProduct
});
}
</code>```

But I get a document property error.

Maybe I need to go in one more collection and then try something? But I also need to be able to retrieve the data back using the userID of the signed in user..

Any hints/helpful links would be greatly appreciated.

So I think what I want to do is iterate through all documents within a collection and then document().collection('').add() something to each of their collection. Hopefully that sheds some more light on my problem.

答: Thanks to those who commented. I found a way to implement this was to use the unique value that each product contains and add it to a list on a per user basis in Firestore. Then fetch that list from Firestore and filter out the corresponding products. No deleting necessary.</p>

Body:
I am trying to structure my data such that when someone adds a new product to the database, all users receive the new product in their list and therefore the new product appears on their screen.
But if a user decides to delete that product, they can delete it but only for themselves. Is there a Cloud Firestore sorting/ordering/filtering that I should be using to accomplish this?

I thought I could use something like the following:

final theProduct = Provider.of<Products>(context);

products = await firestore.collection('products').getDocuments()

for (product in products.documents) {
await firestore.collection('products').add({
'nameOfProduct': theProduct.nameOfProduct
});
}

But I get a document property error.

Maybe I need to go in one more collection and then try something? But I also need to be able to retrieve the data back using the userID of the signed in user..

Any hints/helpful links would be greatly appreciated.

So I think what I want to do is iterate through all documents within a collection and then document().collection('').add() something to each of their collection. Hopefully that sheds some more light on my problem.


问:
How to download multiple files in Google Cloud Storage
Scenario: there are multiple folders and many files stored in storage bucket that is accessible by project team members. Instead of downloading individual files one at a time (which is very slow and time consuming), is there a way to download entire folders? Or at least multiple files at once? Is this possible without having to use one of the command consoles? Some of the team members are not tech savvy and need to access these files as simple as possible. Thank you for any help!</p>

答:
To download files to local machine need to:

install gsutil to local machine

run Google Cloud SDK Shell

run the command like this (example, for Windows-platform):

gsutil -m cp -r gs://source_folder_path "%userprofile%/Downloads"
```


问:
How to define a Vector to have all elements to be of the same type in Julia?
I need to define a Vector such that all elements in it need to be of the same type, though the type itself can be of any type. I tried the below:

```<code>["1", 2] isa AbstractVector{T} where T <: Any
</code>```

but this returns true.

The following works in this case and correctly returns false as needed:

```<code>["1", 2] isa AbstractVector{T} where T <: Union{AbstractString, Number}
</code>```

But, I don't want to restrict the type to be only Strings, Numbers etc. So, how else can I restrict all elements of a Vector to be of the same type though the type itself can be flexible?

答:
["2", 2] is of type Vector{Any} and T <: Any is true because setting T = Any gives Any <: Any which should evaluate to true.

"1" is a String and String <: AbstractString is true. But Julia's type system only works like this

T{S} <: T'{S} is true if T <: T' but is not true if T{S} <: T{S'} even if S <: S'. I don't know the technical term for that in type theory but it should be detailed in here https://en.wikipedia.org/wiki/Covariance_and_contravariance_(computer_science)

Body:
I need to define a Vector such that all elements in it need to be of the same type, though the type itself can be of any type. I tried the below:

["1", 2] isa AbstractVector{T} where T <: Any

but this returns true.

The following works in this case and correctly returns false as needed:

["1", 2] isa AbstractVector{T} where T <: Union{AbstractString, Number}

But, I don't want to restrict the type to be only Strings, Numbers etc. So, how else can I restrict all elements of a Vector to be of the same type though the type itself can be flexible?


问:
Loading a Font in a class in SFML
I'm having trouble loading a font as a static member of a custom class.

I have tried following the SFML tutorial but there are steps that I am clearly missing!

The code is the following:

```<code>#include <string>
#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <random>
#include <chrono>
#include <math.h>

using namespace std;
using namespace sf;

class base
{
    int number;
    double radius;
    double last_update_time;
    public:
        static const string FontFile = "SugarpunchDEMO.otf";
        static bool Init(const string& FontFile)
        {
            return font.loadFromFile(FontFile);
        }
        CircleShape shape;
        Text text;
        static Font font;
        void update_number(double time, double &last_update_time, int &number);
        void update_radius(int number, double &radius);
        base(int ini_number, double pos_x, double pos_y, double time);
        void update(double time);
};
</code>```

The constructor is:

```<code>base::base(int ini_number, double pos_x, double pos_y, double time){
    number = ini_number;
    update_radius(number, radius);
    shape.setRadius(radius);
    shape.setFillColor(Color::Red);
    shape.setPosition(pos_x - radius, pos_y - radius);
    text.setFont(font);
    char name[32];
    sprintf(name,"%d",number);
    text.setString(name);
    text.setCharacterSize(200);
    text.setFillColor(sf::Color::Blue);
    text.setPosition(pos_x,pos_y);
    last_update_time = time;
}
</code>```

The goal would be to load the font just once and to have it applied to each member of the class.

The error I got is:

```<code>In file included from base.cpp:9:0:
base.hpp:19:29: error: in-class initialization of static data member ‘const string base::FontFile’ of non-literal type
         static const string FontFile = "SugarpunchDEMO.otf";
                             ^~~~~~~~
base.hpp:19:40: error: call to non-constexpr function ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
         static const string FontFile = "SugarpunchDEMO.otf";
                                        ^~~~~~~~~~~~~~~~~~~~

</code>```

答:
This issue has nothing to do with SFML as your error message states:

in-class initialization of static data member const string base::FontFile of non-literal type

Or in other words: This way of initializing a class member is only allowed for numerical values and pointers to (string) literals. You're trying to initialize a std::string object of said class.

As a solution, use const char* for FontFile or move the initialization to your implementation file as const std::string FontFile = "SugarpunchDEMO.otf";

Title: Loading a Font in a class in SFML

Body:
I'm having trouble loading a font as a static member of a custom class.

I have tried following the SFML tutorial but there are steps that I am clearly missing!

The code is the following:

#include <string>
#include <iostream>
#include <sstream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <random>
#include <chrono>
#include <math.h>

using namespace std;
using namespace sf;

class base
{
    int number;
    double radius;
    double last_update_time;
    public:
        static const string FontFile = "SugarpunchDEMO.otf";
        static bool Init(const string& FontFile)
        {
            return font.loadFromFile(FontFile);
        }
        CircleShape shape;
        Text text;
        static Font font;
        void update_number(double time, double &last_update_time, int &number);
        void update_radius(int number, double &radius);
        base(int ini_number, double pos_x, double pos_y, double time);
        void update(double time);
};

The constructor is:

base::base(int ini_number, double pos_x, double pos_y, double time){
    number = ini_number;
    update_radius(number, radius);
    shape.setRadius(radius);
    shape.setFillColor(Color::Red);
    shape.setPosition(pos_x - radius, pos_y - radius);
    text.setFont(font);
    char name[32];
    sprintf(name,"%d",number);
    text.setString(name);
    text.setCharacterSize(200);
    text.setFillColor(sf::Color::Blue);
    text.setPosition(pos_x,pos_y);
    last_update_time = time;
}

The goal would be to load the font just once and to have it applied to each member of the class.

The error I got is:

In file included from base.cpp:9:0:
base.hpp:19:29: error: in-class initialization of static data member ‘const string base::FontFile’ of non-literal type
         static const string FontFile = "SugarpunchDEMO.otf";
                             ^~~~~~~~
base.hpp:19:40: error: call to non-constexpr function ‘std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
         static const string FontFile = "SugarpunchDEMO.otf";
                                        ^~~~~~~~~~~~~~~~~~~~


问:
Postgres Query Solution
```<code>with FQuery as
(
select ci_nm      as ci_nm
,     ci_nm             as ci_alias_nm
from rpt.ci_d
),
SQuery as
(
select ci_nm, ci_alias_nm from FQuery limit 10
)
insert into stg.Test1 (Select * from SQuery),
insert into stg.Test2 Select * from SQuery;
</code>```

I am trying to achieve insert in multiple tables from the second subquery. However, it is giving an error 'ERROR: 42601: syntax error at or near "insert"'

答:
If you want to make 2 queries at once, you should use transactions. </p>

```<code>BEGIN;
-- YOUR SQL STUFF
COMMIT;
</code>```

Title: Postgres Query Solution

Body:
with FQuery as
(
select ci_nm      as ci_nm
,     ci_nm             as ci_alias_nm
from rpt.ci_d
),
SQuery as
(
select ci_nm, ci_alias_nm from FQuery limit 10
)
insert into stg.Test1 (Select * from SQuery),
insert into stg.Test2 Select * from SQuery;

I am trying to achieve insert in multiple tables from the second subquery. However, it is giving an error 'ERROR: 42601: syntax error at or near "insert"'

Body:
If you want to make 2 queries at once, you should use transactions.

BEGIN;
-- YOUR SQL STUFF
COMMIT;


问:
Common elements between two randomly formed java arrays
Frame of the question:
Write a class called CommonElements with a single method main that will:

Create and obtain two integer arrays (arrayA and arrayB) using RandomIntegerArrayCreator type objects and its methods,
find the number of common elements between arrayA and arrayB (say: if integer 2 appears in arrayA once and twice in arrayB, that counts as ONE common element between the two),

Constraints / notes:
All array elements are integers from the the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and can appear multiple times in each array,
Arrays A and B do NOT have to be of the same size,
Arrays A and B CAN be empty (no elements),
Arrays A and B will NOT be sorted.

The code that I have already created:

```<code>import java.util.Random;

public class RandomIntegerArrayCreator {
    int[] arr;

    RandomIntegerArrayCreator(){
        Random rand = new Random();

        int size = rand.nextInt(16);
        arr = new int[size];
        for(int i=0;i<size;i++){

            arr[i] = rand.nextInt(11);
        }
    }
    public int getArraySize(){
        return this.arr.length;
    }
    public int[] getArray(){
        return this.arr;
    }
    public static void main(String[] args) {
        RandomIntegerArrayCreator r = new RandomIntegerArrayCreator();
        System.out.println("Size = "+r.getArraySize());
        int[] arr = r.getArray();
        System.out.print("Generated array is ");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}
</code>```

答:
Here's the pseudo code for what you're looking for.

```<code>for i=0, i<size arrayA
  for j=0, j<size arrayB
     if arrayA[i] == arrayB[j]
        if(arrayA is not in dummyarray)
            dummyarray.append(arrayA[i])
            counter++
</code>```

Edit: Basically, you iterate through arrayA and go through each element in arrayB and check if there's something that matches (For instance, arrayA[3] = 4 and arrayB[2] = 4, then there's a match). You add the number to a dummy list which you can check later to see if there's been a duplicate match.

Body:
Frame of the question:
Write a class called CommonElements with a single method main that will:

Create and obtain two integer arrays (arrayA and arrayB) using RandomIntegerArrayCreator type objects and its methods,
find the number of common elements between arrayA and arrayB (say: if integer 2 appears in arrayA once and twice in arrayB, that counts as ONE common element between the two),

Constraints / notes:
All array elements are integers from the the set {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and can appear multiple times in each array,
Arrays A and B do NOT have to be of the same size,
Arrays A and B CAN be empty (no elements),
Arrays A and B will NOT be sorted.

The code that I have already created:

import java.util.Random;

public class RandomIntegerArrayCreator {
    int[] arr;

    RandomIntegerArrayCreator(){
        Random rand = new Random();

        int size = rand.nextInt(16);
        arr = new int[size];
        for(int i=0;i<size;i++){

            arr[i] = rand.nextInt(11);
        }
    }
    public int getArraySize(){
        return this.arr.length;
    }
    public int[] getArray(){
        return this.arr;
    }
    public static void main(String[] args) {
        RandomIntegerArrayCreator r = new RandomIntegerArrayCreator();
        System.out.println("Size = "+r.getArraySize());
        int[] arr = r.getArray();
        System.out.print("Generated array is ");
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+" ");
        }
    }
}

Body:
Here's the pseudo code for what you're looking for.

for i=0, i<size arrayA
  for j=0, j<size arrayB
     if arrayA[i] == arrayB[j]
        if(arrayA is not in dummyarray)
            dummyarray.append(arrayA[i])
            counter++

Edit: Basically, you iterate through arrayA and go through each element in arrayB and check if there's something that matches (For instance, arrayA[3] = 4 and arrayB[2] = 4, then there's a match). You add the number to a dummy list which you can check later to see if there's been a duplicate match.


问:
Read remote file or access Powershell output with Terraform
Sorry if this has been answered.  I have been unable to find someone doing the same thing.  I have a Terraform module that builds an Azure VM.  I have a resource for virtual_machine_extension that runs a Powershell script to do some pre and post build items.  The Powershell script is run from an Azure Blob.  The main output from this script is a text file created.  I am trying to find a way to read that text file and use the contents in Terraform in another resource as a parameter.

I have created a Powershell variable that holds the contents of the file as well but I have the same issue as with the text file.  Not sure how to get the contents out of that variable into a parameter that Terraform can understand.

I am open to whatever way this can be achieved.

Also, I am running TF 12.20.

EDIT: Sorry all.  Let me provide a little more information.  So I Need to get the content on a remote server that is being built with Terraform.  My virtual machine extension runs a powershell script that creates a file locally on the server being built.  I need to take the content from that file and pass it into a null resource.

So let's say the content of the file on the remote server is "Testing data".

I will need to pass that content to a winrm connection.

```<code>    resource "null_resource" "chef-client" {
      triggers = {
        build_number = "${timestamp()}"
      }
      provisioner "chef" {
        connection {
          type = "winrm"
          user = var.user
          password = var.password
          host = var.host
          cacert = <text content>
          timeout = "5m"
          port = 5986
          use_ntlm = false
          https = true
          insecure = false
       }
     }
   }
</code>```

Updated the entire connection piece that I am trying to get working.  The server is not part of the domain at this point.  I tried local_file data source but could not auto-auth because it isn't part of the domain.  Been looking at template_file and external data source but not sure if that is the best way if you can somehow pull the result out of powershell for TF to read.

答:
If I'm reading your question correctly, it is within terraform that you wish to read the contents of the file?

Have you looked at the tf file function?
https://www.terraform.io/docs/configuration/functions/file.html
This allows you to read the contents of a file into a string within terraform where you can the work with it in whatever way you want.

Something like

```<code>locals {
  my_cert = file ("\path\to\cert\certname.crt")
}
    resource "null_resource" "chef-client" {
      triggers = {
        build_number = "${timestamp()}"
      }
      provisioner "chef" {
        connection {
          type = "winrm"
          user = var.user
          password = var.password
          host = var.host
          cacert = local.my_cert
          timeout = "5m"
          port = 5986
          use_ntlm = false
          https = true
          insecure = false
       }
     }
   }
</code>```

Remembering that as it's HCL and windows you need a double backslash to get around the escape charecter.

Body:
Sorry if this has been answered.  I have been unable to find someone doing the same thing.  I have a Terraform module that builds an Azure VM.  I have a resource for virtual_machine_extension that runs a Powershell script to do some pre and post build items.  The Powershell script is run from an Azure Blob.  The main output from this script is a text file created.  I am trying to find a way to read that text file and use the contents in Terraform in another resource as a parameter.

I have created a Powershell variable that holds the contents of the file as well but I have the same issue as with the text file.  Not sure how to get the contents out of that variable into a parameter that Terraform can understand.

I am open to whatever way this can be achieved.

Also, I am running TF 12.20.

EDIT: Sorry all.  Let me provide a little more information.  So I Need to get the content on a remote server that is being built with Terraform.  My virtual machine extension runs a powershell script that creates a file locally on the server being built.  I need to take the content from that file and pass it into a null resource.

So let's say the content of the file on the remote server is "Testing data".

I will need to pass that content to a winrm connection.

    resource "null_resource" "chef-client" {
      triggers = {
        build_number = "${timestamp()}"
      }
      provisioner "chef" {
        connection {
          type = "winrm"
          user = var.user
          password = var.password
          host = var.host
          cacert = <text content>
          timeout = "5m"
          port = 5986
          use_ntlm = false
          https = true
          insecure = false
       }
     }
   }

Updated the entire connection piece that I am trying to get working.  The server is not part of the domain at this point.  I tried local_file data source but could not auto-auth because it isn't part of the domain.  Been looking at template_file and external data source but not sure if that is the best way if you can somehow pull the result out of powershell for TF to read.

Body:
If I'm reading your question correctly, it is within terraform that you wish to read the contents of the file?

Have you looked at the tf file function?
https://www.terraform.io/docs/configuration/functions/file.html
This allows you to read the contents of a file into a string within terraform where you can the work with it in whatever way you want.

Something like

locals {
  my_cert = file ("\path\to\cert\certname.crt")
}
    resource "null_resource" "chef-client" {
      triggers = {
        build_number = "${timestamp()}"
      }
      provisioner "chef" {
        connection {
          type = "winrm"
          user = var.user
          password = var.password
          host = var.host
          cacert = local.my_cert
          timeout = "5m"
          port = 5986
          use_ntlm = false
          https = true
          insecure = false
       }
     }
   }

Remembering that as it's HCL and windows you need a double backslash to get around the escape charecter.


问:
Modifying Android systrace for capturing CPU Frequency even where is no change
I am currently running systrace with the category "freq" to capture cpu frequency with my device and I noticed that it only outputs something during a change in the freq. So if there was no change during the capture, the html output that systrace spits out will be blank. I would like to modify the atrace function and show cpu frequency even if there is no change. I was thinking of reading cpu/cpu*/cpufreq/cpuinfo_cur_freq in adb shell and simulating a change to say it changed from 0 to the current so it could at least output something. Does anyone have any ideas? Thanks.</p>

答: You can add some fake ftrace messages into the systrace's html output. So if you add some fake cpu-freq event message which contains the unique(zero?) value near the beginning of the trace texts in the output html file, you'll see cpu freq line in the systrace output screen.</p>


问:
Maintain display: none through all clicks
I have a page that has five "form-group container-fluid" on it and I am splitting them so that the top two show on one page - div:nth-child(-n+2) - and the bottom three - div:nth-child(n+3) show on a separate page. When the pages open they look perfect but when an element is clicked the page shows all five containers again. The basic scripts which work:

```<code><script type="text/javascript">
// Show only the first two containers
$("div[id$=RadAjaxPanel1] > div > div > div:nth-child(n+3)").css("display","none");
</script>

<script type="text/javascript">
// Show only the last three containers
$("div[id$=RadAjaxPanel1] > div > div > div:nth-child(-n+2)").css("display","none");
</script>
</code>```

Which show correctly on inspection as:

```<code><div class="form-group container-fluid" style="display: none;"></div>
</code>```

I have tried many ways to add a function that maintains the same style throughout page changes and have not been successful. There are signup buttons on the pages which cause popup windows. When a button is clicked the style="display: none; is removed. Thank you for your help!

UPDATE
After the div#id there is a comment added after clicking on the signup button:

```<code><!-- 2020.1.114.45 -->
</code>```

This seems to indicate the change on the page. Is it possible to use this in the script? After clicking a button a popup sign up form comes up. The button js selector is:

```<code>document.querySelector("#ctl05_ctl05_RadGrid2_ctl00_ctl06_gbcsignUp")
</code>```

The the popup form:

```<code>onkeypress=javascript:return WebForm_button(event, "id#save')
</code>```

I would be happy to know the correct language for searching too. I will keep searching for the answer but I have run out of ideas and knowledge for what to search.

答:
Try using CSS instead of javascript as it will keep the style of the page through clicks.</p>

```<code><style>
// Show only the last three containers
[id$='RadAjaxPanel1'] > div > div > div:nth-child(-n+2) {
display: none;
}
// Show only the first two containers
[id$='RadAjaxPanel1'] > div > div > div:nth-child(n+3) {
display: none;
}
</style>
</code>```

Body:
I have a page that has five "form-group container-fluid" on it and I am splitting them so that the top two show on one page - div:nth-child(-n+2) - and the bottom three - div:nth-child(n+3) show on a separate page. When the pages open they look perfect but when an element is clicked the page shows all five containers again. The basic scripts which work:

Which show correctly on inspection as:

I have tried many ways to add a function that maintains the same style throughout page changes and have not been successful. There are signup buttons on the pages which cause popup windows. When a button is clicked the style="display: none; is removed. Thank you for your help!

UPDATE
After the div#id there is a comment added after clicking on the signup button:

This seems to indicate the change on the page. Is it possible to use this in the script? After clicking a button a popup sign up form comes up. The button js selector is:

document.querySelector("#ctl05_ctl05_RadGrid2_ctl00_ctl06_gbcsignUp")

The the popup form:

onkeypress=javascript:return WebForm_button(event, "id#save')

I would be happy to know the correct language for searching too. I will keep searching for the answer but I have run out of ideas and knowledge for what to search.

Body:
Try using CSS instead of javascript as it will keep the style of the page through clicks.

<style>
// Show only the last three containers
[id$='RadAjaxPanel1'] > div > div > div:nth-child(-n+2) {
display: none;
}
// Show only the first two containers
[id$='RadAjaxPanel1'] > div > div > div:nth-child(n+3) {
display: none;
}
</style>


问:
Using captured types to type a class's attributes
I've followed the directions from the answers to the SO question
How can classes be made parametric in Perl 6?. However, I've hit some soft roadblock; I'm trying to type an internal class's attribute using the type capture and getting the following error:

```<code>Died with X::TypeCheck::Assignment
  in submethod BUILDALL at ...
  in method insert at ...
  in block <unit> at ...
</code>```

In the following example, I've typed the class BinaryNode's $.item attribute (with T) but doing so causes the above error:

```<code>class BinarySearchTree {
    my role BTSImpl[::T] {
        my class BinaryNode is rw {
            has T $.item;
            has BinaryNode $.left;
            has BinaryNode $.right;
        }

        method create-node( T $x ) {
            BinaryNode.new(item => $x)
        }
    }

    method ^parameterize(Mu:U \this, Mu \T) {
        my $type := this.^mixin: BTSImpl[T];
        $type.^set_name: this.^name ~ '[' ~ T.^name ~ ']';
        $type
    }
}

my $bst = BinarySearchTree[Int].new;
$bst.create-node(6);
</code>```

答:
First off, there's almost no need to perform the class + ^parameterize + role trick. It appears in some of the internals because it helps deal with some bootstrapping problems (the kind of fun one has when defining a language in terms of itself). However, in normal Raku code, just write a parametric role instead of a class. From the point of view of the consumer, there's usually no difference; one can:

Call .new on it to make an instance (which actually creates a class, known as a "pun", behind the scenes and makes the instance of that)

In fact, call any method on the type object with the same result; new isn't special

Inherit from it (again, it works on the automatically produced class)

With the added bonus that somebody can also compose it instead of inheriting.

Secondly, there's no relationship between a class defined inside of a role and the enclosing role (this is a general principle: nesting of one package inside of another doesn't imply any relationship between them at an object model level). Thus we need to make that separately generic and instantiate it.

These two get us to:

```<code>role BinarySearchTree[::T] {
    my role BinaryNode[::T] is rw {
        has T $.item;
        has BinaryNode $.left;
        has BinaryNode $.right;
    }

    method create-node( T $x ) {
        BinaryNode[T].new(item => $x)
    }
}

my $bst = BinarySearchTree[Int].new;
$bst.create-node(6);
</code>```

Which really should work, but the compiler seems to get the timing wrong on the BinaryNode[T]. We can work around that by just forcing it to delay the paramerterization until runtime; there's many ways we may do that, but writing BinaryNode[$(T)] compact and cheap (optimizes into pretty much no extra cost). Thus giving a working solution:

```<code>role BinarySearchTree[::T] {
    my role BinaryNode[::T] is rw {
        has T $.item;
        has BinaryNode $.left;
        has BinaryNode $.right;
    }

    method create-node( T $x ) {
        BinaryNode[$(T)].new(item => $x)
    }
}

my $bst = BinarySearchTree[Int].new;
$bst.create-node(6);
</code>```

Body:
I've followed the directions from the answers to the SO question
How can classes be made parametric in Perl 6?. However, I've hit some soft roadblock; I'm trying to type an internal class's attribute using the type capture and getting the following error:

Died with X::TypeCheck::Assignment
  in submethod BUILDALL at ...
  in method insert at ...
  in block <unit> at ...

In the following example, I've typed the class BinaryNode's $.item attribute (with T) but doing so causes the above error:

class BinarySearchTree {
    my role BTSImpl[::T] {
        my class BinaryNode is rw {
            has T $.item;
            has BinaryNode $.left;
            has BinaryNode $.right;
        }

        method create-node( T $x ) {
            BinaryNode.new(item => $x)
        }
    }

    method ^parameterize(Mu:U \this, Mu \T) {
        my $type := this.^mixin: BTSImpl[T];
        $type.^set_name: this.^name ~ '[' ~ T.^name ~ ']';
        $type
    }
}

my $bst = BinarySearchTree[Int].new;
$bst.create-node(6);

Body:
First off, there's almost no need to perform the class + ^parameterize + role trick. It appears in some of the internals because it helps deal with some bootstrapping problems (the kind of fun one has when defining a language in terms of itself). However, in normal Raku code, just write a parametric role instead of a class. From the point of view of the consumer, there's usually no difference; one can:

Call .new on it to make an instance (which actually creates a class, known as a "pun", behind the scenes and makes the instance of that)

In fact, call any method on the type object with the same result; new isn't special

Inherit from it (again, it works on the automatically produced class)

With the added bonus that somebody can also compose it instead of inheriting.

Secondly, there's no relationship between a class defined inside of a role and the enclosing role (this is a general principle: nesting of one package inside of another doesn't imply any relationship between them at an object model level). Thus we need to make that separately generic and instantiate it.

These two get us to:

role BinarySearchTree[::T] {
    my role BinaryNode[::T] is rw {
        has T $.item;
        has BinaryNode $.left;
        has BinaryNode $.right;
    }

    method create-node( T $x ) {
        BinaryNode[T].new(item => $x)
    }
}

my $bst = BinarySearchTree[Int].new;
$bst.create-node(6);

Which really should work, but the compiler seems to get the timing wrong on the BinaryNode[T]. We can work around that by just forcing it to delay the paramerterization until runtime; there's many ways we may do that, but writing BinaryNode[$(T)] compact and cheap (optimizes into pretty much no extra cost). Thus giving a working solution:

role BinarySearchTree[::T] {
    my role BinaryNode[::T] is rw {
        has T $.item;
        has BinaryNode $.left;
        has BinaryNode $.right;
    }

    method create-node( T $x ) {
        BinaryNode[$(T)].new(item => $x)
    }
}

my $bst = BinarySearchTree[Int].new;
$bst.create-node(6);


问:
Data Table Solution To New Variables By Group
```<code>library(data.table)
library(dplyr)

dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                    "score"=c(0,8,8,7,9,4,9,2,7),
                    "time"=c(1,2,3,1,2,3,1,2,3))

dataWANT=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                    "score"=c(0,8,8,7,9,4,9,2,7),
                    "time"=c(1,2,3,1,2,3,1,2,3),
                    "score3"=c(1,1,1,0,0,0,1,1,1),
                    "timescore3"=c(1,1,1,3,3,3,2,2,2),
                    "score7"=c(1,1,1,1,1,1,1,1,1),
                    "timescore7"=c(1,1,1,1,1,1,2,2,2))

dataHAVE[, score3 := ifelse(score<=3,
                               time[which.min(score<=3)],
                               time[which.max(time)]), by=student]
</code>```

I have 'dataHAVE' and want to generate 'dataWANT'

1) score3 equals to 1 if a student has any score less than or equals to 3; otherwise 0

2) score7 equals to 1 if a student has any score less than or equals to 7; otherwise 0

3) timescore3 equals to the minimum time value at which a student scores a 3 or less; if a student does not score a 3 or less as indicated by score equals to 3, then timecsore3 is the maximum time for that student.

4) timescore7 equals to the minimum time value at which a student scores a 7 or less; if a student does not score a 7 or less as indicated by score equals to 7, then timecsore7 is the maximum time for that student.

My attempt at this shows above but does not work and please note, I attempted Base R and dplyr but the dataset is so big that these take a very long time. A data.table solution is ideal.

NEW DATA TO HANDLE MISSING::

```<code>dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3))
</code>```

Updated DATA with missing 'time'

```<code>dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA,6,9,3,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,NA,2,NA,NA,NA,NA))
</code>```

答:
Based on the logic showed, it can be done with data.table

```<code>library(data.table)
setDT(dataHAVE)[,c("score3", "timescore3", "score7", "timescore7") := {
                   sc3 <- score <=3
                   sc7 <-  score <= 7
                   tsc3 <- if(any(sc3)) min(time[sc3]) else max(time)
                   tsc7 <- if(any(sc7)) min(time[sc7]) else max(time)
         .(+(any(sc3)), tsc3, +(any(sc7)),tsc7 )}, .(student)]
</code>```

If there are missing values, then use

```<code>setDT(dataHAVE)[,c("score3", "timescore3", "score7", "timescore7") := {
                   sc3 <- score <=3 & !is.na(score)
                    sc7 <-  score <= 7 & !is.na(score)
                    tsc3 <- if(any(sc3)) min(time[sc3], na.rm = TRUE) else max(time, na.rm = TRUE)
                    tsc7 <- if(any(sc7)) min(time[sc7], na.rm = TRUE) else max(time, na.rm = TRUE)
          .(+(any(sc3)), tsc3, +(any(sc7)),tsc7 )}, .(student)]
</code>```

Body:
library(data.table)
library(dplyr)

dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                    "score"=c(0,8,8,7,9,4,9,2,7),
                    "time"=c(1,2,3,1,2,3,1,2,3))

dataWANT=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                    "score"=c(0,8,8,7,9,4,9,2,7),
                    "time"=c(1,2,3,1,2,3,1,2,3),
                    "score3"=c(1,1,1,0,0,0,1,1,1),
                    "timescore3"=c(1,1,1,3,3,3,2,2,2),
                    "score7"=c(1,1,1,1,1,1,1,1,1),
                    "timescore7"=c(1,1,1,1,1,1,2,2,2))

dataHAVE[, score3 := ifelse(score<=3,
                               time[which.min(score<=3)],
                               time[which.max(time)]), by=student]

I have 'dataHAVE' and want to generate 'dataWANT'

1) score3 equals to 1 if a student has any score less than or equals to 3; otherwise 0

2) score7 equals to 1 if a student has any score less than or equals to 7; otherwise 0

3) timescore3 equals to the minimum time value at which a student scores a 3 or less; if a student does not score a 3 or less as indicated by score equals to 3, then timecsore3 is the maximum time for that student.

4) timescore7 equals to the minimum time value at which a student scores a 7 or less; if a student does not score a 7 or less as indicated by score equals to 7, then timecsore7 is the maximum time for that student.

My attempt at this shows above but does not work and please note, I attempted Base R and dplyr but the dataset is so big that these take a very long time. A data.table solution is ideal.

NEW DATA TO HANDLE MISSING::

dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3))

Updated DATA with missing 'time'

dataHAVE=data.frame("student"=c(1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7),
                    "score"=c(0,8,8,7,9,4,9,2,7,NA,4,7,NA,NA,NA,6,9,3,NA,NA,NA),
                    "time"=c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,NA,2,NA,NA,NA,NA))

Body:
Based on the logic showed, it can be done with data.table

library(data.table)
setDT(dataHAVE)[,c("score3", "timescore3", "score7", "timescore7") := {
                   sc3 <- score <=3
                   sc7 <-  score <= 7
                   tsc3 <- if(any(sc3)) min(time[sc3]) else max(time)
                   tsc7 <- if(any(sc7)) min(time[sc7]) else max(time)
         .(+(any(sc3)), tsc3, +(any(sc7)),tsc7 )}, .(student)]

If there are missing values, then use

setDT(dataHAVE)[,c("score3", "timescore3", "score7", "timescore7") := {
                   sc3 <- score <=3 & !is.na(score)
                    sc7 <-  score <= 7 & !is.na(score)
                    tsc3 <- if(any(sc3)) min(time[sc3], na.rm = TRUE) else max(time, na.rm = TRUE)
                    tsc7 <- if(any(sc7)) min(time[sc7], na.rm = TRUE) else max(time, na.rm = TRUE)
          .(+(any(sc3)), tsc3, +(any(sc7)),tsc7 )}, .(student)]


问:
The target "RunResolvePublishAssemblies" does not exist in the project
I'm working on a WPF application, using VS 2017 version 15.3.3

I was curious to know what's behind the file type Azure Function:
When I added it there was nothing changed in the solution explorer, I ignored that and continued my work (which has nothing to do with Azure), but when I compiled the project I get this error:

The target "RunResolvePublishAssemblies" does not exist in the project

and this warning:

Error encountered while loading the project. Some project features,
  such as full solution analysis for the failed project and projects
  that depend on it, have been disabled

I switched the solution explorer to view all files, and I found the azure function class is hidden in the place I added in, I deleted it, but the same problem still exist

Please, help!

答:
This GitHub error log helped me with this error: https://github.com/Azure/azure-functions-vs-build-sdk/issues/92

Following this suggestion resolved my build error:

To work-around this specific issue , you may be able to give an empty target in your csproj
  <Target Name="RunResolvePublishAssemblies" /> but I am not sure what else would be broken without using the SDK style projects.


问:
How to set imageView in circle like imageContacts in Swift correctly?
I want to show a picture into imageView like the image contact (in a circle) But when I try to show this, the imageView rescale his size and this doesn't show correctly in a circle.

```<code> image.layer.borderWidth=1.0
 image.layer.masksToBounds = false
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.clipsToBounds = true
</code>```

I want to show like this:

But I get this:

How can do the image resize to UIImageView size to show as a circle?

Thanks!

答:
You need to make sure the height and width should be the same as your image/view.

Like an image with 100 widths and 100 height sizes (100 X 100). If the sizes are different then the circle does not look like a circle.

Body:
I want to show a picture into imageView like the image contact (in a circle) But when I try to show this, the imageView rescale his size and this doesn't show correctly in a circle.

 image.layer.borderWidth=1.0
 image.layer.masksToBounds = false
 image.layer.borderColor = UIColor.whiteColor().CGColor
 image.layer.cornerRadius = image.frame.size.height/2
 image.clipsToBounds = true

I want to show like this:

But I get this:

How can do the image resize to UIImageView size to show as a circle?

Thanks!


答:
You can create a list and then store your objects there:

Below is the code:

```<code>#Define class in file named MediaFile.py
class MediaFile:

def __init__(self, file_name, file_path, file_type, file_comment=None, categorys=None, playlists=None):
        self.file_name = file_name
        self.file_path = file_path
        self.file_type = file_type
        self.file_comment = file_comment
        self.categorys = categorys
        self.playlists = playlists
</code>```

```<code>    # New file which contains actual code:
    from MediaFile import MediaFile
    import os.path

    filenames = []
    filepaths = []
    fileextentions = []
    # empty list to store objects
    media_list=[]

    d = input('Enter a path to organise: ')
    for path in os.listdir(d):
        full_path = os.path.join(d, path)
        i=0
        if os.path.isfile(full_path):
            filepath = full_path
            name = os.path.splitext(os.path.basename(full_path))[0]
            extention = os.path.splitext(full_path)[1]
            i+=1
            # append the objects to a list
            media_list.append(MediaFile(name, filepath, extention))
</code>```

Title: Is there a way to assign object in a for loop python

Body: I have a class called MediaFiles, and I am getting a path from the user from which I get the full path, name of the file and the file extension, what I am trying to do is store each of these

Body:
You can create a list and then store your objects there:

Below is the code:

#Define class in file named MediaFile.py
class MediaFile:

def __init__(self, file_name, file_path, file_type, file_comment=None, categorys=None, playlists=None):
        self.file_name = file_name
        self.file_path = file_path
        self.file_type = file_type
        self.file_comment = file_comment
        self.categorys = categorys
        self.playlists = playlists

    # New file which contains actual code:
    from MediaFile import MediaFile
    import os.path

    filenames = []
    filepaths = []
    fileextentions = []
    # empty list to store objects
    media_list=[]

    d = input('Enter a path to organise: ')
    for path in os.listdir(d):
        full_path = os.path.join(d, path)
        i=0
        if os.path.isfile(full_path):
            filepath = full_path
            name = os.path.splitext(os.path.basename(full_path))[0]
            extention = os.path.splitext(full_path)[1]
            i+=1
            # append the objects to a list
            media_list.append(MediaFile(name, filepath, extention))


问:
Keychain Query Always Returns errSecItemNotFound After Upgrading to iOS 13
I am storing passwords into the iOS keychain and later retrieving them to implement a "remember me" (auto-login) feature on my app.

I implemented my own wrapper around the Security.framework functions (SecItemCopyMatching(), etc.), and it was working like a charm up until iOS 12.

Now I am testing that my app doesn't break with the upcoming iOS 13, and lo and behold:

SecItemCopyMatching() always returns .errSecItemNotFound

...even though I have previously stored the data I am querying.

My wrapper is a class with static properties to conveniently provide  the values of the kSecAttrService and kSecAttrAccount when assembling the query dictionaries:

```<code>class LocalCredentialStore {

    private static let serviceName: String = {
        guard let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else {
            return "Unknown App"
        }
        return name
    }()
    private static let accountName = "Login Password"

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

I am inserting the password into the keychain with code like the following:

```<code>/*
  - NOTE: protectWithPasscode is currently always FALSE, so the password
  can later be retrieved programmatically, i.e. without user interaction.
 */
static func storePassword(_ password: String, protectWithPasscode: Bool, completion: (() -> Void)? = nil, failure: ((Error) -> Void)? = nil) {
    // Encode payload:
    guard let dataToStore = password.data(using: .utf8) else {
        failure?(NSError(localizedDescription: ""))
        return
    }

    // DELETE any previous entry:
    self.deleteStoredPassword()

    // INSERT new value:
    let protection: CFTypeRef = protectWithPasscode ? kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly : kSecAttrAccessibleWhenUnlocked
    let flags: SecAccessControlCreateFlags = protectWithPasscode ? .userPresence : []

    guard let accessControl = SecAccessControlCreateWithFlags(
        kCFAllocatorDefault,
        protection,
        flags,
        nil) else {
            failure?(NSError(localizedDescription: ""))
            return
    }

    let insertQuery: NSDictionary = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrAccessControl: accessControl,
        kSecValueData: dataToStore,
        kSecUseAuthenticationUI: kSecUseAuthenticationUIAllow,
        kSecAttrService: serviceName, // These two values identify the entry;
        kSecAttrAccount: accountName  // together they become the primary key in the Database.
    ]
    let resultCode = SecItemAdd(insertQuery as CFDictionary, nil)

    guard resultCode == errSecSuccess else {
        failure?(NSError(localizedDescription: ""))
        return
    }
    completion?()
}
</code>```

...and later, I am retrieving the password with:

```<code>static func loadPassword(completion: @escaping ((String?) -> Void)) {

    // [1] Perform search on background thread:
    DispatchQueue.global().async {
        let selectQuery: NSDictionary = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: serviceName,
            kSecAttrAccount: accountName,
            kSecReturnData: true,
            kSecUseOperationPrompt: "Please authenticate"
        ]
        var extractedData: CFTypeRef?
        let result = SecItemCopyMatching(selectQuery, &extractedData)

        // [2] Rendez-vous with the caller on the main thread:
        DispatchQueue.main.async {
            switch result {
            case errSecSuccess:
                guard let data = extractedData as? Data, let password = String(data: data, encoding: .utf8) else {
                    return completion(nil)
                }
                completion(password) // < SUCCESS

            case errSecUserCanceled:
                completion(nil)

            case errSecAuthFailed:
                completion(nil)

            case errSecItemNotFound:
                completion(nil)

            default:
                completion(nil)
            }
        }
    }
}
</code>```

(I don't think any of the entries of the dictionaries I use for either call has an inappropriate value... but perhaps I am missing something that just happened to "get a pass" until now)

I have set up a repository with a working project (Xcode 11 beta) that demonstrates the problem.

The password storing always succeeds; The password loading:

Succeeds on Xcode 10 - iOS 12 (and earlier), but

Fails with .errSecItemNotFound on Xcode 11 - iOS 13.

UPDATE: I can not reproduce the issue on the device, only Simulator. On the device, the stored password is retrieved successfully.
Perhaps this is a bug or limitation on the iOS 13 Simulator and/or iOS 13 SDK for the x86 platform.

UPDATE 2: If someone comes up with an alternative approach that somehow works around the issue (whether by design or by taking advantage of some oversight by Apple), I will accept it as an answer.

答:
Regarding the issue in kSecClassGenericPassword, I was trying to understand what is the problem and I found a solution for that.

Basically it seems like Apple was fixing an issue with kSecAttrAccessControl, so below iOS version 13 you add keyChain object with kSecAttrAccessControl without biometric identity and above iOS 13 that does not work anymore in a simulator.

So the solution for that is when you want to encrypt the keyChain object with biometric you need to add kSecAttrAccessControl to your query but if you don't need to encrypted by biometric you need to add only kSecAttrAccessible that's the right way to do these.

Examples

Query for biometric encrypt:

```<code>guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                                          kSecAttrAccessibleWhenUnlocked,
                                                          userPresence,
                                                          nil) else {
                                                              // failed to create accessControl
                                                              return
                                                          }

var attributes: [CFString: Any] = [kSecClass: kSecClassGenericPassword,
                                           kSecAttrService: "Your service",
                                           kSecAttrAccount: "Your account",
                                           kSecValueData: "data",
                                           kSecAttrAccessControl: accessControl]
</code>```

Query for regular KeyChain (without biometric):

```<code>var attributes: [CFString: Any] = [kSecClass: kSecClassGenericPassword,
                                               kSecAttrService: "Your service",
                                               kSecAttrAccount: "Your account",
                                               kSecValueData: "data",
                                               kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]
</code>```

Body:
I am storing passwords into the iOS keychain and later retrieving them to implement a "remember me" (auto-login) feature on my app.

I implemented my own wrapper around the Security.framework functions (SecItemCopyMatching(), etc.), and it was working like a charm up until iOS 12.

Now I am testing that my app doesn't break with the upcoming iOS 13, and lo and behold:

SecItemCopyMatching() always returns .errSecItemNotFound

...even though I have previously stored the data I am querying.

My wrapper is a class with static properties to conveniently provide  the values of the kSecAttrService and kSecAttrAccount when assembling the query dictionaries:

class LocalCredentialStore {

    private static let serviceName: String = {
        guard let name = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else {
            return "Unknown App"
        }
        return name
    }()
    private static let accountName = "Login Password"

// ...

I am inserting the password into the keychain with code like the following:

/*
  - NOTE: protectWithPasscode is currently always FALSE, so the password
  can later be retrieved programmatically, i.e. without user interaction.
 */
static func storePassword(_ password: String, protectWithPasscode: Bool, completion: (() -> Void)? = nil, failure: ((Error) -> Void)? = nil) {
    // Encode payload:
    guard let dataToStore = password.data(using: .utf8) else {
        failure?(NSError(localizedDescription: ""))
        return
    }

    // DELETE any previous entry:
    self.deleteStoredPassword()

    // INSERT new value:
    let protection: CFTypeRef = protectWithPasscode ? kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly : kSecAttrAccessibleWhenUnlocked
    let flags: SecAccessControlCreateFlags = protectWithPasscode ? .userPresence : []

    guard let accessControl = SecAccessControlCreateWithFlags(
        kCFAllocatorDefault,
        protection,
        flags,
        nil) else {
            failure?(NSError(localizedDescription: ""))
            return
    }

    let insertQuery: NSDictionary = [
        kSecClass: kSecClassGenericPassword,
        kSecAttrAccessControl: accessControl,
        kSecValueData: dataToStore,
        kSecUseAuthenticationUI: kSecUseAuthenticationUIAllow,
        kSecAttrService: serviceName, // These two values identify the entry;
        kSecAttrAccount: accountName  // together they become the primary key in the Database.
    ]
    let resultCode = SecItemAdd(insertQuery as CFDictionary, nil)

    guard resultCode == errSecSuccess else {
        failure?(NSError(localizedDescription: ""))
        return
    }
    completion?()
}

...and later, I am retrieving the password with:

static func loadPassword(completion: @escaping ((String?) -> Void)) {

    // [1] Perform search on background thread:
    DispatchQueue.global().async {
        let selectQuery: NSDictionary = [
            kSecClass: kSecClassGenericPassword,
            kSecAttrService: serviceName,
            kSecAttrAccount: accountName,
            kSecReturnData: true,
            kSecUseOperationPrompt: "Please authenticate"
        ]
        var extractedData: CFTypeRef?
        let result = SecItemCopyMatching(selectQuery, &extractedData)

        // [2] Rendez-vous with the caller on the main thread:
        DispatchQueue.main.async {
            switch result {
            case errSecSuccess:
                guard let data = extractedData as? Data, let password = String(data: data, encoding: .utf8) else {
                    return completion(nil)
                }
                completion(password) // < SUCCESS

            case errSecUserCanceled:
                completion(nil)

            case errSecAuthFailed:
                completion(nil)

            case errSecItemNotFound:
                completion(nil)

            default:
                completion(nil)
            }
        }
    }
}

(I don't think any of the entries of the dictionaries I use for either call has an inappropriate value... but perhaps I am missing something that just happened to "get a pass" until now)

I have set up a repository with a working project (Xcode 11 beta) that demonstrates the problem.

The password storing always succeeds; The password loading:

Succeeds on Xcode 10 - iOS 12 (and earlier), but

Fails with .errSecItemNotFound on Xcode 11 - iOS 13.

UPDATE: I can not reproduce the issue on the device, only Simulator. On the device, the stored password is retrieved successfully.
Perhaps this is a bug or limitation on the iOS 13 Simulator and/or iOS 13 SDK for the x86 platform.

UPDATE 2: If someone comes up with an alternative approach that somehow works around the issue (whether by design or by taking advantage of some oversight by Apple), I will accept it as an answer.

Body:
Regarding the issue in kSecClassGenericPassword, I was trying to understand what is the problem and I found a solution for that.

Basically it seems like Apple was fixing an issue with kSecAttrAccessControl, so below iOS version 13 you add keyChain object with kSecAttrAccessControl without biometric identity and above iOS 13 that does not work anymore in a simulator.

So the solution for that is when you want to encrypt the keyChain object with biometric you need to add kSecAttrAccessControl to your query but if you don't need to encrypted by biometric you need to add only kSecAttrAccessible that's the right way to do these.

Examples

Query for biometric encrypt:

guard let accessControl = SecAccessControlCreateWithFlags(kCFAllocatorDefault,
                                                          kSecAttrAccessibleWhenUnlocked,
                                                          userPresence,
                                                          nil) else {
                                                              // failed to create accessControl
                                                              return
                                                          }

var attributes: [CFString: Any] = [kSecClass: kSecClassGenericPassword,
                                           kSecAttrService: "Your service",
                                           kSecAttrAccount: "Your account",
                                           kSecValueData: "data",
                                           kSecAttrAccessControl: accessControl]

Query for regular KeyChain (without biometric):

var attributes: [CFString: Any] = [kSecClass: kSecClassGenericPassword,
                                               kSecAttrService: "Your service",
                                               kSecAttrAccount: "Your account",
                                               kSecValueData: "data",
                                               kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly]


问:
Are there any story based BDD test framework in python?
I mean, we have rSpec, cucumber in the ruby world.
But do we have similar tools in python? How about robot framework? Can we use it as a story based BDD test tool?

I'm asking because I'm kind of buying the BDD, story based test stuffs.

答: Python freshen is a python port of cucumber, implemented as nose plugin. </p>


问:
d3/js data manipulation dropping columns
I have a dataset in csv and it looks like below.

```<code>country,col1,col2,col3
Germany,19979188,11233906,43.7719591
UK,3839766,1884423,50.92349378
France,1363608,796271,41.60557873
Italy,957516,557967,41.72765781
</code>```

I'd like to drop col1, col2 off while keeping country and col3. If possible, I'd like to wrap it into a function where I can pass column list that I'd like to drop/keep.

Using pandas, which I'm familiar with, I can easily do it. e.g. data.drop(['col1', 'col2'], axis = 1). But I found d3 way or js way in general is based on each row so couldn't come up with an idea to drop columns.

I was thinking of d3.map() taking desirable columns only. But I was stuck to build a general function that the column list can be passed in.

Could anyone have thoughts?

答:
D3 fetch methods, like d3.csv, will retrieve the whole CSV and will create an array of objects based on that CSV. Because of that, filtering out some columns is useless. Actually, it's worse than useless: you'll spend time and resources with an unnecessary operation.

Therefore, the only useful solution is, if you have access and own that CSV, creating a new CSV without those columns. That way you'll have a smaller file, faster to load. Otherwise, if you cannot change the CSV itself, don't bother: just load the whole thing and use the columns you want (which will be properties in the objects), ignoring the others.

Finally, if you have a lot of data manipulation it might be interesting reducing the size of the objects in the data array. If that's your case, use a row function to return only the properties you want. For instance:

```<code>d3.csv(url, function (d){
    return {country: d.country, col3: d.col3}
}).then(etc...)
</code>```

Body:
I have a dataset in csv and it looks like below.

country,col1,col2,col3
Germany,19979188,11233906,43.7719591
UK,3839766,1884423,50.92349378
France,1363608,796271,41.60557873
Italy,957516,557967,41.72765781

I'd like to drop col1, col2 off while keeping country and col3. If possible, I'd like to wrap it into a function where I can pass column list that I'd like to drop/keep.

Using pandas, which I'm familiar with, I can easily do it. e.g. data.drop(['col1', 'col2'], axis = 1). But I found d3 way or js way in general is based on each row so couldn't come up with an idea to drop columns.

I was thinking of d3.map() taking desirable columns only. But I was stuck to build a general function that the column list can be passed in.

Could anyone have thoughts?

Body:
D3 fetch methods, like d3.csv, will retrieve the whole CSV and will create an array of objects based on that CSV. Because of that, filtering out some columns is useless. Actually, it's worse than useless: you'll spend time and resources with an unnecessary operation.

Therefore, the only useful solution is, if you have access and own that CSV, creating a new CSV without those columns. That way you'll have a smaller file, faster to load. Otherwise, if you cannot change the CSV itself, don't bother: just load the whole thing and use the columns you want (which will be properties in the objects), ignoring the others.

Finally, if you have a lot of data manipulation it might be interesting reducing the size of the objects in the data array. If that's your case, use a row function to return only the properties you want. For instance:

d3.csv(url, function (d){
    return {country: d.country, col3: d.col3}
}).then(etc...)


问:
Split vector into dataframe at every nth element
I would like to perform the following task in R.
Here is character vector:

```<code>a <- c("a", "1", "2", "3", "b", "5", "6", "7", "c", "8", "9", "11")
</code>```

Convert a into dataframe that looks like this:

```<code>a 1 2 3
b 5 6 7
c 8 9 11
</code>```

答:
This is an additional tale of caution, that adds to the existing answers, for tidyverse users who (like me) can automatically use pipes for everything: converting a vector to a dataframe all in a single pipe operation can be slightly tricky. See the following behaviors:

```<code>a <- seq(4)

a %>%
  matrix(., ncol = 2,  byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4

a %>%
  as.data.frame(matrix(., ncol = 2,  byrow = TRUE))
##   .
## 1 1
## 2 2
## 3 3
## 4 4
</code>```

Warning message:
      In as.data.frame.integer(., matrix(., ncol = 2, byrow = TRUE)) :
    'row.names' is not a character vector of length 4 -- omitting it. Will be an error!

```<code>a %>%
  as.data.frame(x = matrix(., ncol = 2,  byrow = TRUE))

##   V1 V2
## 1  1  2
## 2  3  4

a %>%
  as_tibble(matrix(., ncol = 2,  byrow = TRUE))
## # A tibble: 4 x 1
##   value
##   <int>
## 1     1
## 2     2
## 3     3
## 4     4

a %>%
  as_tibble(x = matrix(., ncol = 2,  byrow = TRUE))
## Error in .name_repair != name_repair :
##   comparison (2) is possible only for atomic and list types
</code>```

Hence what serves the purpose is

```<code>a %>%
  as.data.frame(x = matrix(., ncol = 2,  byrow = TRUE))
</code>```

I do need to dig deeper about why this is the case, though.

Body:
I would like to perform the following task in R.
Here is character vector:

a <- c("a", "1", "2", "3", "b", "5", "6", "7", "c", "8", "9", "11")

Convert a into dataframe that looks like this:

a 1 2 3
b 5 6 7
c 8 9 11

Body:
This is an additional tale of caution, that adds to the existing answers, for tidyverse users who (like me) can automatically use pipes for everything: converting a vector to a dataframe all in a single pipe operation can be slightly tricky. See the following behaviors:

a <- seq(4)

a %>%
  matrix(., ncol = 2,  byrow = TRUE)
##      [,1] [,2]
## [1,]    1    2
## [2,]    3    4

a %>%
  as.data.frame(matrix(., ncol = 2,  byrow = TRUE))
##   .
## 1 1
## 2 2
## 3 3
## 4 4

Warning message:
      In as.data.frame.integer(., matrix(., ncol = 2, byrow = TRUE)) :
    'row.names' is not a character vector of length 4 -- omitting it. Will be an error!

a %>%
  as.data.frame(x = matrix(., ncol = 2,  byrow = TRUE))

##   V1 V2
## 1  1  2
## 2  3  4

a %>%
  as_tibble(matrix(., ncol = 2,  byrow = TRUE))
## # A tibble: 4 x 1
##   value
##   <int>
## 1     1
## 2     2
## 3     3
## 4     4

a %>%
  as_tibble(x = matrix(., ncol = 2,  byrow = TRUE))
## Error in .name_repair != name_repair :
##   comparison (2) is possible only for atomic and list types

Hence what serves the purpose is

a %>%
  as.data.frame(x = matrix(., ncol = 2,  byrow = TRUE))

I do need to dig deeper about why this is the case, though.


问:
Linking static ".a" libraries to an Android Studio project using Gradle and CMake
I need to link a, prebuilt ".a" static library to an Android Studio project, using CMakeLists.txt.

The .a library was properly built to armeabi, armeabiv-7a, mips and x86 (it can even be "objdumped" for "content checking") and the ".h" files are just right as well.

The goal isn't to recompile the library sources along with my Android Studio project native sources.

Also, please do not refer to solutions using NDK + Andoid.mk (CMakeLists.txt only).

Since there is no working example on this matter on the web (including the Google NDK documentation and SO), please provide every change needed to the project files and/or project structure.

I keep the ".a" file and its "include" directory on a local folder, so as a meta reference to the this location, please consider /lib.a and /include.

Thank you.

答:
Create a submodule to your project.

put your *.a files in the appropriate libs/armAppropriate/nameOfLib.a

in your cmakelists.txt add the following lines

```<code>set(import-lib-location ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs)
</code>```

make sure this matches the location of your libs folder, do not use absolute path

put your .h files in the include directory of the submodule main.cpp.include

add the following to your CmakeLists.txt file

```<code>include_directories(include/)
add_library(nameOfLib STATIC IMPORTED )
set_target_properties(crypto
        PROPERTIES IMPORTED_LOCATION ${import-lib-location}/${ANDROID_ABI}/nameOfLib.a)

target_link_libraries( # Specifies the target library.
        your_main_cpp_file

        nameOfLib
        )
</code>```

Your static lib will be available through api written in your main cpp file and java/kotlin code written in this module

In your build.gradle of your main module write

```<code>api project(path: ':project_that_contains_a_libs')
</code>```

Body:
Create a submodule to your project.

put your *.a files in the appropriate libs/armAppropriate/nameOfLib.a

in your cmakelists.txt add the following lines

set(import-lib-location ${CMAKE_CURRENT_SOURCE_DIR}/../../../libs)

make sure this matches the location of your libs folder, do not use absolute path

put your .h files in the include directory of the submodule main.cpp.include

add the following to your CmakeLists.txt file

include_directories(include/)
add_library(nameOfLib STATIC IMPORTED )
set_target_properties(crypto
        PROPERTIES IMPORTED_LOCATION ${import-lib-location}/${ANDROID_ABI}/nameOfLib.a)

target_link_libraries( # Specifies the target library.
        your_main_cpp_file

        nameOfLib
        )

Your static lib will be available through api written in your main cpp file and java/kotlin code written in this module

In your build.gradle of your main module write

api project(path: ':project_that_contains_a_libs')


问:
How to solve SassError: Invalid parent selector "*"?
I have an Angular 9 app and when I use this snippet SCSS it returns this error:

```<code>SassError: Invalid parent selector "*"
   ╷
52 │         &#{$value} {
   │         ^^^^^^^^^^^^^^^
   ╵
</code>```

This is the snippet:

```<code>$values: (
  "":"",
  one: one,
  two: two,
);

@mixin gen() {
  @each $value, $key in $values {
    @media (min-width: 300px) {
      &#{$value} {
        @content
      }
    }
  }
}

@mixin display {
  display: block;
}

.display > * {
  @include gen() {
    @include display();
  }
}
</code>```

I want in output classes for each value like: display > *, display-one > *, display-two > *and so on.

答:
What @Yosef describes is correct – however, there are a few things to consider

When using @each loops on maps the order is $key, $value.

To minimize the CSS output move the @each loop inside the media query – like:

```<code>@media (min-width: 300px) {
  //  move loop here
  @each $key, $value in $values {
    ...
  }
}

// CSS output without redundant media queries
@media (min-width: 300px) {
  .display > * {
    display: block;
  }
  .display-one > * {
    display: block;
  }
  .display-two > * {
    display: block;
  }
}

</code>```

Last but not least consider not doing this at all – use an attribute selector instead – this way you can handle everything in one selector :-)

```<code>@media (min-width: 300px) {
  [class|=display] > * { display: block; }
}

// This will match
.display > *, .display-one > *, .display-two > *, .display-xxx > * etc.

</code>```

Body:
I have an Angular 9 app and when I use this snippet SCSS it returns this error:

SassError: Invalid parent selector "*"
   ╷
52 │         &#{$value} {
   │         ^^^^^^^^^^^^^^^
   ╵

This is the snippet:

$values: (
  "":"",
  one: one,
  two: two,
);

@mixin gen() {
  @each $value, $key in $values {
    @media (min-width: 300px) {
      &#{$value} {
        @content
      }
    }
  }
}

@mixin display {
  display: block;
}

.display > * {
  @include gen() {
    @include display();
  }
}

I want in output classes for each value like: display > *, display-one > *, display-two > *and so on.

Body:
What @Yosef describes is correct – however, there are a few things to consider

When using @each loops on maps the order is $key, $value.

To minimize the CSS output move the @each loop inside the media query – like:

@media (min-width: 300px) {
  //  move loop here
  @each $key, $value in $values {
    ...
  }
}

// CSS output without redundant media queries
@media (min-width: 300px) {
  .display > * {
    display: block;
  }
  .display-one > * {
    display: block;
  }
  .display-two > * {
    display: block;
  }
}

Last but not least consider not doing this at all – use an attribute selector instead – this way you can handle everything in one selector :-)

@media (min-width: 300px) {
  [class|=display] > * { display: block; }
}

// This will match
.display > *, .display-one > *, .display-two > *, .display-xxx > * etc.


问:
how to comment and like FB status when we use FBGraph API (iphone)
In Facebook Graph API....

suppose there is a wall there ...

I want to put comment and like symbols there..

so I can comment and I can like any status which are there on the wall??

is it possible?? how??

答:
please see "publish" section in api reference.
http://developers.facebook.com/docs/reference/api/

once you list the statuses or photos, you should have their ids

you can comment on a post via a POST request https://graph.facebook.com/OBJECT_ID/comments with patterns 'access_token=...' and 'message=...'

or like a post/comment by requesting https://graph.facebook.com/OBJECT_ID/likes
with 'access_token=...'

i use curl in php and XMLHttpRequest in ajax for sending a POST request, you should know how to do it in iOS :)


问:
Can MySQL JSON columns be indexed in version 8.0.19?
According to this webpage, MySQL JSON columns cannot be indexed.

MySQL Server Blog

"JSON columns cannot be indexed. You can work around this restriction by creating an index on a generated column that extracts a scalar value from the JSON column."

Can someone please tell me if this is changed in latest MySQL community version 8.0.19?

What will give me the best performance? A index on a generated column or a duplicate (a non JSON column with the exact same text as in the JSON column) column with normal fulltext search?

答: JSON is a handy way to store somewhat arbitrary information in a database table.  If will regularly use the components of the JSON in RDBMS operations, such as indexing, then you should pull them out of the JSON (or copy them out).