问:
How do I obtain a specific row with the cut command?

Background

I have a file, named yeet.d, that looks like this

```<code>JET_FUEL = /steel/beams
ABC_DEF = /michael/jackson
....50 rows later....
SHIA_LEBEOUF = /just/do/it
....73 rows later....
GIVE_FOOD = /very/hungry
NEVER_GONNA = /give/you/up
</code>```

I am familiar with the f and d options of the cut command.  The f option allows you to specify which column(s) to extract from, while the d option allows you to specify what the delimiters.

Problem

I want this output returned using the cut command.

```<code>/just/do/it
</code>```

From what I know, this is part of the command I want to enter:

```<code>cut -f1 -d= yeet.d
</code>```

Given that I want the values to the right of the equals sign, with the equals sign as the delimiter. However this would return:

```<code>/steel/beams
/michael/jackson
....50 rows later....
/just/do/it
....73 rows later....
/very/hungry
/give/you/up
</code>```

Which is more than what I want.

Question

How do I use the cut command to return only /just/do/it and nothing else from the situation above? This is different from How to get second last field from a cut command because I want to select a row within a large file, not just near from the end or the beginning.

答:
It depends on how you want to identify the desired line.

You could identify it by the line number. In this case you can use sed

```<code>cut -f2 -d= yeet.d | sed '53q;d'
</code>```

This extracts the 53th line.

Or you could identify it by a keyword. In this case use grep

```<code>cut -f2 -d= yeet.d | grep just
</code>```

This extracts all lines containing the word just.

Body:
Background

I have a file, named yeet.d, that looks like this

JET_FUEL = /steel/beams
ABC_DEF = /michael/jackson
....50 rows later....
SHIA_LEBEOUF = /just/do/it
....73 rows later....
GIVE_FOOD = /very/hungry
NEVER_GONNA = /give/you/up

I am familiar with the f and d options of the cut command.  The f option allows you to specify which column(s) to extract from, while the d option allows you to specify what the delimiters.

Problem

I want this output returned using the cut command.

/just/do/it

From what I know, this is part of the command I want to enter:

cut -f1 -d= yeet.d

Given that I want the values to the right of the equals sign, with the equals sign as the delimiter. However this would return:

/steel/beams
/michael/jackson
....50 rows later....
/just/do/it
....73 rows later....
/very/hungry
/give/you/up

Which is more than what I want.

Question

How do I use the cut command to return only /just/do/it and nothing else from the situation above? This is different from How to get second last field from a cut command because I want to select a row within a large file, not just near from the end or the beginning.

Body:
It depends on how you want to identify the desired line.

You could identify it by the line number. In this case you can use sed

cut -f2 -d= yeet.d | sed '53q;d'

This extracts the 53th line.

Or you could identify it by a keyword. In this case use grep

cut -f2 -d= yeet.d | grep just

This extracts all lines containing the word just.


来源: stackexchange

问:
Aggregating categorical variables to one variable in python 3 pandas
I have a pandas dataframe with 4 columns. like this

```<code>ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive
</code>```

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both
</code>```

Not able to think of a logic

```<code>ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both
</code>```

答:
You have 3 columns so you can use

```<code>DF.apply(YourCustomFunction, axis=1)
</code>```

Axis 1 tells you want to perform an operation on rows. Write your custom logic as a function:

```<code>def MyFunction(x):
    if condition1:
        Do something
    elif condition2:
        Do something
    ........
</code>```

So passing

DF['NewCol'] = DF.apply(MyFunction, axis=1)

Will do the trick. Mind you the x passed to the function will be an array so you have to address it correctly indexing within your function.

ContentLicense: CC BY-SA 4.0

Body:
I have a pandas dataframe with 4 columns. like this

ID  col1                        col2                col3
1   Strongly Positive   Strongly Positive   Weekly Positive
2   Strongly Positive   Strongly Positive   Neutral
3   Strongly Negative   Strongly Negative   Weekly Negative
4   Weekly Negative      Strongly Negative  Neutral
5   Neutral              Neutral            Neutral
6   Strongly Positive   Strongly Negative   Strongly Negative
7   Strongly Negative   Weekly Positive     Neutral
8   Neutral               Weekly Negative   Weekly Positive

Each of the columns can take values like (strongly positive, weekly positive, Neutral, weekly negative and strongly negative and an ID column.
I need to create a new column with these logic

If all the column has positive values or atleast one positive and two neutral values then aggregate that record in the new column as positive

If all the three column has neutral value then flag as neutral

If all the columns have negative values or atleast one negative and two neutral values then flag it as negative

If both positive and negative values are thre then flag it as both
by positive i mean either strong or weekly positive and the same for negative as well.

I need the the final data frame to be like this

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral                Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive        Both

Not able to think of a logic

ID  col1                  col2          col3        Aggregated_Col
1   Strongly Positive  Strongly Positive Weekly Positive    Positive
2   Strongly Positive  Strongly Positive Neutral            Positive
3   Strongly Negative  Strongly Negative Weekly Negative    Negative
4   Weekly Negative    Strongly Negative Neutral            Negative
5   Neutral            Neutral       Neutral            Neutral
6   Strongly Positive  Strongly Negative Strongly Negative  Both
7   Strongly Negative  Weekly Positive   Neutral            Both
8   Neutral Weekly     Negative      Weekly Positive    Both

Body:
You have 3 columns so you can use

DF.apply(YourCustomFunction, axis=1)

Axis 1 tells you want to perform an operation on rows. Write your custom logic as a function:

def MyFunction(x):
    if condition1:
        Do something
    elif condition2:
        Do something
    ........

So passing

DF['NewCol'] = DF.apply(MyFunction, axis=1)

Will do the trick. Mind you the x passed to the function will be an array so you have to address it correctly indexing within your function.


问:
OpenCL, problem with vector types: cross product is not working as I expect
I am newbie to OpenCL as well as heavy parallel computing. I came across a problem with operations over vector types.
I am crazy about taking advantage of SIMD instructions for operations with vectors and matrices. But the problem is that vector types, float float3 may be not working as I expect...
The thing is quite simple I just need to make my function to the cross product of two vectors.

I've written version of that function in Scala and it's working perfectly.

Here is the code in Scala:

```<code>    @inline def crossProduct(other: Vector3D) = Vector3D(
        y * other.z - z * other.y,
        z * other.x - x * other.z,
        x * other.y - y * other.x)
</code>```

And this one is version in OpenCL and fails the test:

float3 cross_pro(float3 a, float3 b) {
    return (float3) (
        (a.y * b.z) - (a.z * b.y),
        (a.z * b.x) - (a.x * b.z),
        (a.x * b.y) - (a.y * a.x));
}
```

Given set of parameters: cross_pro((float3) (0, 1, 0), (float3) (1, 0, 0));
Online calculators say that the result must be (float3) (0, 0, -1)
but OpenCL version prints: (float3) (0, 0, 0)!
 I can not even imagine why it happens? so I checked this function for overloading, experimented with these vector types an did so many other stuff...

答:
```<code>(a.x * b.y) - (a.y * a.x));
</code>```

should be

```<code>(a.x * b.y) - (a.y * b.x));
</code>```

also OpenCL has cross product already

https://www.khronos.org/registry/OpenCL/sdk/1.1/docs/man/xhtml/cross.html

```<code>float4 cross (float4 p0,float4 p1)
float3 cross (float3 p0,float3 p1)

double4 cross(double4 p0,double4 p1)   // if double extension enabled
double3 cross(double3 p0,double3 p1)   // if double extension enabled

half4 cross(half4 p0,half4 p1)   // if half extension enabled
half3 cross(half3 p0,half3 p1)   // if half extension enabled
</code>```

Description

Returns the cross product of p0.xyz and p1.xyz. The w component of the
  float4 result (or double or half if the cl_khr_fp64 or cl_khr_fp16
  extensions are enabled) will be 0.0.

If you need SIMD performance of a CPU: I guess, drivers will handle any available CPU cross product or dot product-like functions efficiently if you use their cross product function definition.

Body:
I am newbie to OpenCL as well as heavy parallel computing. I came across a problem with operations over vector types.
I am crazy about taking advantage of SIMD instructions for operations with vectors and matrices. But the problem is that vector types, float float3 may be not working as I expect...
The thing is quite simple I just need to make my function to the cross product of two vectors.

I've written version of that function in Scala and it's working perfectly.

Here is the code in Scala:

    @inline def crossProduct(other: Vector3D) = Vector3D(
        y * other.z - z * other.y,
        z * other.x - x * other.z,
        x * other.y - y * other.x)

And this one is version in OpenCL and fails the test:

float3 cross_pro(float3 a, float3 b) {
    return (float3) (
        (a.y * b.z) - (a.z * b.y),
        (a.z * b.x) - (a.x * b.z),
        (a.x * b.y) - (a.y * a.x));
}

Given set of parameters: cross_pro((float3) (0, 1, 0), (float3) (1, 0, 0));
Online calculators say that the result must be (float3) (0, 0, -1)
but OpenCL version prints: (float3) (0, 0, 0)!
 I can not even imagine why it happens? so I checked this function for overloading, experimented with these vector types an did so many other stuff...

Body:
(a.x * b.y) - (a.y * a.x));

should be

(a.x * b.y) - (a.y * b.x));

also OpenCL has cross product already

https://www.khronos.org/registry/OpenCL/sdk/1.1/docs/man/xhtml/cross.html

float4 cross (float4 p0,float4 p1)
float3 cross (float3 p0,float3 p1)

double4 cross(double4 p0,double4 p1)   // if double extension enabled
double3 cross(double3 p0,double3 p1)   // if double extension enabled

half4 cross(half4 p0,half4 p1)   // if half extension enabled
half3 cross(half3 p0,half3 p1)   // if half extension enabled

Description

Returns the cross product of p0.xyz and p1.xyz. The w component of the
  float4 result (or double or half if the cl_khr_fp64 or cl_khr_fp16
  extensions are enabled) will be 0.0.

If you need SIMD performance of a CPU: I guess, drivers will handle any available CPU cross product or dot product-like functions efficiently if you use their cross product function definition.


问:
Binding SelectedItem subclass list to a textbox
I want to display a list of joined strings to a textbox. I use converter for that which works great. The problem is when I try to bind the selected item sub class to a textbox, it doesn't display the values. It displays Projectname.Model.Tag

Tags is the subclass

```<code><TextBox HorizontalAlignment="Left"  Height="23" Text="{Binding Path=SelectedItem.Tags,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource myConverter}}" VerticalAlignment="Top" Width="auto"/>
</code>```

If I do this

```<code><TextBox HorizontalAlignment="Left"  Height="23" Text="{Binding Path=SelectedItem.Tags.Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource myConverter}}" VerticalAlignment="Top" Width="auto"/>
</code>```

It just displays empty

How do I properly bind the selected item to a textbox?

EDIT
So I have a class Book which contains a list of Tags. Name is the property of Tags.

```<code>public class Book:INotifyPropertyChanged
    {

        private int _idBook;
        private string _title;
        private ObservableCollection<Tag> _tag;

        public int IdBook
        {
            get { return _idBook; }
            set { _idBook = value; }
        }

        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        public ObservableCollection<Tag> Tags
        {
            get { return _tag; }
            set { _tag = value; OnPropertyChanged("Tags"); }
            }
}
</code>```

And Tag model

```<code> public class Tag:INotifyPropertyChanged
    {

        private int _idTag;
        private string _name;

        public int IdTag
        {
            get { return _idTag; }
            set { _idTag = value; OnPropertyChanged("IdTag"); }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; OnPropertyChanged("Name"); }
        }
}
</code>```

答: I solved it, the answer was in the converter rather than using string.Join I'm using String Builders Append and now it binds properly.</p>

Body:
I want to display a list of joined strings to a textbox. I use converter for that which works great. The problem is when I try to bind the selected item sub class to a textbox, it doesn't display the values. It displays Projectname.Model.Tag

Tags is the subclass

<TextBox HorizontalAlignment="Left"  Height="23" Text="{Binding Path=SelectedItem.Tags,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource myConverter}}" VerticalAlignment="Top" Width="auto"/>

If I do this

<TextBox HorizontalAlignment="Left"  Height="23" Text="{Binding Path=SelectedItem.Tags.Name,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged,Converter={StaticResource myConverter}}" VerticalAlignment="Top" Width="auto"/>

It just displays empty

How do I properly bind the selected item to a textbox?

EDIT
So I have a class Book which contains a list of Tags. Name is the property of Tags.

public class Book:INotifyPropertyChanged
    {

        private int _idBook;
        private string _title;
        private ObservableCollection<Tag> _tag;

        public int IdBook
        {
            get { return _idBook; }
            set { _idBook = value; }
        }

        public string Title
        {
            get { return _title; }
            set { _title = value; }
        }
        public ObservableCollection<Tag> Tags
        {
            get { return _tag; }
            set { _tag = value; OnPropertyChanged("Tags"); }
            }
}

And Tag model

 public class Tag:INotifyPropertyChanged
    {

        private int _idTag;
        private string _name;

        public int IdTag
        {
            get { return _idTag; }
            set { _idTag = value; OnPropertyChanged("IdTag"); }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; OnPropertyChanged("Name"); }
        }
}


问:
Rename column name with hyphen (-) in laravel migration
I'm trying to run a laravel migration that renames a particular column in my database but I repeatedly get an error message.

```<code>class ModifyColumnName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->renameColumn("content-description", "content_description");
        });
    }

}
</code>```

I keep on getting this error message.

```<code>Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax to use near '-description content_description VARCHAR(255) DEFAULT NULL' at line 1 (SQL: ALTER TABLE posts CHANGE content-description content_description VARCHAR(255) DEFAULT NULL)
</code>```

答:
since the column has no data, try this...

```<code>class ModifyColumnName extends Migration
{
 /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->dropColumn("`content-description`");
        $table->string("`content_description`");
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string("`content-description`");
        $table->dropColumn("`content_description"`);
    });
}
</code>```

}

According to mariadb.com: "Identifiers may be quoted using the backtick character -`. Quoting is optional for identifiers that do not contain special characters, or for identifiers that are not reserved words, if the ANSI_QUOTES SQL_MODE flag is set, double quotes ( ") can also be used to quote identifiers."

that's why I prefer innoDB ... !! to always use single quotes

Body:
I'm trying to run a laravel migration that renames a particular column in my database but I repeatedly get an error message.

class ModifyColumnName extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function (Blueprint $table) {
            $table->renameColumn("content-description", "content_description");
        });
    }

}

I keep on getting this error message.

Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
check the manual that corresponds to your MariaDB server version for the right syntax to use near '-description content_description VARCHAR(255) DEFAULT NULL' at line 1 (SQL: ALTER TABLE posts CHANGE content-description content_description VARCHAR(255) DEFAULT NULL)

Body:
since the column has no data, try this...

class ModifyColumnName extends Migration
{
 /**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->dropColumn("`content-description`");
        $table->string("`content_description`");
    });
}
/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('posts', function (Blueprint $table) {
        $table->string("`content-description`");
        $table->dropColumn("`content_description"`);
    });
}

}

According to mariadb.com: "Identifiers may be quoted using the backtick character -`. Quoting is optional for identifiers that do not contain special characters, or for identifiers that are not reserved words, if the ANSI_QUOTES SQL_MODE flag is set, double quotes ( ") can also be used to quote identifiers."

that's why I prefer innoDB ... !! to always use single quotes


问:
Understanding the types of functions
I am trying to understand the types of functions and being able to explain them.

Two functions:

```<code>insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
insert a True (b,c) = (a:b,c)
insert a False (b,c) = (b,a:c)

partition :: (t -> Bool) -> [t] -> ([t],[t])
partition p [] = ([],[])
partition p (x : xs) = insert x (p x) (partition p xs)
</code>```

From my limited knowledge I think that insert function:

insert is of type t, it takes two arguments one of bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

Is that the right way of thinking about it or am I getting it wrong? I have been following some tutorials and this is what I've u   nderstood so far.

答:
No, insert is a function, so it can't be "of type t". If it were of type t, it would be a value:

```<code>a :: Int
a = 5
</code>```

Here a is of type Int.

As you can see from the function implementation, insert takes three arguments:

```<code>insert a True (b,c) = ...
</code>```

The arguments are a, True and (b, c).

So, the type of insert is exactly t -> Bool -> ([t],[t]) -> ([t],[t]):

it's a function (because of ->s)

...of one argument of some type t

...and returns another function of type Bool -> ([t],[t]) -> ([t],[t])

...which takes one argument of type Bool (and Bool only)

...and returns a function ([t],[t]) -> ([t],[t])

(this should be one level of indentation deeper) ...which takes one argument of type ([t],[t]) (a tuple of two lists, each of which holds values of some type t)

...and returns, finally, a value of type ([t],[t])

Now, this looks like a mess: functions returning other functions that return functions... But this can be simplified. You can think of insert as a function of three arguments:

insert is this crazy function that returns other functions: type t -> Bool -> ([t],[t]) -> ([t],[t])

insert 2 is of type Bool -> ([t],[t]) -> ([t],[t])

insert 2 True if of type ([t],[t]) -> ([t],[t])

insert 2 True ([1], [2]) is of type ([t],[t])

BOOM! The last call actually returned a value, not a function! And due to this, one can treat insert as a function of three arguments. This thing is called currying, and it's named after the same man after whom Haskell is named - Haskell Curry.

Title: Understanding the types of functions

Body:
I am trying to understand the types of functions and being able to explain them.

Two functions:

insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
insert a True (b,c) = (a:b,c)
insert a False (b,c) = (b,a:c)

partition :: (t -> Bool) -> [t] -> ([t],[t])
partition p [] = ([],[])
partition p (x : xs) = insert x (p x) (partition p xs)

From my limited knowledge I think that insert function:

insert is of type t, it takes two arguments one of bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

Is that the right way of thinking about it or am I getting it wrong? I have been following some tutorials and this is what I've u   nderstood so far.

Body:
No, insert is a function, so it can't be "of type t". If it were of type t, it would be a value:

a :: Int
a = 5

Here a is of type Int.

As you can see from the function implementation, insert takes three arguments:

insert a True (b,c) = ...

The arguments are a, True and (b, c).

So, the type of insert is exactly t -> Bool -> ([t],[t]) -> ([t],[t]):

it's a function (because of ->s)

...of one argument of some type t

...and returns another function of type Bool -> ([t],[t]) -> ([t],[t])

...which takes one argument of type Bool (and Bool only)

...and returns a function ([t],[t]) -> ([t],[t])

(this should be one level of indentation deeper) ...which takes one argument of type ([t],[t]) (a tuple of two lists, each of which holds values of some type t)

...and returns, finally, a value of type ([t],[t])

Now, this looks like a mess: functions returning other functions that return functions... But this can be simplified. You can think of insert as a function of three arguments:

insert is this crazy function that returns other functions: type t -> Bool -> ([t],[t]) -> ([t],[t])

insert 2 is of type Bool -> ([t],[t]) -> ([t],[t])

insert 2 True if of type ([t],[t]) -> ([t],[t])

insert 2 True ([1], [2]) is of type ([t],[t])

BOOM! The last call actually returned a value, not a function! And due to this, one can treat insert as a function of three arguments. This thing is called currying, and it's named after the same man after whom Haskell is named - Haskell Curry.


问:
A target curve in Spotfire
In Spotfire, I am trying to draw three horizontal curves from columns in a different data table than my plot. These lines are supposed to be target lines. I know I can do this either in a combination chart or in Lines & Curves in properties.

However, I prefer not to do it in a combination chart as I have to add colouring and I get many distinct series when I add colouring to three different target lines.

So I tried doing this by adding a horizontal line in "Add > Horizontal Line > Line From Data Table". However instead of drawing a curve what this does is draw multiple horizontal lines for the slightly fluctuating values in this column. I have also tried other options in Lines  & Curves but none seem to work. And this happens although I have matchedthe data tables.

Does anyone have an idea how I can draw these target lines while avoiding the situation linked below?

The situation now:

The red, purple and black lines are supposed to be  3 seperate lines.

答:
I think you are very close. Try the Properties > Lines and Curves  and then Add > Line From Column Values. You will need to specify the x and y axis from the data table.

This will not always work on a bar chart, as the x may not line up with your category axis on the bar chart. Your x-axis for the line will need to be the same as the category axis.

ContentLicense: CC BY-SA 3.0

Title: A target curve in Spotfire


问:
How change a iframe content?

Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

```<code><html>
<head></head>
 <body>
  <iframe src="http://www.google.com"></iframe>
 </body>
</html>
</code>```

Thanks.

答:
No it is not possible to edit the contents of an iframe from another domain, otherwise this would be a huge security risk.

This is called Cross Site Scripting, which is always a no-no.

Title: How change a iframe content?

Body:
Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

Thanks.


问:
Cannot get access to Google Calendar API via Service Account
I'm trying to retrieve my own free/busy calendar via a simple POST call in Java, and I'm running into access errors.  Basically I'm getting a 404, notFound error like so:

```<code>{
 "kind": "calendar#freeBusy",
 "timeMin": "2019-05-28T13:00:00.000Z",
 "timeMax": "2019-05-28T21:00:00.000Z",
 "calendars": {
  "me@mycompany.com": {
   "errors": [
    {
     "domain": "global",
     "reason": "notFound"
    }
   ],
   "busy": []
  }
 }
}
</code>```

The code is fairly straightforward.  I can get exactly what I need if I use a bearer token from the OAuth Playground, everything works just fine.  Here's my relevant code:

```<code>        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(Objects.requireNonNull(classLoader.getResource("...a59.json")).getFile());

        GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream(file))
                .createScoped(CalendarScopes.all());

        credential.refreshToken();
        String accessToken = credential.getAccessToken();
</code>```

The accessToken value I get back results in the response above.

For my service account, I have created it within a project that has the Calendar API enabled.  I've also granted it the role of Project Owner so that it has full access to the settings in the project.

I'm sure this is something small and simple with my Service Account configuration, but I cannot for the life of me figure out what it is.

答:
You need one more step.

You will need to share your calendar with your service account.

Open the something-something.json file which you downloaded when creating the service account with a text editor, and you'll find the email address needed as the value of the "client_email" key/value pair.

Go to your calendar "Settings and sharing" and click on "+ Add people" button which you'll find under "Share with specific people".

You have likely done this, but for others, here is the full procedure to access Google Calendar with a service account: (allow my user to add meeting in my calendar with Google Calendar API with PHP without auth)

Body:
I'm trying to retrieve my own free/busy calendar via a simple POST call in Java, and I'm running into access errors.  Basically I'm getting a 404, notFound error like so:

{
 "kind": "calendar#freeBusy",
 "timeMin": "2019-05-28T13:00:00.000Z",
 "timeMax": "2019-05-28T21:00:00.000Z",
 "calendars": {
  "me@mycompany.com": {
   "errors": [
    {
     "domain": "global",
     "reason": "notFound"
    }
   ],
   "busy": []
  }
 }
}

The code is fairly straightforward.  I can get exactly what I need if I use a bearer token from the OAuth Playground, everything works just fine.  Here's my relevant code:

        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(Objects.requireNonNull(classLoader.getResource("...a59.json")).getFile());

        GoogleCredential credential = GoogleCredential
                .fromStream(new FileInputStream(file))
                .createScoped(CalendarScopes.all());

        credential.refreshToken();
        String accessToken = credential.getAccessToken();

The accessToken value I get back results in the response above.

For my service account, I have created it within a project that has the Calendar API enabled.  I've also granted it the role of Project Owner so that it has full access to the settings in the project.

I'm sure this is something small and simple with my Service Account configuration, but I cannot for the life of me figure out what it is.


答:
This looks like it would be easier to express with awk...

# awk -v _s="${_string}" '$3 == _s {print $3}' "${_path}"

## Above could be more _scriptable_ form of bellow example

awk -v _search="/just/do/it" '$3 == _search {print $3}' <<'EOF'
JET_FULE = /steal/beams
SHIA_LEBEOUF = /just/do/it
NEVER_GONNA = /give/you/up
EOF

## Either way, output should be similar to
##  /just/do/it
```

<ul>
<li><p><em><code>-v _something="Some Thing"</code></em> bit allows for passing Bash variables to <code>awk</code></p></li>
<li><p><em><code>$3 == _search</code></em> bit tells <code>awk</code> to match only when column <code>3</code> is equal to the <code>search</code> string</p>

<ul>
<li>To search for a sub-string within a line one can use <em><code>$0 ~ _search</code></em></li>
</ul></li>
<li><p><em><code>{print $3}</code></em> bit tells <code>awk</code> to <code>print</code> column <code>3</code> for any matches</p></li>
<li><p>And the <em><code><<'EOF'</code></em> bit tells Bash to not expand anything within the opening and closing <em><code>EOF</code></em> <em>tags</em></p></li>
</ul>

<p>... however, the above will still output duplicate matches, eg. if <code>yeet.d</code> somehow contained...</p>

```JET_FULE = /steal/beams
SHIA_LEBEOUF = /just/do/it
NEVER_GONNA = /give/you/up
AGAIN = /just/do/it
```

<p>... there'd be two <code>/just/do/it</code> lines outputed by <code>awk</code>.</p>

<p>Quickest way around that would be to pipe <code>|</code> to <code>head -1</code>, but the <em>better</em> way would be to tell <code>awk</code> to <code>exit</code> after it's been told to <code>print</code>...</p>

<pre class="lang-sh prettyprint-override"><code>_string='/just/do/it'
_path='yeet.d'

awk -v _s="${_string}" '$3 == _s {print $3; exit}' "${_path}"
</code>```

... though that now assumes that only the first match is wanted, obtaining the nth is possible though currently outside the scope of the question as of last time read.

Updates

To trip awk on the first column while printing the third column and exiting after the first match may look like...

_string='SHIA_LEBEOUF'
_path='yeet.d'

awk -v _s="${_string}" '$1 == _s {print $3; exit}' "${_path}"
```

<p>... and generalize even further...</p>

<pre class="lang-sh prettyprint-override"><code>_string='^SHIA_LEBEOUF '
_path='yeet.d'

awk -v _s="${_string}" '$0 ~ _s {print $3; exit}' "${_path}"
</code>```

... because awk totally gets regular expressions, mostly.

Title: How do I obtain a specific row with the cut command?

Body:
This looks like it would be easier to express with awk...

# awk -v _s="${_string}" '$3 == _s {print $3}' "${_path}"

## Above could be more _scriptable_ form of bellow example

awk -v _search="/just/do/it" '$3 == _search {print $3}' <<'EOF'
JET_FULE = /steal/beams
SHIA_LEBEOUF = /just/do/it
NEVER_GONNA = /give/you/up
EOF

## Either way, output should be similar to
##  /just/do/it

-v _something="Some Thing" bit allows for passing Bash variables to awk

$3 == _search bit tells awk to match only when column 3 is equal to the search string

To search for a sub-string within a line one can use $0 ~ _search

{print $3} bit tells awk to print column 3 for any matches

And the <<'EOF' bit tells Bash to not expand anything within the opening and closing EOF tags

... however, the above will still output duplicate matches, eg. if yeet.d somehow contained...

JET_FULE = /steal/beams
SHIA_LEBEOUF = /just/do/it
NEVER_GONNA = /give/you/up
AGAIN = /just/do/it

... there'd be two /just/do/it lines outputed by awk.

Quickest way around that would be to pipe | to head -1, but the better way would be to tell awk to exit after it's been told to print...

_string='/just/do/it'
_path='yeet.d'

awk -v _s="${_string}" '$3 == _s {print $3; exit}' "${_path}"

... though that now assumes that only the first match is wanted, obtaining the nth is possible though currently outside the scope of the question as of last time read.

Updates

To trip awk on the first column while printing the third column and exiting after the first match may look like...

_string='SHIA_LEBEOUF'
_path='yeet.d'

awk -v _s="${_string}" '$1 == _s {print $3; exit}' "${_path}"

... and generalize even further...

_string='^SHIA_LEBEOUF '
_path='yeet.d'

awk -v _s="${_string}" '$0 ~ _s {print $3; exit}' "${_path}"

... because awk totally gets regular expressions, mostly.


问:
How to sort queryset based on two fields in Django?
This is my serilizer class:

```<code>class RankNewsChannelSerializers(serializers.ModelSerializer):
    class Meta:
        model = News_Channel
        fields = ('id', 'name','total_star', 'total_user')
</code>```

This is my view:

```<code>class NewsChannelRankApi(ListAPIView):
    queryset = News_Channel.objects.order_by('-total_star').all()
    serializer_class = RankNewsChannelSerializers
</code>```

The response I'm getting is sorted, based on total_stars, as shown below:

```<code>[
    {
        "id": 9,
        "name": "The Hindu",
        "total_star": 36,
        "total_user": 5
    },
    {
        "id": 1,
        "name": "NDTV",
        "total_star": 36,
        "total_user": 5
    },
    {
        "id": 10,
        "name": "Firstpost",
        "total_star": 35,
        "total_user": 6
    },
    {
        "id": 14,
        "name": "DD News",
        "total_star": 25,
        "total_user": 4
    }
]

</code>```

But I need the response to be sorted by total_star/total_user.
Like this is my invalid method, but it will give you a rough idea of what I want to achieve.

```<code>class NewsChannelRankApi(ListAPIView):
    queryset = News_Channel.objects.order_by('-total_star/total_user').all()
    serializer_class = RankNewsChannelSerializers
</code>```

Please help me if there is anyway to do so?

答:
You can add a field with the value you want and then order by it.
Also, you don't need the .all()

    queryset = News_Channel.objects \
         .annotate(stars_per_user=F('total_star')/F('total_user')) \
         .order_by('-stars_per_user')
```

Body:
This is my serilizer class:

class RankNewsChannelSerializers(serializers.ModelSerializer):
    class Meta:
        model = News_Channel
        fields = ('id', 'name','total_star', 'total_user')

This is my view:

class NewsChannelRankApi(ListAPIView):
    queryset = News_Channel.objects.order_by('-total_star').all()
    serializer_class = RankNewsChannelSerializers

The response I'm getting is sorted, based on total_stars, as shown below:

[
    {
        "id": 9,
        "name": "The Hindu",
        "total_star": 36,
        "total_user": 5
    },
    {
        "id": 1,
        "name": "NDTV",
        "total_star": 36,
        "total_user": 5
    },
    {
        "id": 10,
        "name": "Firstpost",
        "total_star": 35,
        "total_user": 6
    },
    {
        "id": 14,
        "name": "DD News",
        "total_star": 25,
        "total_user": 4
    }
]

But I need the response to be sorted by total_star/total_user.
Like this is my invalid method, but it will give you a rough idea of what I want to achieve.

class NewsChannelRankApi(ListAPIView):
    queryset = News_Channel.objects.order_by('-total_star/total_user').all()
    serializer_class = RankNewsChannelSerializers

Please help me if there is anyway to do so?


问:
How to write SQL statements in succession without error
I am running a CREATE VIEW statement which is perfectly self-contained and runs perfect on its own. Two lines below I run a separate SELECT statement to view the results, which works perfect on its own.

However, I run the whole script together and it doesn't work.

Code looks something like this:

```<code>--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;

--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work
</code>```

The error message is "Incorrect syntax near the keyword 'SELECT'."

答:
You should run this queries separetly or you have too old SQL server to run CREATE OR ALTER VIEW. Firstly create the view, and then run the select.

You can also add GO, it will separate batches:

```<code>--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;
GO
--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work
</code>```

Body:
I am running a CREATE VIEW statement which is perfectly self-contained and runs perfect on its own. Two lines below I run a separate SELECT statement to view the results, which works perfect on its own.

However, I run the whole script together and it doesn't work.

Code looks something like this:

--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;

--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work

The error message is "Incorrect syntax near the keyword 'SELECT'."

Body:
You should run this queries separetly or you have too old SQL server to run CREATE OR ALTER VIEW. Firstly create the view, and then run the select.

You can also add GO, it will separate batches:

--- These four lines run fine on their own.
CREATE OR ALTER VIEW view1 AS
SELECT column1, column2, column3
FROM table1;
GO
--- This line runs fine on its own
SELECT * FROM view1

--- If I run the whole script it doesn't work


问:
Kinect pattern recognition
I bought a Kinect to play around with on my PC in C#. (And what fun it is to program!)

I'm using CLNUIDevice.dll to get the depth image from Kinect. This works fine and I'm able to read the depth through the RGB values in the image.

Now I'm wondering what libraries there are to do different types of recognition. I've seen hand recognition, face recognition, skeleton, emotions, objects, etc.

The image processing libraries don't have to be for Kinect (though that would be nice) and they don't have to be for .Net (though that would be nice). For instance: Any object tracking lib will work, but if it can use the 3D heatmap from Kinect properly it will work much better.

答: Learn OpenCV. It is a standard framework for computer vision labs/learning today. Try contour finding facilities, K-nearest neighbors, etc. But first, learn its interface (data structures, functions).</p>

ContentLicense: CC BY-SA 2.5

Title: Kinect pattern recognition


问:
Control z-index in Fabric.js
In fabricjs, I want to create a scene in which the object under the mouse rises to the top of the scene in z-index, then once the mouse leaves that object, it goes back to the z-index where it came from. One cannot set object.zindex (which would be nice). Instead, I'm using a placeholder object which is put into the object list at the old position, and then the old object is put back in the position where it was in the list using canvas.insertAt. However this is not working.

See http://jsfiddle.net/rFSEV/ for the status of this.

```<code>var canvasS = new fabric.Canvas('canvasS', { renderOnAddition: false, hoverCursor: 'pointer', selection: false });
var bars = {}; //storage for bars (bar number indexed by group object)
var selectedBar = null; //selected bar (group object)
var placeholder = new fabric.Text("XXXXX", { fontSize: 12 });

//pass null or a bar
function selectBar(bar) {
    if (selectedBar) {
        //remove the old topmost bar and put it back in the right zindex
        //PROBLEM: It doesn't go back; it stays at the same zindex
        selectedBar.remove();
        canvasS.insertAt(selectedBar, selectedBar.XZIndex, true);
        selectedBar = null;
        }
    if (bar) {
        //put a placeholder object ("XXX" for now) in the position
        //where the bar was, and put the bar in the top position
        //so it shows topmost
        selectedBar = bar;
        canvasS.insertAt(placeholder, selectedBar.XZIndex, true);
        canvasS.add(bar);
        canvasS.renderAll();
        }
    }

canvasS.on({
     'mouse:move': function(e) {
        //hook up dynamic zorder
        if (!e.target) return;
        if (bars[e.target])
            selectBar(e.target);
        else
            selectBar(null);
        },
    });

var objcount = canvasS.getObjects().length;

//create bars
for (var i = 0; i < 20; ++i) {
    var rect = new fabric.Rect({
      left: 0,
      top: 0,
      rx: 3,
      ry: 3,
      stroke: 'red',
      width: 200,
      height: 25
    });
    rect.setGradientFill({
      x1: 0,
      y1: 0,
      x2: 0,
      y2: rect.height,
      colorStops: {
        0: '#080',
        1: '#fff'
      }
    });
    var text = new fabric.Text("Bar number " + (i+1), {
        fontSize: 12
    });
    var group = new fabric.Group([ rect, text ], {
      left: i + 101,
      top: i * 4 + 26
    });
    group.hasControls = group.hasBorders = false;

    //our properties (not part of fabric)
    group.XBar = rect;
    group.XZIndex = objcount++;

    canvasS.add(group);
    bars[group] = i;
    }
canvasS.renderAll();
</code>```

答:
After I added a line object, I was make the line appear under the object using:

```<code>canvas.add(line);
canvas.sendToBack(line);
</code>```

Other options are

canvas.sendBackwards

canvas.sendToBack

canvas.bringForward

canvas.bringToFront

see:  https://github.com/fabricjs/fabric.js/issues/135

Title: Control z-index in Fabric.js

Body:
In fabricjs, I want to create a scene in which the object under the mouse rises to the top of the scene in z-index, then once the mouse leaves that object, it goes back to the z-index where it came from. One cannot set object.zindex (which would be nice). Instead, I'm using a placeholder object which is put into the object list at the old position, and then the old object is put back in the position where it was in the list using canvas.insertAt. However this is not working.

See http://jsfiddle.net/rFSEV/ for the status of this.

var canvasS = new fabric.Canvas('canvasS', { renderOnAddition: false, hoverCursor: 'pointer', selection: false });
var bars = {}; //storage for bars (bar number indexed by group object)
var selectedBar = null; //selected bar (group object)
var placeholder = new fabric.Text("XXXXX", { fontSize: 12 });

//pass null or a bar
function selectBar(bar) {
    if (selectedBar) {
        //remove the old topmost bar and put it back in the right zindex
        //PROBLEM: It doesn't go back; it stays at the same zindex
        selectedBar.remove();
        canvasS.insertAt(selectedBar, selectedBar.XZIndex, true);
        selectedBar = null;
        }
    if (bar) {
        //put a placeholder object ("XXX" for now) in the position
        //where the bar was, and put the bar in the top position
        //so it shows topmost
        selectedBar = bar;
        canvasS.insertAt(placeholder, selectedBar.XZIndex, true);
        canvasS.add(bar);
        canvasS.renderAll();
        }
    }

canvasS.on({
     'mouse:move': function(e) {
        //hook up dynamic zorder
        if (!e.target) return;
        if (bars[e.target])
            selectBar(e.target);
        else
            selectBar(null);
        },
    });

var objcount = canvasS.getObjects().length;

//create bars
for (var i = 0; i < 20; ++i) {
    var rect = new fabric.Rect({
      left: 0,
      top: 0,
      rx: 3,
      ry: 3,
      stroke: 'red',
      width: 200,
      height: 25
    });
    rect.setGradientFill({
      x1: 0,
      y1: 0,
      x2: 0,
      y2: rect.height,
      colorStops: {
        0: '#080',
        1: '#fff'
      }
    });
    var text = new fabric.Text("Bar number " + (i+1), {
        fontSize: 12
    });
    var group = new fabric.Group([ rect, text ], {
      left: i + 101,
      top: i * 4 + 26
    });
    group.hasControls = group.hasBorders = false;

    //our properties (not part of fabric)
    group.XBar = rect;
    group.XZIndex = objcount++;

    canvasS.add(group);
    bars[group] = i;
    }
canvasS.renderAll();

Body:
After I added a line object, I was make the line appear under the object using:

canvas.add(line);
canvas.sendToBack(line);

Other options are

canvas.sendBackwards

canvas.sendToBack

canvas.bringForward

canvas.bringToFront

see:  https://github.com/fabricjs/fabric.js/issues/135


问:
Dynamics 365 virtual entities from Cosmos DB
The “Azure Cosmos DB for DocumentDB API Data Provider” does not seem to be actively maintained and I was not able to get it to work in D365 CE. I would like to use my Cosmos TB to be the source for some virtual entities in my CRM and the only way I can get this to work is writing a data provider plugin or creating an api. Is anyone aware of any other method to accomplish this?</p>

答:
I believe you will have to expose your database or
Particular table as Odata v4.0 webapi.
Or you could create your own data provider and expose your data through that data provider.

This is how data shall be available in virtual entity.
Note: your odata or custom data provider should respect field types of Crm.
For ex: 1 mandatory EDM.Guid field and so
On.


问:
Django file upload with "application/octet-stream" content-type
I have a 3rd side service which making a POST request with file to my Django application.To success upload to Django application request must have 'multipart/form-data' content type but content type is 'octet-stream' in my case and Request.FILES is always empty. How can i receive file with 'octet-stream' content type in django?

request.content_type # is octet-stream
form = UploadFileForm(request.POST, files=request.FILES)
file = form.cleaned_data[file_name]
```

答:
If anybody stuck too I found a some solution. You can just read data as bytes and then save it to file</p>

```<code>with open(file_name, 'wb') as output:
    output.write(request.read())
</code>```

Body:
If anybody stuck too I found a some solution. You can just read data as bytes and then save it to file

with open(file_name, 'wb') as output:
    output.write(request.read())


问:
Bit twiddling: which bit is set?
I have a 64-bit unsigned integer with exactly 1 bit set. I’d like to assign a value to each of the possible 64 values (in this case, the odd primes, so 0x1 corresponds to 3, 0x2 corresponds to 5, …, 0x8000000000000000 corresponds to 313).

It seems like the best way would be to convert 1 → 0, 2 → 1, 4 → 2, 8 → 3, …, 263 → 63 and look up the values in an array. But even if that’s so, I’m not sure what the fastest way to get at the binary exponent is. And there may be more efficient ways, still.

This operation will be used 1014 to 1016 times, so performance is a serious issue.

答:
This is for 32 bit, java, but it should be possible to adapt it to 64 bit.
It assume this will be the fastest cause there is no branching involved.

```<code>static public final int msb(int n) {
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n >>>= 1;
    n += 1;
    return n;
}

static public final int msb_index(int n) {

    final int[] multiply_de_bruijn_bit_position = {
        0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
        31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
    };
    return multiply_de_bruijn_bit_position[(msb(n) * 0x077CB531) >>> 27];
}
</code>```

Here is more information from: http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup

```<code>// Count the consecutive zero bits (trailing) on the right with multiply and lookup

unsigned int v;  // find the number of trailing zeros in 32-bit v
int r;           // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
  0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];

// Converting bit vectors to indices of set bits is an example use for this.
// It requires one more operation than the earlier one involving modulus
// division, but the multiply may be faster. The expression (v & -v) extracts
// the least significant 1 bit from v. The constant 0x077CB531UL is a de Bruijn
// sequence, which produces a unique pattern of bits into the high 5 bits for
// each possible bit position that it is multiplied against. When there are no
// bits set, it returns 0. More information can be found by reading the paper
// Using de Bruijn Sequences to Index 1 in a Computer Word by
// Charles E. Leiserson, Harald Prokof, and Keith H. Randall.
</code>```

and as last:
http://supertech.csail.mit.edu/papers/debruijn.pdf

Title: Bit twiddling: which bit is set?

Body:
This is for 32 bit, java, but it should be possible to adapt it to 64 bit.
It assume this will be the fastest cause there is no branching involved.

static public final int msb(int n) {
    n |= n >>> 1;
    n |= n >>> 2;
    n |= n >>> 4;
    n |= n >>> 8;
    n |= n >>> 16;
    n >>>= 1;
    n += 1;
    return n;
}

static public final int msb_index(int n) {

    final int[] multiply_de_bruijn_bit_position = {
        0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
        31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
    };
    return multiply_de_bruijn_bit_position[(msb(n) * 0x077CB531) >>> 27];
}

Here is more information from: http://graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup

// Count the consecutive zero bits (trailing) on the right with multiply and lookup

unsigned int v;  // find the number of trailing zeros in 32-bit v
int r;           // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
  0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
  31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];

// Converting bit vectors to indices of set bits is an example use for this.
// It requires one more operation than the earlier one involving modulus
// division, but the multiply may be faster. The expression (v & -v) extracts
// the least significant 1 bit from v. The constant 0x077CB531UL is a de Bruijn
// sequence, which produces a unique pattern of bits into the high 5 bits for
// each possible bit position that it is multiplied against. When there are no
// bits set, it returns 0. More information can be found by reading the paper
// Using de Bruijn Sequences to Index 1 in a Computer Word by
// Charles E. Leiserson, Harald Prokof, and Keith H. Randall.

and as last:
http://supertech.csail.mit.edu/papers/debruijn.pdf


问:
Add textbox when button is pressed
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

```<code> <input name="userfile[]" type="file" /><br />
    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" /><br />
</code>```

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

答:
You can write a JS function for adding textboxes and call the function when the button is pressed.

The function should go along these lines....

```<code>var count;
function functionName()
{
   count++;
   document.Write('<input type="text"  value="..." name="imagedescriptor'+count+'" max..');
}
</code>```

Hopefully it works.

Title: Add textbox when button is pressed

Body:
I know this can be accomplished in Javascript (I hope!) I have a couple of forms on my page, but I cannot guess how many the user will need, so is there some magic which can be done in javascript which when a button is pressed this:

 <input name="userfile[]" type="file" />

    <input type="text" value="Description goes here." name="imagedescription2" maxlength="20" onfocus="this.value = '';" />

Is added to a designated area? Keeping in mind adding a number onto the name if the  button is pressed eg name="imagedescription3" next name="imagedescription4" and so forth
This may be posted around the internet, I know it would be, I just don't know how to thorougly phrase my question

Body:
You can write a JS function for adding textboxes and call the function when the button is pressed.

The function should go along these lines....

var count;
function functionName()
{
   count++;
   document.Write('<input type="text"  value="..." name="imagedescriptor'+count+'" max..');
}

Hopefully it works.


问:
How to download NuGet packages programatically from .NET Core, .NET Standard projects
I want to download Nuget packages programmatically from the .NET core/.NET Standard projects

We have some console apps that are tools NuGet packages and I want to download those and start them as a background process.

答:
Best way to achieve it is by referring NugetDownloader Nuget package  in Project and use it to download any package programmatically(in dotnet core as well)

```<code>Install-Package NugetDownloader
</code>```

Source code and help guide on the same is available at :
https://github.com/paraspatidar/NugetDownloader

Here is a quick sample on how to achieve it :

string packageName="Newtonsoft.json";
string version="10.2.1.0"; \\optional

\\initilize NugetEngine from NugetDownloader namespaces

NugetEngine nugetEngine = new NugetEngine();
nugetEngine.GetPackage(packageName, version).Wait();
```

sample client is also available at https://github.com/paraspatidar/NugetDownloader/tree/master/NugetDownloaderTestConsole

Alternately In case if you want to build your Nugetdownloader engine from scratch , then you might also refer https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script/Description/DotNet/PackageManager.cs as it has something similar implementation , but that too much of code understanding and extraction.

Body:
Best way to achieve it is by referring NugetDownloader Nuget package  in Project and use it to download any package programmatically(in dotnet core as well)

Install-Package NugetDownloader

Source code and help guide on the same is available at :
https://github.com/paraspatidar/NugetDownloader

Here is a quick sample on how to achieve it :

string packageName="Newtonsoft.json";
string version="10.2.1.0"; \\optional

\\initilize NugetEngine from NugetDownloader namespaces

NugetEngine nugetEngine = new NugetEngine();
nugetEngine.GetPackage(packageName, version).Wait();

sample client is also available at https://github.com/paraspatidar/NugetDownloader/tree/master/NugetDownloaderTestConsole

Alternately In case if you want to build your Nugetdownloader engine from scratch , then you might also refer https://github.com/Azure/azure-functions-host/blob/dev/src/WebJobs.Script/Description/DotNet/PackageManager.cs as it has something similar implementation , but that too much of code understanding and extraction.


问:
Convert Tensorflow graph to CoreML
I'm trying to convert a Tensorflow graph to CoreML and I'm following this tutorial. There's this bit of code that I don't quite understand:

#include <metal_stdlib>
using namespace metal;

kernel void swish(
  texture2d_array<half, access::read> inTexture [[texture(0)]],
  texture2d_array<half, access::write> outTexture [[texture(1)]],
  ushort3 gid [[thread_position_in_grid]])
{
  if (gid.x >= outTexture.get_width() ||
      gid.y >= outTexture.get_height()) {
    return;
  }

  const float4 x = float4(inTexture.read(gid.xy, gid.z));
  const float4 y = x / (1.0f + exp(-x));
  outTexture.write(half4(y), gid.xy, gid.z);
}
```

What I don't understand is the use of gid here. Isn't the grid 2 dimensional? What does gid.z signify? Isn't gid.x is the current x-coordinate of the current pixel?

答:
gid.x and gid.y are the x/y coordinate of the current pixel. So when you do a texture.read(gid.xy) it gives you 4 channels worth of pixel data.

But the "images" used in neural networks may have many more than 4 channels. That's why the data type for the textures is texture2d_array<> instead of just texture2d<>.

The gid.z value refers to the index of the texture "slice" in this array. If the image/tensor has 32 channels, then there are 8 texture slices (because each texture stores up to 4 channels of data).

So the grid really is three dimensional: (x, y, slice).

Title: Convert Tensorflow graph to CoreML

Body:
I'm trying to convert a Tensorflow graph to CoreML and I'm following this tutorial. There's this bit of code that I don't quite understand:

#include <metal_stdlib>
using namespace metal;

kernel void swish(
  texture2d_array<half, access::read> inTexture [[texture(0)]],
  texture2d_array<half, access::write> outTexture [[texture(1)]],
  ushort3 gid [[thread_position_in_grid]])
{
  if (gid.x >= outTexture.get_width() ||
      gid.y >= outTexture.get_height()) {
    return;
  }

  const float4 x = float4(inTexture.read(gid.xy, gid.z));
  const float4 y = x / (1.0f + exp(-x));
  outTexture.write(half4(y), gid.xy, gid.z);
}

What I don't understand is the use of gid here. Isn't the grid 2 dimensional? What does gid.z signify? Isn't gid.x is the current x-coordinate of the current pixel?


问:
Referential integrity in SQL Server
Can we set up referential integrity between two databases in SQL Server?
If yes, how can we do this?</p>

答:
From Microsoft documentation:

FOREIGN KEY constraints can reference only tables within the same database on the same server. Cross-database referential integrity must be implemented through triggers. For more information, see CREATE TRIGGER (Transact-SQL).

Source:

Create Foreign Key Relationships

Title: Referential integrity in SQL Server


问:
How to call an ASP.NET WebMethod in a UserControl (.ascx)
Is it possible to place a WebMethod in an ascx.cs file (for a UserControl)  and then call it from client-side jQuery code?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.

Example: In ArticleList.ascx.cs I have the following code:

```<code>[WebMethod]
public static string HelloWorld()
{
    return "helloWorld";
}
</code>```

In ArticleList.ascx file there I have the call to the WebMethod as follows:

```<code>$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
            {
                var msg;
                if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "ArticleList.ascx/HelloWorld",
            success: function(msg) {
                alert(msg);
            }
        });
</code>```

and the error from firebug is:

```<code><html>
<head>
    <title>This type of page is not served.</title>
</code>```

How can I sucessfully call the server-side WebMethod from my client-side jQuery code?

答: Your method needs to be in an .aspx (or I think .ashx or .asmx will work as well). Since it's actually making a new call to the web server, IIS has to handle the request, and IIS will not respond to calls to .ascx files.</p>

Body:
Is it possible to place a WebMethod in an ascx.cs file (for a UserControl)  and then call it from client-side jQuery code?

For some reasons I can't place the WebMethod code in an .asmx or .aspx file.

Example: In ArticleList.ascx.cs I have the following code:

[WebMethod]
public static string HelloWorld()
{
    return "helloWorld";
}

In ArticleList.ascx file there I have the call to the WebMethod as follows:

$.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataFilter: function(data)//makes it work with 2.0 or 3.5 .net
            {
                var msg;
                if (typeof (JSON) !== 'undefined' &&
                typeof (JSON.parse) === 'function')
                    msg = JSON.parse(data);
                else
                    msg = eval('(' + data + ')');
                if (msg.hasOwnProperty('d'))
                    return msg.d;
                else
                    return msg;
            },
            url: "ArticleList.ascx/HelloWorld",
            success: function(msg) {
                alert(msg);
            }
        });

and the error from firebug is:

    <title>This type of page is not served.</title>

How can I sucessfully call the server-side WebMethod from my client-side jQuery code?


问:
How to use object as variable of class as ArrayList?
I've Course Class that conatains name, teacher, students[];

```<code>public class Course implements Comparable<Course> {
variables ...
private Student[] students;

public Course(variables... int maxStudents) {
variables...
this.maxStudents = maxStudents;
students = new Student[maxStudents];
}
</code>```

I've courseGrades class

```<code>public class GradesList{
private Course course;
private ArrayList<Integer> grades;

public ListaOcen(Course course)
{
    this.course = course;
    grades = new ArrayList<>();
}
</code>```

And also I've student class

```<code>public class Student extends Person {
variables...
private ArrayList<ListaOcen> degresList;

public Student(variables...) {
    super(variables...);
    course = new Course[5];
    degresList = new ArrayList<>();

}
</code>```

I can't figure out, how exactly should I pass courseGrades class as variable of student class and how later on I can fill that grades list. So far I've created this function

```<code>public void addDeggre(Integer deggre) {
    if(deggre > 1 && deggre < 7)
        grades.add(deggre);
}
</code>```

答:
To use a map in the Course class, include :

```<code>   private TreeMap<Student, Integer> grades = new TreeMap<>();
   private ArrayList<Student> students = new ArrayList<>();
</code>```

Then the Course class has a method to add a student, and to set the grade, and get the grade:

```<code>   public void addStudent( Student s ) {
      students.add(s);
      grades.put(s,0);
   }
   public void setGrade( Student s, int grade ) {
      grades.replace(s,grade);
   }
   public int getGrade( Student s ) {
      return grades.get(s).intvalue();
   }
</code>```

Of course, you need to add code to handle errors, such as for setGrade() and getGrade() if the passed Student is not in the map.

Body:
I've Course Class that conatains name, teacher, students[];

public class Course implements Comparable<Course> {
variables ...
private Student[] students;

public Course(variables... int maxStudents) {
variables...
this.maxStudents = maxStudents;
students = new Student[maxStudents];
}

I've courseGrades class

public class GradesList{
private Course course;
private ArrayList<Integer> grades;

public ListaOcen(Course course)
{
    this.course = course;
    grades = new ArrayList<>();
}

And also I've student class

public class Student extends Person {
variables...
private ArrayList<ListaOcen> degresList;

public Student(variables...) {
    super(variables...);
    course = new Course[5];
    degresList = new ArrayList<>();

}

I can't figure out, how exactly should I pass courseGrades class as variable of student class and how later on I can fill that grades list. So far I've created this function

public void addDeggre(Integer deggre) {
    if(deggre > 1 && deggre < 7)
        grades.add(deggre);
}

Body:
To use a map in the Course class, include :

   private TreeMap<Student, Integer> grades = new TreeMap<>();
   private ArrayList<Student> students = new ArrayList<>();

Then the Course class has a method to add a student, and to set the grade, and get the grade:

   public void addStudent( Student s ) {
      students.add(s);
      grades.put(s,0);
   }
   public void setGrade( Student s, int grade ) {
      grades.replace(s,grade);
   }
   public int getGrade( Student s ) {
      return grades.get(s).intvalue();
   }

Of course, you need to add code to handle errors, such as for setGrade() and getGrade() if the passed Student is not in the map.


问:
How can I delete the line below in Font Awesome icon?
I placed an icon cart from Font Awesome in my Navigation Bar. The problem is that this line appears to the left below in the cart icon when I go over with my mouse. I tried a lot of things but I could not find a way to remove this line:

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="main.css">

        <title>Σκοτεινή Πλευρά</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">

                        2

```

<pre class="lang-css prettyprint-override"><code>.Basket {
    display: inline-block;
    text-align: center;
    margin-right: 11px;
    margin-bottom: -6px;
}

.Basket a {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    margin-top: 100px;
    font-size: 30px;
    width: 40px;
    height: 40px;
    color: #332f25;
    transition: color 0.3s ease;
    text-decoration: none;
}

.Basket_Number {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: -15px;
    left: 35px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #fe4c50;
    font-size: 12px;
    color: white;
}
</code>```

答:
Use the :hover selector to get rid of the underline when hovering</p>

```<code>.Basket a:hover {
    text-decoration: none;
}
</code>```

Body:
I placed an icon cart from Font Awesome in my Navigation Bar. The problem is that this line appears to the left below in the cart icon when I go over with my mouse. I tried a lot of things but I could not find a way to remove this line:

<!DOCTYPE html>

        <link rel="stylesheet" type="text/css" href="main.css">

        <title>Σκοτεινή Πλευρά</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.4.1/css/all.css">

                        2

.Basket {
    display: inline-block;
    text-align: center;
    margin-right: 11px;
    margin-bottom: -6px;
}

.Basket a {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    margin-top: 100px;
    font-size: 30px;
    width: 40px;
    height: 40px;
    color: #332f25;
    transition: color 0.3s ease;
    text-decoration: none;
}

.Basket_Number {
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: absolute;
    top: -15px;
    left: 35px;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: #fe4c50;
    font-size: 12px;
    color: white;
}

Body:
Use the :hover selector to get rid of the underline when hovering

.Basket a:hover {
    text-decoration: none;
}


问:
Is there a way to use a variable to name a data frame in R?
Basically I want to be able to do this.

```<code>a <- 1
data_frame_1 <- "some data"
a <- a+1
data_frame_2 <- "some data"
</code>```

Where the 1 and 2 at the end of the data frame names are coming from the values of a. Is there a way to do this?

答:
You can do this using assign. Check out these links for reference.

Error in  : target of assignment expands to non-language object

Create a variable name with "paste" in R?

```<code>assign(paste0("data_frame_",a), "some_data")
</code>```

Body:
Basically I want to be able to do this.

a <- 1
data_frame_1 <- "some data"
a <- a+1
data_frame_2 <- "some data"

Where the 1 and 2 at the end of the data frame names are coming from the values of a. Is there a way to do this?

Body:
You can do this using assign. Check out these links for reference.

Error in  : target of assignment expands to non-language object

Create a variable name with "paste" in R?

assign(paste0("data_frame_",a), "some_data")


问:
How to intersect two queries in MySQL
I have 3 tables in the database as follows:

```<code>airlines
+----+-----------------+-------+---------+
| Id | Name            | Abbr  | Country |
+----+-----------------+-------+---------+
| 1  | United Airlines | UAL   | USA     |
| 2  | US Airways      | USAir | USA     |
|... | ...             | ...   | ...     |
+----+-----------------+-------+---------+
</code>```

```<code>airports
+--------------+------+-------------+---------------+-------+
| City         | Code | Name        | Country       | CAbbr |
+--------------+------+-------------+---------------+-------+
| Apalachicola | AAF  | Municipal   | United States | US    |
| Abilene      | ABI  | US Airways  | United States | US    |
| ...          | ...  | ...         | ...           | ...   |
+--------------+------+-------------+---------------+-------+
</code>```

```<code>flights
+---------+----------+--------+-------------+
| Airline | FlightNo | Source | Destination |
+---------+----------+--------+-------------+
| 1       | 28       | APG    | ASY         |
| 1       | 44       | CVO    | ACV         |
| ...     | ...      | ...    | ...         |
+---------+----------+--------+-------------+
</code>```

I am trying to report all pairs of airports served by both Frontier and JetBlue. Each airport pair must be reported exactly once (if a pair X,Y is reported, than a pair Y,X is redundant and should not be reported).

I believe I understand how to get the Frontier flights and JetBlue flights separately:

```<code>SELECT  ap1.Code, ap2.Code
FROM    flights f, airports ap1, airports ap2, airlines al
WHERE   ap1.Code = f.Source
AND     ap2.Code = f.Destination
AND     f.Airline = al.Id
AND     al.Abbr = 'Frontier'
ORDER BY ap1.Code ASC;

SELECT  ap1.Code, ap2.Code
FROM    flights f, airports ap1, airports ap2, airlines al
WHERE   ap1.Code = f.Source
AND     ap2.Code = f.Destination
AND     f.Airline = al.Id
AND     al.Abbr = 'JetBlue'
ORDER BY ap1.Code ASC;
</code>```

But I don't understand how to get the Intersection between them. I've tried both LEFT JOIN and WHERE EXISTS but I'm doing something wrong because I'm getting what looks to be more of a Union than an Intersection. Here is my most recent attempt(definitely wrong).

```<code>SELECT  ap1.Code, ap2.Code AS code
FROM    airports ap1, airports ap2
WHERE
EXISTS (SELECT  ap1.Code, ap2.Code
        FROM    flights f, airports ap1, airports ap2, airlines al
        WHERE   ap1.Code = f.Source
        AND     ap2.Code = f.Destination
        AND     f.Airline = al.Id
        AND     al.Abbr = 'Frontier') AND
EXISTS (SELECT  ap1.Code, ap2.Code
        FROM    flights f, airports ap1, airports ap2, airlines al
        WHERE   ap1.Code = f.Source
        AND     ap2.Code = f.Destination
        AND     f.Airline = al.Id
        AND     al.Abbr = 'JetBlue')
ORDER BY ap1.Code ASC;
</code>```

And once the intersection is found I'm not quite sure how to go about making X,Y pairs and Y,X pairs distinct because DISTINCT wouldn't recognize the tuples as the same.

Any help would be much appreciated.

答:
If you need both then you could try using IN for the airlines:

```<code>SELECT  ap1.Code, ap2.Code
FROM    flights f
INNER JOIN airports ap1 ON  ap1.Code = f.Source
INNER JOIN airports ap2 ON ap2.Code = f.Destination
INNER JOIN airlines al ON  f.Airline = al.Id
WHERE  al.Abbr IN ( 'Frontier', 'JetBlue')
ORDER BY ap1.Code ASC;
</code>```

You should avoid old (1992) implicit join syntax based on where and use explicit join syntax.

Title: How to intersect two queries in MySQL

Body:
I have 3 tables in the database as follows:

airlines
+----+-----------------+-------+---------+
| Id | Name            | Abbr  | Country |
+----+-----------------+-------+---------+
| 1  | United Airlines | UAL   | USA     |
| 2  | US Airways      | USAir | USA     |
|... | ...             | ...   | ...     |
+----+-----------------+-------+---------+

airports
+--------------+------+-------------+---------------+-------+
| City         | Code | Name        | Country       | CAbbr |
+--------------+------+-------------+---------------+-------+
| Apalachicola | AAF  | Municipal   | United States | US    |
| Abilene      | ABI  | US Airways  | United States | US    |
| ...          | ...  | ...         | ...           | ...   |
+--------------+------+-------------+---------------+-------+

flights
+---------+----------+--------+-------------+
| Airline | FlightNo | Source | Destination |
+---------+----------+--------+-------------+
| 1       | 28       | APG    | ASY         |
| 1       | 44       | CVO    | ACV         |
| ...     | ...      | ...    | ...         |
+---------+----------+--------+-------------+

I am trying to report all pairs of airports served by both Frontier and JetBlue. Each airport pair must be reported exactly once (if a pair X,Y is reported, than a pair Y,X is redundant and should not be reported).

I believe I understand how to get the Frontier flights and JetBlue flights separately:

SELECT  ap1.Code, ap2.Code
FROM    flights f, airports ap1, airports ap2, airlines al
WHERE   ap1.Code = f.Source
AND     ap2.Code = f.Destination
AND     f.Airline = al.Id
AND     al.Abbr = 'Frontier'
ORDER BY ap1.Code ASC;

SELECT  ap1.Code, ap2.Code
FROM    flights f, airports ap1, airports ap2, airlines al
WHERE   ap1.Code = f.Source
AND     ap2.Code = f.Destination
AND     f.Airline = al.Id
AND     al.Abbr = 'JetBlue'
ORDER BY ap1.Code ASC;

But I don't understand how to get the Intersection between them. I've tried both LEFT JOIN and WHERE EXISTS but I'm doing something wrong because I'm getting what looks to be more of a Union than an Intersection. Here is my most recent attempt(definitely wrong).

SELECT  ap1.Code, ap2.Code AS code
FROM    airports ap1, airports ap2
WHERE
EXISTS (SELECT  ap1.Code, ap2.Code
        FROM    flights f, airports ap1, airports ap2, airlines al
        WHERE   ap1.Code = f.Source
        AND     ap2.Code = f.Destination
        AND     f.Airline = al.Id
        AND     al.Abbr = 'Frontier') AND
EXISTS (SELECT  ap1.Code, ap2.Code
        FROM    flights f, airports ap1, airports ap2, airlines al
        WHERE   ap1.Code = f.Source
        AND     ap2.Code = f.Destination
        AND     f.Airline = al.Id
        AND     al.Abbr = 'JetBlue')
ORDER BY ap1.Code ASC;

And once the intersection is found I'm not quite sure how to go about making X,Y pairs and Y,X pairs distinct because DISTINCT wouldn't recognize the tuples as the same.

Any help would be much appreciated.

Body:
If you need both then you could try using IN for the airlines:

SELECT  ap1.Code, ap2.Code
FROM    flights f
INNER JOIN airports ap1 ON  ap1.Code = f.Source
INNER JOIN airports ap2 ON ap2.Code = f.Destination
INNER JOIN airlines al ON  f.Airline = al.Id
WHERE  al.Abbr IN ( 'Frontier', 'JetBlue')
ORDER BY ap1.Code ASC;

You should avoid old (1992) implicit join syntax based on where and use explicit join syntax.


问:
Linkedin Sharing web page does not show summary
We have been sharing our website pages and articles to LinkedIn for almost 4 years using

https://www.linkedin.com/shareArticle?mini=true&url=https://example.com/page1/

Until recently, the share block would appear with an image, caption and summary. Just as in Facebook. But now, we find that the summary does not show. I know many have raised this same concern here. One solution I saw in this forum is to switch to forcing visitors to sign into our LinkedIn app and post the status via REST API. My question is, Is this really necessary. We don't have a login feature for our website and to force people to login to LinkedIn app just to show description which is already part of the og tags on the page. Surely someone from LinkedIn can respond to this issue since so many have raised it.

答:
You can use Post Inspector (https://www.linkedin.com/post-inspector/) to preview how your posts will be shared on LinkedIn.

Alternatively, you can use the Share Plugin (https://learn.microsoft.com/en-us/linkedin/consumer/integrations/self-serve/plugins/share-plugin) to add a widget for users to easily share content on LinkedIn.


问:
validation for primefaces editor
My first problem with primefaces editor is it does not accept the text from a MS word document in chrome and explorer but works fine in Firefox. Is there a way that it directly accept the content from MS word instead of using page as text option in p:editor.

My code looks like:

```<code>   <p:editor id="courseSummary" value="#{course.courseSummary.courseSummary}"    required="true" requiredMessage="#{messageBundle['productManagement.product.descriptionRequired']}"/>
</code>```

My second one is I entered some string value which has many lines and pressed save which stored the value into my backing bean. Then if I manually clear my editor on UI, and if I don't clear the lines, it does not validate but stores in to the string courseSummaryas   br/>
.
Can someone help me how to go about in this?

答:
CKeditor along with some java script and FacesContext should replace p:editor. Which supports copy from MSWord and HTML content.</p>

```<code> FacesContext fc = FacesContext.getCurrentInstance();
 Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
 reviewCommentsText = params.get("myObj");
</code>```

Title: validation for primefaces editor

Body:
My first problem with primefaces editor is it does not accept the text from a MS word document in chrome and explorer but works fine in Firefox. Is there a way that it directly accept the content from MS word instead of using page as text option in p:editor.

My code looks like:

My second one is I entered some string value which has many lines and pressed save which stored the value into my backing bean. Then if I manually clear my editor on UI, and if I don't clear the lines, it does not validate but stores in to the string courseSummaryas   br/>
.
Can someone help me how to go about in this?

Body:
CKeditor along with some java script and FacesContext should replace p:editor. Which supports copy from MSWord and HTML content.

 FacesContext fc = FacesContext.getCurrentInstance();
 Map<String,String> params = fc.getExternalContext().getRequestParameterMap();
 reviewCommentsText = params.get("myObj");


答:
```<code>SELECT apPairs.*, ap1.stuff, ap2.stuff
FROM (
   SELECT LEAST(f.Source, f.Destination) AS ap1Code
      , GREATEST(f.Source, f.Destination) AS ap2Code
   FROM airlines AS al
   INNER JOIN flights AS f ON al.Id = f.Airline
   WHERE al.Abbr IN ('Frontier', 'JetBlue')
   GROUP BY ap1Code, ap2Code
   HAVING COUNT(DISTINCT al.Abbr) = 2  -- Served by both airlines
) AS apPairs
INNER JOIN airports AS ap1 ON apPairs.ap1Code = ap1.Code
INNER JOIN airports AS ap2 ON apPairs.ap1Code = ap2.Code
;
</code>```

I used LEAST and GREATEST to merge any (X,Y) and (Y,X) redundancies; those functions are MySQL specific though, so in other RDBMS you may need to create your own versions of those. Note: depending on how this data is being used, you may want to double-check the assumption that x->y and y->x pairs are really redundant; it is possible (at least in reality) that an airline could have an X->Y->Z->X route, but no direct Y->X.

COUNT(DISTINCT) in the HAVING clause makes sure to only count each airline abbreviation only once, so 100 flights will not inflate the numbers. It's use in the query makes sure you get airports served by both airlines, rather than
either airline.

Since the query in apPairs already has the codes, you don't even need to do the outer query; but I added in case you need information from airports table that you didn't not feel the need to specify in the question.

Title: How to intersect two queries in MySQL

Body:
SELECT apPairs.*, ap1.stuff, ap2.stuff
FROM (
   SELECT LEAST(f.Source, f.Destination) AS ap1Code
      , GREATEST(f.Source, f.Destination) AS ap2Code
   FROM airlines AS al
   INNER JOIN flights AS f ON al.Id = f.Airline
   WHERE al.Abbr IN ('Frontier', 'JetBlue')
   GROUP BY ap1Code, ap2Code
   HAVING COUNT(DISTINCT al.Abbr) = 2  -- Served by both airlines
) AS apPairs
INNER JOIN airports AS ap1 ON apPairs.ap1Code = ap1.Code
INNER JOIN airports AS ap2 ON apPairs.ap1Code = ap2.Code
;

I used LEAST and GREATEST to merge any (X,Y) and (Y,X) redundancies; those functions are MySQL specific though, so in other RDBMS you may need to create your own versions of those. Note: depending on how this data is being used, you may want to double-check the assumption that x->y and y->x pairs are really redundant; it is possible (at least in reality) that an airline could have an X->Y->Z->X route, but no direct Y->X.

COUNT(DISTINCT) in the HAVING clause makes sure to only count each airline abbreviation only once, so 100 flights will not inflate the numbers. It's use in the query makes sure you get airports served by both airlines, rather than
either airline.

Since the query in apPairs already has the codes, you don't even need to do the outer query; but I added in case you need information from airports table that you didn't not feel the need to specify in the question.


问:
Missing Frames Tab On Network View in Chrome
I'm running Chrome 74.0.x on multiple computers and cannot find a Frames tab in the network view on any of them.  I'm aware of the issue where data within the Frames tab is rolled-up, but I simply have no Frames tab there at all.

I can see tabs for Headers, Messages and Timings, which is great and working, but am trying to see websocket Pings (which I've read would be within Frames).

What am I missing here??

答:
Answering my own question.  TL/DR: I am presuming that what I was looking for does not exist within Chrome (any more, at least).  And, I'm going to send a "normal" message as a form of ping/pong for now.

This came up because Heroku (my host) will time out within 50 seconds or so if a websocket appears inactive.  Ping/pong seems designed for this.

However, it's not clear if the definition of a websocket ping/pong is nailed down, let alone supported by tools.  See this discussion: Sending websocket ping/pong frame from browser

There are references that explain how ping/pong control codes should be implemented. See the aptly-named "Pings and Pongs: The Heartbeat of WebSockets" at https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#Pings_and_Pongs_The_Heartbeat_of_WebSockets.  And, the RFC6455 (https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2) states that "A Ping frame may serve either as a keepalive or as a means to verify that the remote endpoint is still responsive".

Note that I have pings working, as in, I am sending them to the client (Chrome), Heroku is not timing out, and the client is staying alive.  However, I can't see any activity on the browser end.  It's automagic, which bugs me.

It seems the functionality to drill down that did exist (chrome://net-internals) was removed. Apparently as a consolation prize, there is now a built-in tool (chrome://net-export) which allows one to capture network activity, and then a supporting site (https://netlog-viewer.appspot.com/#import) that allows those logs to be analyzed (painful).  They show traffic from many entities that chrome is aware of, including websocket messages, but surprisingly do not show any of the pings I was sending.

In the near term I am abandoning the idea of using ping/pong control codes and just using standard messages as a form of simulating a keep-alive, since they work and I can see them in Chrome.

Any comments which help me understand this better would be greatly appreciated.


问:
Restore or access workspaces from MySQL Workbench
Using MySQL Workbench 6.3.8 build 1228 CE (64-bit), on Windows 10 Pro, version 1803, build 17134.112.

I want to restore my old workspaces in MySQL Workbench. If that is not possible, I will be happy with just being able to access them as text files.

I guess my laptop had an unusual power-off or reset last night. Normally I put it in Sleep mode, but when I opened it this morning it had reset itself: all applications had quit.

I re-opened Workbench, and got this error message:

saying that my workspaces could not be opened.

I can't get the full text of the error message, so I don't know exactly where Workbench is looking, but using Windows Explorer I could navigate to:

```<code>C:\Users\JamesBarton\AppData\Roaming\MySQL\Workbench\sql_workspaces
</code>```

which looks right to me, and contains .workspace and .autosave directories.

I've backed up the Workbench\ directory, and then tried just removing the .autosave directories, to force the use of the .workspace directories, but when I did that, Workbench still just opened one empty tab. The first .workspace directory contains 95 files, including 45 .scratch files totalling 107kb.

Is it possible to check exactly where MySQL Workbench is looking for workspaces?

Can I force it to open a workspace directly, or at least show me why it can't open a workspace? If that is not possible, can I somehow extract the SQL from the .scratch files? Thanks.

答:
Even though my desktop has crashed several times in the past 3 years (either power-related or system) this last time was the first time MySQL Workbench had issues with a workspace (apparently the 2 I had open at the time?). When I investigated why I discovered that all the .info and .scratch files in those workspaces were written with only NUL characters so no easy recovery of my tabs is possible. Grrr.

I will have to recover everything from scratch (haha) by going through the sql_history and possibly log folders and copy/paste as necessary back into the GUI.

Body:
Using MySQL Workbench 6.3.8 build 1228 CE (64-bit), on Windows 10 Pro, version 1803, build 17134.112.

I want to restore my old workspaces in MySQL Workbench. If that is not possible, I will be happy with just being able to access them as text files.

I guess my laptop had an unusual power-off or reset last night. Normally I put it in Sleep mode, but when I opened it this morning it had reset itself: all applications had quit.

I re-opened Workbench, and got this error message:

saying that my workspaces could not be opened.

I can't get the full text of the error message, so I don't know exactly where Workbench is looking, but using Windows Explorer I could navigate to:

C:\Users\JamesBarton\AppData\Roaming\MySQL\Workbench\sql_workspaces

which looks right to me, and contains .workspace and .autosave directories.

I've backed up the Workbench\ directory, and then tried just removing the .autosave directories, to force the use of the .workspace directories, but when I did that, Workbench still just opened one empty tab. The first .workspace directory contains 95 files, including 45 .scratch files totalling 107kb.

Is it possible to check exactly where MySQL Workbench is looking for workspaces?

Can I force it to open a workspace directly, or at least show me why it can't open a workspace? If that is not possible, can I somehow extract the SQL from the .scratch files? Thanks.


问:
How to start mapping a nested json from a certain index and map it back to that index-1 value

I want to map my nested json from a certain index

For example if my json is the following:

```<code>{"data":[{id:1,name:"NAV"},{id:2,name:"Rick"},{id:3,name:"Ceil"}]}
</code>```

I want to start mapping this json from 1st index i.e. id =1 name :rick
and map it till nav so the mapping is in the following order:

{id:2,name:"Rick"}

{id:3,name:"Ceil"}

{id:1,name:"NAV"}

Something like a circular array or queue
I have no idea how to implement this mapping in react native or js.

How I am currently mapping my json

```<code>renderArtciles=()=>{

  return this.state.dataSource.map((item,i)=>{
    <Animated.View key={item._id} >
      <View style={styles.Imagebody}>
        <Image source={{ uri:item.img.data }} style{styles.image}/>
      </View>

      <View  style={styles.inner}>
        <ShareItem id={item._id} />
        <View style={styles.inner}>
          <Text style={styles.titleArrtibute}>Trending</Text>
          <Text style={styles.titleText} >{item.title}</Text>
          <View>
            <Text style={styles.body}>{item.body}</Text>
          </View>
        </View>
      </View >
    </Animated.View>
  });
}
</code>```

答:
Here's a quick way to pop off the first element from an array and push it to the back.

Note: These examples modify the original collection.

If you do not want to modify the original you will need to create a clone of the array first. Or you can go with the "walking the array" approach I've added below.

Overall I do not think you are looking to map in this instance, the real question seems to be sorting or iterating your array in a specific way where it loops.

Once you have sorted or iterated your array you can then do your mapping to extract the data you are after.

Example - Rotate a Single Element

const cats = ['Bob', 'Willy', 'Mini'];
cats.push(cats.shift());
console.log(cats);```
</div>
</div>
</p>

<h2>Example - Rotate Multiple Elements</h2>

<p>This is if you want to cycle more than 1 element from the front to the back of the array (an example has been attached at the bottom to demonstrate cloning an array).</p>

<p>This will cut off the given amount (2 in this example) and then uses the spread operator to push the new cut off items from the array back into the array. We use the spread operator because splice returns an array and we don't want a jagged semi-multidimensional array.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const cats = ['Bob', 'Willy', 'Mini', 'Dingus'];
cats.push(...cats.splice(0, 2));
console.log(cats);</code>```

Example - Nested Data

Since Javascript stores objects by reference we can store variables and apply the same techniques from above to directly modify the original object.

ie: Notice how we assign a new variable data and modify it but log the original object namesInData which is now changed.

const namesInData = {data:[{name: 'Bob'}, {name: 'Willy'}, {name: 'Mini'}]};
const data = namesInData.data;

data.push(data.shift());
console.log(namesInData);```
</div>
</div>
</p>

<h2>Example - Walking the Array with a For Loop & Offset</h2>

<p>We use the modulus operator <code>%</code> so that when <code>i</code> blows past the end of the array it will wrap back to the front.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const cats = ['Bob', 'Willy', 'Mini', 'Dingus'];
const start = 2;
const length = cats.length;

for(let i = start; i < length + start; i++) {
  console.log(cats[i % length]);
}</code>```

Cloning an Array

If you do not want to modify the original array you will need to clone it first.

ES6 Way

Using the spread operator we can assign the spread to a new array.

```<code>const data = [...originalData];
</code>```

Older Non ES6

```<code>const data = originalData.slice();
</code>```

Additional Resources

Pop, Push, Shift, and Unshift Array

Array.prototype.splice not to be confused with slice which does not modify the original array.

Cloning an array

Body:
I want to map my nested json from a certain index

For example if my json is the following:

{"data":[{id:1,name:"NAV"},{id:2,name:"Rick"},{id:3,name:"Ceil"}]}

I want to start mapping this json from 1st index i.e. id =1 name :rick
and map it till nav so the mapping is in the following order:

{id:2,name:"Rick"}

{id:3,name:"Ceil"}

{id:1,name:"NAV"}

Something like a circular array or queue
I have no idea how to implement this mapping in react native or js.

How I am currently mapping my json

renderArtciles=()=>{

  return this.state.dataSource.map((item,i)=>{
    <Animated.View key={item._id} >
      <View style={styles.Imagebody}>
        <Image source={{ uri:item.img.data }} style{styles.image}/>
      </View>

      <View  style={styles.inner}>
        <ShareItem id={item._id} />
        <View style={styles.inner}>
          <Text style={styles.titleArrtibute}>Trending</Text>
          <Text style={styles.titleText} >{item.title}</Text>
          <View>
            <Text style={styles.body}>{item.body}</Text>
          </View>
        </View>
      </View >
    </Animated.View>
  });
}

Body:
Here's a quick way to pop off the first element from an array and push it to the back.

Note: These examples modify the original collection.

If you do not want to modify the original you will need to create a clone of the array first. Or you can go with the "walking the array" approach I've added below.

Overall I do not think you are looking to map in this instance, the real question seems to be sorting or iterating your array in a specific way where it loops.

Once you have sorted or iterated your array you can then do your mapping to extract the data you are after.

Example - Rotate a Single Element

const cats = ['Bob', 'Willy', 'Mini'];
cats.push(cats.shift());
console.log(cats);

Example - Rotate Multiple Elements

This is if you want to cycle more than 1 element from the front to the back of the array (an example has been attached at the bottom to demonstrate cloning an array).

This will cut off the given amount (2 in this example) and then uses the spread operator to push the new cut off items from the array back into the array. We use the spread operator because splice returns an array and we don't want a jagged semi-multidimensional array.

const cats = ['Bob', 'Willy', 'Mini', 'Dingus'];
cats.push(...cats.splice(0, 2));
console.log(cats);

Example - Nested Data

Since Javascript stores objects by reference we can store variables and apply the same techniques from above to directly modify the original object.

ie: Notice how we assign a new variable data and modify it but log the original object namesInData which is now changed.

const namesInData = {data:[{name: 'Bob'}, {name: 'Willy'}, {name: 'Mini'}]};
const data = namesInData.data;

data.push(data.shift());
console.log(namesInData);

Example - Walking the Array with a For Loop & Offset

We use the modulus operator % so that when i blows past the end of the array it will wrap back to the front.

const cats = ['Bob', 'Willy', 'Mini', 'Dingus'];
const start = 2;
const length = cats.length;

for(let i = start; i < length + start; i++) {
  console.log(cats[i % length]);
}

Cloning an Array

If you do not want to modify the original array you will need to clone it first.

ES6 Way

Using the spread operator we can assign the spread to a new array.

const data = [...originalData];

Older Non ES6

const data = originalData.slice();

Additional Resources

Pop, Push, Shift, and Unshift Array

Array.prototype.splice not to be confused with slice which does not modify the original array.

Cloning an array