问:
How to handle JS serialized item in PHP?
Hey guys!
I am having a bit of trouble handling the data from a submitted form that is serialized with JS.
In the form there a textarea fields which users can input any text they want but when they enter & like "apples & oranges", I have trouble handling that.  As we know that JS serializes & to %26 and spaces with a "+" sign.

So now back in PHP, I am trying to put this data into the database and call it back out elsewhere but for the life of me don't know how to handle the special characters properly.

Note that I am also php exploding the data at the "&" sign to make it into an array, then is put into the database as an array.  I tried several methods like urldecode, htmlentities but those don't help because remember I need to explode at "&".

I am serializing in JS because its an AJAX submitting form.

答:
I would use a double replace to prevent using a loop.

First I would replace all & to '####-####' or any other code that is highly unlikely to appear (or use chr(0)).

Then use urldecode() to replace all %26 to & and all + to ' '

Last explode on '####-####' instead of the &


来源: stackexchange

问:
CS0103: The name ' ' does not exist in the current context
I program a  little BMI calculator atm. I coded the basic stuff, which I can work with. I have the problem that my var BMIformula doesnt exist in the context (heading). </p>

<p>Here is my current code: </p>

```<code>        BMIformula = 0;

        Console.WriteLine("Geben Sie Körpergewicht ein: ");
            int bodyWeight = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Geben Sie Ihre Körpergröße in cm ein: ");
            int bodyHeight = Convert.ToInt32(Console.ReadLine());

            // Console.WriteLine(bodyWeight.ToString(), bodyHeight.ToString());

            Console.WriteLine("Ihre Eingaben: Körpergewicht: {0}    Körpergröße: {1}", bodyWeight, bodyHeight);

           //  Console.WriteLine("Der BMI beträgt: {0}");

            Console.ReadLine();

        BMIformula = bodyWeight / bodyHeight * bodyHeight;
        BMIformula.ToString();

        if (BMIformula <= 20)
        {
            Console.WriteLine("Du bist im Untergewicht!");
        }
        else if (BMIformula >= 20 && BMIformula <= 25)
        {
            Console.WriteLine("Du bist im Normalgewicht");
        }
        else if (BMIformula >= 25 && BMIformula <= 30)
        {
            Console.WriteLine("Du bist Übergewichtig");
        }
        else if (BMIformula >= 30 && BMIformula <= 40)
        {
            Console.WriteLine("Du hast Adipositas");
        }
        else
        {
            Console.WriteLine("Du hast Massive Adipositas");
        }
</code>```

答:
You should declare your var BMIformula.

var BMIformula = 0;
```

<p>or </p>

```float BMIformula = 0;
```

ContentLicense: CC BY-SA 4.0

Body:
I program a  little BMI calculator atm. I coded the basic stuff, which I can work with. I have the problem that my var BMIformula doesnt exist in the context (heading).

Here is my current code:

        BMIformula = 0;

        Console.WriteLine("Geben Sie Körpergewicht ein: ");
            int bodyWeight = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Geben Sie Ihre Körpergröße in cm ein: ");
            int bodyHeight = Convert.ToInt32(Console.ReadLine());

            // Console.WriteLine(bodyWeight.ToString(), bodyHeight.ToString());

            Console.WriteLine("Ihre Eingaben: Körpergewicht: {0}    Körpergröße: {1}", bodyWeight, bodyHeight);

           //  Console.WriteLine("Der BMI beträgt: {0}");

            Console.ReadLine();

        BMIformula = bodyWeight / bodyHeight * bodyHeight;
        BMIformula.ToString();

        if (BMIformula <= 20)
        {
            Console.WriteLine("Du bist im Untergewicht!");
        }
        else if (BMIformula >= 20 && BMIformula <= 25)
        {
            Console.WriteLine("Du bist im Normalgewicht");
        }
        else if (BMIformula >= 25 && BMIformula <= 30)
        {
            Console.WriteLine("Du bist Übergewichtig");
        }
        else if (BMIformula >= 30 && BMIformula <= 40)
        {
            Console.WriteLine("Du hast Adipositas");
        }
        else
        {
            Console.WriteLine("Du hast Massive Adipositas");
        }

Body:
You should declare your var BMIformula.

var BMIformula = 0;

or

float BMIformula = 0;


问:
Install .ipa to iPad with or without iTunes
I have the .ipa from PhoneGap build and I need to test it. I got provisioning profile from Developer account.

So my question is: can I directly put my .ipa to iPad to install for testing, or do I have to follow some rules to install?

答:
iPhone doesn't allow to install an ipa directly, so provide a direct link to the ipa file is useless. That's why some people uses external services that provide a link or a qcode to install the ipa.

Another option, that nobody told in the other answers to this question and that it's completely independent from iTunes or any external service, is to create your own script that generates an installation link and automatically sends it to your mobile (for example by email). I created a such script for my personal use, that:

creates the html file;

creates the plist file;

copies ipa, html and plist files to my server;

sends me the link.

Because I work on Linux, I created a Bash script. You can use any other scripting language, but it's important to know what to put in the html and plist files.

This is the part of my script that generates the html and plist content. I hope that it's enough self-explanatory:

```<code>sha=`sha1sum ${ipa} | awk '{ print $1 }'`
output=${sha}-${AppName}-${version}.ipa
html=${sha}-${AppName}-${version}.html
plist=${sha}-${AppName}-${version}.plist

# Generates html
echo "<!DOCTYPE html>
 <html>
 <head>
 <meta charset=\"UTF-8\">
 <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">
    <meta name=\"MobileOptimized\" content=\"width\" />
    <meta name=\"HandheldFriendly\" content=\"true\" />
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
    <meta http-equiv=\"cleartype\" content=\"on\" />
 <title>Install ${AppName} ${version}</title>
 </head>

 <body>
   <h1><a href=\"itms-services://?action=download-manifest&url=${serverUrl}${plist}\">
     Install </a></h1>
 </body>

 </html>" > ${html}

# Generate plist
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>${serverUrl}${output}</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>full-size-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>${serverUrl}Icon%402x.png</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>${serverUrl}Icon.png</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>${bundle}</string>
                <key>bundle-version</key>
                <string>${version}</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>${AppName}</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>" > ${plist}
</code>```

For a simple example you can also see: https://github.com/Saleh7/ipa-install

ContentLicense: CC BY-SA 3.0

Body:
iPhone doesn't allow to install an ipa directly, so provide a direct link to the ipa file is useless. That's why some people uses external services that provide a link or a qcode to install the ipa.

Another option, that nobody told in the other answers to this question and that it's completely independent from iTunes or any external service, is to create your own script that generates an installation link and automatically sends it to your mobile (for example by email). I created a such script for my personal use, that:

creates the html file;

creates the plist file;

copies ipa, html and plist files to my server;

sends me the link.

Because I work on Linux, I created a Bash script. You can use any other scripting language, but it's important to know what to put in the html and plist files.

This is the part of my script that generates the html and plist content. I hope that it's enough self-explanatory:

sha=`sha1sum ${ipa} | awk '{ print $1 }'`
output=${sha}-${AppName}-${version}.ipa
html=${sha}-${AppName}-${version}.html
plist=${sha}-${AppName}-${version}.plist

# Generates html
echo "<!DOCTYPE html>
 <html>
 <head>
 <meta charset=\"UTF-8\">
 <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">
    <meta name=\"MobileOptimized\" content=\"width\" />
    <meta name=\"HandheldFriendly\" content=\"true\" />
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />
    <meta http-equiv=\"cleartype\" content=\"on\" />
 <title>Install ${AppName} ${version}</title>
 </head>

 <body>
   <h1><a href=\"itms-services://?action=download-manifest&url=${serverUrl}${plist}\">
     Install </a></h1>
 </body>

 </html>" > ${html}

# Generate plist
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">
<plist version=\"1.0\">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>${serverUrl}${output}</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>full-size-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>${serverUrl}Icon%402x.png</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>${serverUrl}Icon.png</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>${bundle}</string>
                <key>bundle-version</key>
                <string>${version}</string>
                <key>kind</key>
                <string>software</string>
                <key>title</key>
                <string>${AppName}</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>" > ${plist}

For a simple example you can also see: https://github.com/Saleh7/ipa-install


问:
Must declare the scalar variable "@id". Creating stored procedure with SQL Server
I am trying to create a stored procedure for updating a table according to id given but it is showing me error

```<code>CREATE PROCEDURE updateCategoryPro
    (@categoryName VARCHAR(64),
     @IsActive BIT,
     @IsSelected BIT,
     @mediaId INT,
     @pageTitle VARCHAR(128),
     @metaKeyword VARCHAR(512),
     @metaDescription VARCHAR(256),
     @createDate DATETIME,
     @createdBy INT,
     @updatedDate DATETIME,
     @updatedBy INT)
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName = @categoryName,
        @IsActive = IsActive,
        @IsSelected = IsSelected,
        @mediaId = mediaId,
        pageTitle = @pageTitle,
        metaKeyword = @metaKeyword,
        metaDescription = @metaDescription,
        @createDate = createDate,
        @createdBy = createdBy,
        @updatedDate = updatedDate,
        @updatedBy = updatedBy
    WHERE categoryId = @id
END
</code>```

Getting error at @id

答: You need to include the @id as part of your stored procedure parameters.

Body:
I am trying to create a stored procedure for updating a table according to id given but it is showing me error

CREATE PROCEDURE updateCategoryPro
    (@categoryName VARCHAR(64),
     @IsActive BIT,
     @IsSelected BIT,
     @mediaId INT,
     @pageTitle VARCHAR(128),
     @metaKeyword VARCHAR(512),
     @metaDescription VARCHAR(256),
     @createDate DATETIME,
     @createdBy INT,
     @updatedDate DATETIME,
     @updatedBy INT)
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName = @categoryName,
        @IsActive = IsActive,
        @IsSelected = IsSelected,
        @mediaId = mediaId,
        pageTitle = @pageTitle,
        metaKeyword = @metaKeyword,
        metaDescription = @metaDescription,
        @createDate = createDate,
        @createdBy = createdBy,
        @updatedDate = updatedDate,
        @updatedBy = updatedBy
    WHERE categoryId = @id
END

Getting error at @id


问:
swfobject.embedSWF doesn't load objects in IE7 and IE8
I have this code running great in ff, opera and chrome:

```<code><script type="text/javascript">
                    $(document).ready(function(){
                      var swfUrl = "http://www.youtube.com/apiplayer?video_id=<?php echo bg_get_video_id($post->post_content)?>&enablejsapi=1&version=3&playerapiid=ytplayer_<?php echo $i?>";

                      // allowScriptAccess must be set to allow the Javascript from one
                      // domain to access the swf on the youtube domain
                      var params = { allowScriptAccess: "always", wmode: "opaque" };

                      // This sets the ID of the DOM object or embed tag to 'myytplayer'.
                      // You can use this ID to access the swf and call the player's API
                      var atts = { id: "ytplayer_<?php echo $i?>", class: "ytplayer"};
                      var flashvars = {};
                      swfobject.embedSWF(swfUrl, "ytdiv_<?php echo $i?>", "300", "120", "9", null, flashvars, params, atts);
                    });
                </script>
</code>```

But not in Internet Explorer versions 7 and 8. It's a part of php file from Wordpress, but it's not important - video_id and ytdiv_ are all ok, it works in other browsers.

Is there anything I can do to make it work in IE? I don't have any ideas about what could have caused it.

Cheers,
Nebril

答: I don't know whether it's the same problem I had, but I had to upgrade to the latest version of swfobject, 2.2 I think it is now, that solved it for me.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have this code running great in ff, opera and chrome:

But not in Internet Explorer versions 7 and 8. It's a part of php file from Wordpress, but it's not important - video_id and ytdiv_ are all ok, it works in other browsers.

Is there anything I can do to make it work in IE? I don't have any ideas about what could have caused it.

Cheers,
Nebril


问:
aws cli command for list of elastic ip address that are not in use?
I need to write a shell script to find the list of Elastic ip address that are not in use by any instances and need to associate free ip to my newly launched instance.</p>

答:
You can use this aws cli to get all the elastic Ip's that are not in use.

```<code>aws ec2 describe-addresses --query "Addresses[?NetworkInterfaceId == null ].PublicIp"
</code>```

If you need output in text format just append --output text to the CLI.

You can then similarly use the cli to launch a new EC2. Refer the cli https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html on details around launching an instance.

Body:
You can use this aws cli to get all the elastic Ip's that are not in use.

aws ec2 describe-addresses --query "Addresses[?NetworkInterfaceId == null ].PublicIp"

If you need output in text format just append --output text to the CLI.

You can then similarly use the cli to launch a new EC2. Refer the cli https://docs.aws.amazon.com/cli/latest/reference/ec2/run-instances.html on details around launching an instance.


问:
Executing a shell script inside a jar file. How to extract?
I am developing a Linux-only Java application, and I need to execute a shell script in it. According to what I have read, the only way to execute that shell script is by extracting it from the jar file and executing it. The question is? How can I extract that shell script at runtime? </p>

<p>Thank you in advance </p>

答: Do not bundle the script in your jar in the first place. Deploy the scripts as independent files.</p>

Body:
I am developing a Linux-only Java application, and I need to execute a shell script in it. According to what I have read, the only way to execute that shell script is by extracting it from the jar file and executing it. The question is? How can I extract that shell script at runtime?

Thank you in advance


问:
What does "matscale" function in Matlab actually do?
I'm trying to implement a convertor from z to s time for transfer function in Python.
Matlab give us an opportunity to do this using d2c function. But i can't get what the "matscale" function does.

I've stucked in mscale.m file with calling matscale(abs(a),0.01) function. There is no description and no such function in matlab website at all. I can't open it, because its extention is .mex32 (i guess). All that i found in internet is that it may implement the "scale the matrix using the projection radius", but i'm not sure it's correct (http://www.adras.com/Purpose-of-matscale-in-Control-Toolbox.t124458-80.html)
 Could you please explain me what this function does or share a source code? i use matlab 2018a

[~,s] = matscale(abs(a),0.01);

答: If someone needs the solution of my problem, i found that the "matscale" function executes the same thing as function "balance". Python libs contain this function</p>


问:
how hashmap object reference change
Trying to check how hashmap works

```<code>public class hashmapcheck {
public static void main(String args[]) {
    Person abhishek = new Person("abhishek");
    Map<Person,String> mapCheck = new HashMap<Person,String>();
    mapCheck.put(abhishek,"ancd");
    abhishek.setName("defg");
    System.out.println(mapCheck.get(abhishek));  //line which i try to undertand
}
</code>```

}

```<code>public class Person {
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Person(String name) {
    this.name = name;
}

String name;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Person person = (Person) o;

    return name != null ? name.equals(person.name) : person.name == null;
}

@Override
public int hashCode() {
    return name != null ? name.hashCode() : 0;
}
</code>```

}

if equals and hashcode is not overriden  for person class it print ancd,  but when i override it it will print null.
what i thought when i store objectin hashmap it will store reference of that hashmap what is going wrong

答:
abhishek.setName("defg") is mutating a key of your HashMap (a Person instance) after you added it to the HashMap.

This causes the hashCode() of that key to change, so the get() method fails to locate it according to the new hashCode() (since it was placed in a bin that matches the original hashCode().

You are misusing the HashMap class. Keys should not be mutated after being added to the HashMap (at least properties that affect the outcome of hashCode and equals should not be mutated).

As for the behavior when not overriding equals and hashCode, in this case equals asnd hashCode do not depend on the value of name, so changing the name makes no difference. In that case, the default implementation guarantees that your key can be found in the HashMap if you are searching for the exact same Person instance you put into the Map.

Title: how hashmap object reference change

Body:
Trying to check how hashmap works

public class hashmapcheck {
public static void main(String args[]) {
    Person abhishek = new Person("abhishek");
    Map<Person,String> mapCheck = new HashMap<Person,String>();
    mapCheck.put(abhishek,"ancd");
    abhishek.setName("defg");
    System.out.println(mapCheck.get(abhishek));  //line which i try to undertand
}

}

public class Person {
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public Person(String name) {
    this.name = name;
}

String name;

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Person person = (Person) o;

    return name != null ? name.equals(person.name) : person.name == null;
}

@Override
public int hashCode() {
    return name != null ? name.hashCode() : 0;
}

}

if equals and hashcode is not overriden  for person class it print ancd,  but when i override it it will print null.
what i thought when i store objectin hashmap it will store reference of that hashmap what is going wrong


答: What about url*decode*?

Title: How to handle JS serialized item in PHP?

Body:
Hey guys!
I am having a bit of trouble handling the data from a submitted form that is serialized with JS.
In the form there a textarea fields which users can input any text they want but when they enter & like "apples & oranges", I have trouble handling that.  As we know that JS serializes & to %26 and spaces with a "+" sign.

So now back in PHP, I am trying to put this data into the database and call it back out elsewhere but for the life of me don't know how to handle the special characters properly.

Note that I am also php exploding the data at the "&" sign to make it into an array, then is put into the database as an array.  I tried several methods like urldecode, htmlentities but those don't help because remember I need to explode at "&".

I am serializing in JS because its an AJAX submitting form.

Body: What about url*decode*?


问:
Error: colon expected css(css-colonexpected)
I'm trying to create a. Simple angular project.
In the css file /src/styles.css ,while writing the code, I'm facing being shown syntax errors.

```<code>body {
     margin: 0;
     background: #F2F2F2;
     font-family: 'Montserrat', sans-serif;
     height: 100vh;
}

#container {    display: grid;
    grid-template-columns: 70px auto;
    height: 100%;

    #content {
        padding: 30px 50px;

        ul {//error highlight saying: colon expected css(css-colonexpected)

            list-style-type: none;
            margin:0;padding:0;

            li {
                background: #fff;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 8px;

                a {
                    font-size: 1.5em;
                    text-decoration: none;
                    font-weight: bold;
                    color:#00A8FF;
                }

                ul {
                    margin-top: 20px;

                    li {
                        padding:0;

                        a {
                            font-size: 1em;
                            font-weight: 300;
                        }//Error highlight saying: at-rule or selector expected css(css-ruleselectorexpected)
                    }
                }
            }
        }
    }
}
</code>```

Error msg shown as comments

Syntax errors being shown are:
-colon expected css(css-colonexpected)

-at-rule or selector expected css(css-ruleselectorexpected)

答:
You are using a valid SASS or SCSS with nested classes in  a .css file and hence the error is shown. The equivalent css would be:

```<code>body {
  margin: 0;
  background: #F2F2F2;
  font-family: "Montserrat", sans-serif;
  height: 100vh;
}

#container {
  display: grid;
  grid-template-columns: 70px auto;
  height: 100%;
}
#container #content {
  padding: 30px 50px;
}
#container #content ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#container #content ul li {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 8px;
}
#container #content ul li a {
  font-size: 1.5em;
  text-decoration: none;
  font-weight: bold;
  color: #00A8FF;
}
#container #content ul li ul {
  margin-top: 20px;
}
#container #content ul li ul li {
  padding: 0;
}
#container #content ul li ul li a {
  font-size: 1em;
  font-weight: 300;
}
</code>```

Body:
I'm trying to create a. Simple angular project.
In the css file /src/styles.css ,while writing the code, I'm facing being shown syntax errors.

body {
     margin: 0;
     background: #F2F2F2;
     font-family: 'Montserrat', sans-serif;
     height: 100vh;
}

#container {    display: grid;
    grid-template-columns: 70px auto;
    height: 100%;

    #content {
        padding: 30px 50px;

        ul {//error highlight saying: colon expected css(css-colonexpected)

            list-style-type: none;
            margin:0;padding:0;

            li {
                background: #fff;
                border-radius: 8px;
                padding: 20px;
                margin-bottom: 8px;

                a {
                    font-size: 1.5em;
                    text-decoration: none;
                    font-weight: bold;
                    color:#00A8FF;
                }

                ul {
                    margin-top: 20px;

                    li {
                        padding:0;

                        a {
                            font-size: 1em;
                            font-weight: 300;
                        }//Error highlight saying: at-rule or selector expected css(css-ruleselectorexpected)
                    }
                }
            }
        }
    }
}

Error msg shown as comments

Syntax errors being shown are:
-colon expected css(css-colonexpected)

-at-rule or selector expected css(css-ruleselectorexpected)

Body:
You are using a valid SASS or SCSS with nested classes in  a .css file and hence the error is shown. The equivalent css would be:

body {
  margin: 0;
  background: #F2F2F2;
  font-family: "Montserrat", sans-serif;
  height: 100vh;
}

#container {
  display: grid;
  grid-template-columns: 70px auto;
  height: 100%;
}
#container #content {
  padding: 30px 50px;
}
#container #content ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#container #content ul li {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 8px;
}
#container #content ul li a {
  font-size: 1.5em;
  text-decoration: none;
  font-weight: bold;
  color: #00A8FF;
}
#container #content ul li ul {
  margin-top: 20px;
}
#container #content ul li ul li {
  padding: 0;
}
#container #content ul li ul li a {
  font-size: 1em;
  font-weight: 300;
}


问:
Copy files from folders and sub-folders to another folder and saving the structure of the folders
I have created a list of files by some conditions and I want to copy only the files from that list to a new folder and subfolders like in the origin folder.
The structure of the folders is year/month/day.

This is the code I tried:

```<code>from.dir <- "J:/Radar_data/Beit_Dagan/RAW/2018"
## I want only the files from the night
to.dir   <- "J:/Radar_data/Beit_Dagan/night"
files    <- list.files(path = from.dir, full.names = TRUE, recursive =
TRUE)
## night_files is a vector I created with the files I need - only during the night
for (f in night_files) file.copy(from = f, to = to.dir)
</code>```

But I get all the files in one folder

part of my list look like this:

```<code>[1] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142554.h5"
[2] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142749.h5"
[3] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310143054.h5"
</code>```

Is there a way to keep the structure of the folder and the subfolders when copying?

I want to get the same structure of year/month/day in the new "night" folder

答:
You just need:</p>

```<code>file.copy(from = from.dir, to = to.dir,recursive=T)
</code>```

Body:
I have created a list of files by some conditions and I want to copy only the files from that list to a new folder and subfolders like in the origin folder.
The structure of the folders is year/month/day.

This is the code I tried:

from.dir <- "J:/Radar_data/Beit_Dagan/RAW/2018"
## I want only the files from the night
to.dir   <- "J:/Radar_data/Beit_Dagan/night"
files    <- list.files(path = from.dir, full.names = TRUE, recursive =
TRUE)
## night_files is a vector I created with the files I need - only during the night
for (f in night_files) file.copy(from = f, to = to.dir)

But I get all the files in one folder

part of my list look like this:

[1] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142554.h5"
[2] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310142749.h5"
[3] "J:/Radar_data/Beit_Dagan/H5/2018/03/10/TLV180310143054.h5"

Is there a way to keep the structure of the folder and the subfolders when copying?

I want to get the same structure of year/month/day in the new "night" folder

Body:
You just need:

file.copy(from = from.dir, to = to.dir,recursive=T)


问:
Overriding protected methods in Java
Test.java

```<code>package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}
</code>```

A.java:

```<code>package a;
public class A {
    protected void test() { }
}
</code>```

B.java:

```<code>package b;
public class B extends a.A {
    protected void test() { }
}
</code>```

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.

答:
This is just not how inheritance works in Java.

If a method is overridden, and the overridden method is not visible, it's a compile-time error to try and call it.

You seem to expect that Java would automatically fall back to the method in the super class, but that does not happen.

I'll try and dig out the JLS later on why this is not done...

Title: Overriding protected methods in Java

Body:
Test.java

package a;
import b.B;
public class Test {
    public static void main(String[] v) {
        new A().test();
        new B().test();
    }
}

A.java:

package a;
public class A {
    protected void test() { }
}

B.java:

package b;
public class B extends a.A {
    protected void test() { }
}

Why does new B().test() give an error? Doesn't that break visibility rules?

B.test() is invisible in Test because they're in different packages, and yet it refuses to call the test() in B's superclass which is visible.

Links to the appropriate part of the JLS would be appreciated.


问:
Send Raw Transaction Ethereum infura nodejs npm
I'm currently trying to implement an ethereum Node Connection to my Typescript/ Node Project.

I'm connection to the "Infura" node server where i need to sign my transaction locally.
Well, anyway. I'm signing my transaction using the npm package "ethereumjs-tx" and everything looks great.
When i'm using "sendRawTransaction" from web3 my response is an tx-id which means my transaction should be allready in the Blockchain. Well... it isn't

My sign Transaction Function is below.

private signTransactionLocally(amountInWei: number, to: string, privateKey: string = <PRIVATE_KEY>, wallet: string = <MY_WALLET>) {
        const pKeyBuffer = Buffer.from(privateKey, "hex");

        const txParams = {
            nonce: this.getNonce(true,wallet),
            //gas: this.getGasPrice(true),
            gasLimit: this.getGasLimit2(true),
            to: to,
            value: amountInWei,
            data: '0x000000000000000000000000000000000000000000000000000000000000000000000000',
            chainId: "0x1"
        };

        // console.log(JSON.stringify(txParams));
        const tx = new this.ethereumTx(txParams);
        tx.sign(pKeyBuffer);
        return tx.serialize().toString("hex");

    }```
</div>
</div>
</p>

<p>Used Functions in "signTransactionLocally" : </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>    private getGasLimit2(hex: boolean = false) {
        const latestGasLimit = this.web3.eth.getBlock("latest").gasLimit;
        return hex ? this.toHex(latestGasLimit) : latestGasLimit;
    }

        private getNonce(hex:boolean = false, wallet: string = "0x60a22659E0939a061a7C9288265357f5d26Cf98a") {
        return hex ? this.toHex(this.eth().getTransactionCount(wallet)) : this.eth().getTransactionCount(wallet);
    }</code>```

Running my code looks like following:

this.dumpInformations();
const signedTransaction = this.signTransactionLocally(this.toHex((this.getMaxAmountToSend(false, "0x60a22659E0939a061a7C9288265357f5d26Cf98a") / 3 )), "0x38bc48f1d19fdf7c8094a4e40334250ce1c1dc66" );
        console.log(signedTransaction);

this.web3.eth.sendRawTransaction("0x" + signedTransaction, function(err: any, res: any) {
            if (err)
                console.log(err);
            else
                console.log("transaction Done=>" + res);
        });```

since sendRawTransaction results in console log:
[Node] transaction Done=>0xc1520ebfe0a225e6971e81953221c60ac1bfcd528e2cc17080b3f9b357003e34

everything should be allright.

Has anybody had the same problem?
i Hope that someone could help me. Have a nice day!

答:
After dealing with these issues countless times; i'm pretty sure you are sending a nonce too high.

In these cases, the node will still return you a transaction hash, but your transaction will remain in the nodes queue and not enter the memory pool or be propagated to other nodes, UNTIL, you fill in the nonce gaps.

You could try the following :

Use getTransactionCount(address, 'pending') - to include the txs that are int nodes queue & memory pool . But this method unreliable and won't deal with concurrent requests as the node needs time to assess the correct amount at any given time.

Keep your own counter, without relying on the node (unless you detect some serious errors).

For more serious projects, persist your counter / per address at the level of the database with locks to handle concurrency, making sure you give out correct nonces to each request.

Cheers

Body:
I'm currently trying to implement an ethereum Node Connection to my Typescript/ Node Project.

I'm connection to the "Infura" node server where i need to sign my transaction locally.
Well, anyway. I'm signing my transaction using the npm package "ethereumjs-tx" and everything looks great.
When i'm using "sendRawTransaction" from web3 my response is an tx-id which means my transaction should be allready in the Blockchain. Well... it isn't

My sign Transaction Function is below.

private signTransactionLocally(amountInWei: number, to: string, privateKey: string = <PRIVATE_KEY>, wallet: string = <MY_WALLET>) {
        const pKeyBuffer = Buffer.from(privateKey, "hex");

        const txParams = {
            nonce: this.getNonce(true,wallet),
            //gas: this.getGasPrice(true),
            gasLimit: this.getGasLimit2(true),
            to: to,
            value: amountInWei,
            data: '0x000000000000000000000000000000000000000000000000000000000000000000000000',
            chainId: "0x1"
        };

        // console.log(JSON.stringify(txParams));
        const tx = new this.ethereumTx(txParams);
        tx.sign(pKeyBuffer);
        return tx.serialize().toString("hex");

    }

Used Functions in "signTransactionLocally" :

    private getGasLimit2(hex: boolean = false) {
        const latestGasLimit = this.web3.eth.getBlock("latest").gasLimit;
        return hex ? this.toHex(latestGasLimit) : latestGasLimit;
    }

        private getNonce(hex:boolean = false, wallet: string = "0x60a22659E0939a061a7C9288265357f5d26Cf98a") {
        return hex ? this.toHex(this.eth().getTransactionCount(wallet)) : this.eth().getTransactionCount(wallet);
    }

Running my code looks like following:

this.dumpInformations();
const signedTransaction = this.signTransactionLocally(this.toHex((this.getMaxAmountToSend(false, "0x60a22659E0939a061a7C9288265357f5d26Cf98a") / 3 )), "0x38bc48f1d19fdf7c8094a4e40334250ce1c1dc66" );
        console.log(signedTransaction);

this.web3.eth.sendRawTransaction("0x" + signedTransaction, function(err: any, res: any) {
            if (err)
                console.log(err);
            else
                console.log("transaction Done=>" + res);
        });

since sendRawTransaction results in console log:
[Node] transaction Done=>0xc1520ebfe0a225e6971e81953221c60ac1bfcd528e2cc17080b3f9b357003e34

everything should be allright.

Has anybody had the same problem?
i Hope that someone could help me. Have a nice day!


答:
You are using sass in CSS file.. So this error is being shown. Its file extension should be .sass or stylesheet should be coded according to CSS syntax.

In CSS, it would be like:

```<code>    body {
  margin: 0;
  background: #F2F2F2;
  font-family: "Montserrat", sans-serif;
  height: 100vh;
}

#container {
  display: grid;
  grid-template-columns: 70px auto;
  height: 100%;
}
#container #content {
  padding: 30px 50px;
}
#container #content ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#container #content ul li {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 8px;
}
#container #content ul li a {
  font-size: 1.5em;
  text-decoration: none;
  font-weight: bold;
  color: #00A8FF;
}
#container #content ul li ul {
  margin-top: 20px;
}
#container #content ul li ul li {
  padding: 0;
}
#container #content ul li ul li a {
  font-size: 1em;
  font-weight: 300;
}
</code>```

Title: Error: colon expected css(css-colonexpected)

Body:
You are using sass in CSS file.. So this error is being shown. Its file extension should be .sass or stylesheet should be coded according to CSS syntax.

In CSS, it would be like:

    body {
  margin: 0;
  background: #F2F2F2;
  font-family: "Montserrat", sans-serif;
  height: 100vh;
}

#container {
  display: grid;
  grid-template-columns: 70px auto;
  height: 100%;
}
#container #content {
  padding: 30px 50px;
}
#container #content ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
}
#container #content ul li {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 8px;
}
#container #content ul li a {
  font-size: 1.5em;
  text-decoration: none;
  font-weight: bold;
  color: #00A8FF;
}
#container #content ul li ul {
  margin-top: 20px;
}
#container #content ul li ul li {
  padding: 0;
}
#container #content ul li ul li a {
  font-size: 1em;
  font-weight: 300;
}


问:
Finding not equal adjacent indexes in vector
I have this vector of ints:

```<code>std::vector<int> v = {1, 1, 2, 2, 2, 3};
</code>```

and I want to find indexes, where the adjacent elements aren't equal:

```<code>1
4
5
</code>```

My solution is (which isn't working):

```<code>std::vector<int> v = {1, 1, 2, 2, 2, 3};

auto i1 = std::begin(v);

while(1)
{
    i1 = std::adjacent_find(i1, std::end(v), std::not_equal_to<int>());
    std::cout << std::distance(std::begin(v), i1) << '\n';

    if (i1++ == std::end(v))
        break;
}
</code>```

This prints:

```<code>1
4
6
</code>```

The last elements points to index 6, but I want it to point 5 (value 3). Any help appreciated!

答:
Your code and expected answer are invalid. Proper answer for this data is:

```<code>1
4
</code>```

Last iteration of your loop treats result where nothing was found as a valid result.
That is why you see size of the array as a last result.

So fixed code looks like this:

```<code>std::vector<int> v = {1, 1, 2, 2, 2, 3};

auto i1 = std::begin(v);

while(1)
{
    i1 = std::adjacent_find(i1, std::end(v), std::not_equal_to<int>());
    if (i1 == std::end(v))
        break;

    std::cout << std::distance(std::begin(v), i1) << '\n';
    ++i1;
}
</code>```

Body:
I have this vector of ints:

std::vector<int> v = {1, 1, 2, 2, 2, 3};

and I want to find indexes, where the adjacent elements aren't equal:

1
4
5

My solution is (which isn't working):

std::vector<int> v = {1, 1, 2, 2, 2, 3};

auto i1 = std::begin(v);

while(1)
{
    i1 = std::adjacent_find(i1, std::end(v), std::not_equal_to<int>());
    std::cout << std::distance(std::begin(v), i1) << '\n';

    if (i1++ == std::end(v))
        break;
}

This prints:

1
4
6

The last elements points to index 6, but I want it to point 5 (value 3). Any help appreciated!

Body:
Your code and expected answer are invalid. Proper answer for this data is:

1
4

Last iteration of your loop treats result where nothing was found as a valid result.
That is why you see size of the array as a last result.

So fixed code looks like this:

std::vector<int> v = {1, 1, 2, 2, 2, 3};

auto i1 = std::begin(v);

while(1)
{
    i1 = std::adjacent_find(i1, std::end(v), std::not_equal_to<int>());
    if (i1 == std::end(v))
        break;

    std::cout << std::distance(std::begin(v), i1) << '\n';
    ++i1;
}


问:
Android XML: android:elevation vs. app:elevation
When do I use android:elevation and when app:elevation?

What's the difference between those two?

答:
There is one more thing:

```<code><com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/spacing"
    android:src="@drawable/svg_my_location"
    app:elevation="4dp" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/shape_rect_round_white"
    app:elevation="8dp"
    app:behavior_hideable="true"
    app:behavior_peekHeight="100dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"/>
</code>```

With using app FloatingActionButton is visible

```<code><com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/spacing"
    android:src="@drawable/svg_my_location"
    android:elevation="4dp" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/shape_rect_round_white"
    android:elevation="8dp"
    app:behavior_hideable="true"
    app:behavior_peekHeight="100dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"/>
</code>```

When you're using android FloatingActionButton is invisible, because it overlapped  by bottom sheet

Body:
There is one more thing:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/spacing"
    android:src="@drawable/svg_my_location"
    app:elevation="4dp" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/shape_rect_round_white"
    app:elevation="8dp"
    app:behavior_hideable="true"
    app:behavior_peekHeight="100dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"/>

With using app FloatingActionButton is visible

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/spacing"
    android:src="@drawable/svg_my_location"
    android:elevation="4dp" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/shape_rect_round_white"
    android:elevation="8dp"
    app:behavior_hideable="true"
    app:behavior_peekHeight="100dp"
    app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"/>

When you're using android FloatingActionButton is invisible, because it overlapped  by bottom sheet


问:
Does hiding flash elements & iFrames with aria-hidden="true" help make my website accessible?
I work for a website design company and we have a lot of flash projects and clients constantly embed iframes to Facebook, etc.

For example, when I do my test using a screen reader it seems like it's a bad user-experience when you get into an Iframe because most Facebook feed embedded load forever and you might even get stuck into an ajax loading iFrame.

I want to know if it's considered bad practice to hide flash/ iframes elements from screen readers using aria-hidden? Also, does it makes my website accessible by hiding them?

Thanks!

答:
If content or functionality is usable by one group of people, it should be available to everyone. If you're serving up inaccessible content inside an iframe, hiding it so blind users don't know it's there isn't your "get out of jail free" card, it's a breach of the Web Content Accessibility Guidelines, and depending on what country you live in it could be a breach of your accessibility law.

As someone said above, if the iframe content is purely decorative, then hiding it would be OK, but if it contains important information or interactive elements, then pretending to one group of users that it doesn't exist is not an option.


问:
Designing mongodb data model: embedding vs. referencing
I'm writing an application that gathers statistics of users across multiple social networks accounts. I have a collection of users and I would like to store the statistics information of each user.

Now, I have two options:

Create a collection that stores users statistics documents, and add a reference object to each of the user documents that links it to the corresponding document in the statistics collection.

Embed a statistics document in each of the users document.

Besides for query performance (which I'm less concerned about):

what are the pros and cons of each of these approaches?

What should I take into account if I choose to use references rather than embedding the information inside the user document?

答:
The shape of the data is determined by the application itself.

There’s a good chance that when you are working with the users data, you probably need statistics details.

The decision about what to put in the document is pretty much determined by how the data is used by the application.

The data that is used together as users documents is a good candidate to be pre-joined or embedded.

One of the limitations of this approach is the size of the document. It should be a maximum of 16 MB.

Another approach is to split data between multiple collections.

One of the limitations of this approach is that there is no constraint in MongoDB, so there are no foreign key constraints as well.

The database does not guarantee consistency of the data. Is it up to you as a programmer to take care that your data has no orphans.

Data from multiple collections could be joined by applying the lookup operator. But, a collection is a separate file on disk, so seeking on multiple collections means seeking from multiple files, and that is, as you are probably guessing, slow.

Generally speaking, embedded data is the preferable approach.


问:
Rails 5: Insert/Update only if there's no filled specific field for that id
I have a Followups table with the fields: patient_id, death_date (and other fields..).

There could be multiple records for the same patient_id but there must be only one death_date for that patient_id.
A unique index won't work as the user could insert two different death_date.

Which is the best way to achieve this in Rails 5?

If possible, please make an example.

Thanks

答:
You could do this with a callback on the Followup model:
Assuming a Patient has_many :followups

```<code>class Followup
  belongs_to :patient
  validate :check_for_existing_death_date

  private

  def check_for_existing_death_date
    # This will grab the first one if any with a death date exist
    # This also assumes that the patient_id and patient exist
    followup = patient.followups.where("death_date IS NOT NULL").take

    # if you want to raise an error...
    if followup
      errors.add(:death_date, 'There is already a death date for this patient')
      return false
    end

    # If not, do something with the data
    # if followup
    #   self.death_date = nil # or followup.death_date if you want it saved on followups as well
    # end
  end
end
</code>```

I would think that the best way to do this would be to store the death_date on the Patient record, since death only happens once per patient.

Body:
You could do this with a callback on the Followup model:
Assuming a Patient has_many :followups

class Followup
  belongs_to :patient
  validate :check_for_existing_death_date

  private

  def check_for_existing_death_date
    # This will grab the first one if any with a death date exist
    # This also assumes that the patient_id and patient exist
    followup = patient.followups.where("death_date IS NOT NULL").take

    # if you want to raise an error...
    if followup
      errors.add(:death_date, 'There is already a death date for this patient')
      return false
    end

    # If not, do something with the data
    # if followup
    #   self.death_date = nil # or followup.death_date if you want it saved on followups as well
    # end
  end
end

I would think that the best way to do this would be to store the death_date on the Patient record, since death only happens once per patient.


问:
Passing variable in file path
I want to pass the timestamp variable in the filename variable. Please suggest how.
I am doing this in VUGEN.

Code:

```<code>int timestamp;
char * filename;

web_save_timestamp_param("c_launchid", LAST);

timestamp = lr_output_message( "%s",lr_eval_string("{c_launchid}") );

filename = "C:\\temp\\icafile_{timestamp}.ica";
</code>```

答:
I am not familiar with Vugen, but normally in Java you could do it like so:

```<code>filename = String.format("C:\\temp\\icafile_{%d}.ica", timestamp);
</code>```

Or perhaps a more simple approach:

```<code>filename = "C:\\temp\\icafile_{" + timestamp + "}.ica";
</code>```

Title: Passing variable in file path

Body:
I want to pass the timestamp variable in the filename variable. Please suggest how.
I am doing this in VUGEN.

Code:

int timestamp;
char * filename;

web_save_timestamp_param("c_launchid", LAST);

timestamp = lr_output_message( "%s",lr_eval_string("{c_launchid}") );

filename = "C:\\temp\\icafile_{timestamp}.ica";

Body:
I am not familiar with Vugen, but normally in Java you could do it like so:

filename = String.format("C:\\temp\\icafile_{%d}.ica", timestamp);

Or perhaps a more simple approach:

filename = "C:\\temp\\icafile_{" + timestamp + "}.ica";


问:
Blender + SceneKit (how-to)
A few questions to game developers. I am very beginner in this. I want to create a game level for example a green plane with trees. I have played a little in Blender and SceneKit. I know that I can export .dae from Blender and import it to Xcode. My questions:

Should I delete camera and light node before export? Why?

Should I design all level in one .dea file or make it separately? For example one .dea for plane and four different trees in for .dea's How to merge them in Xcode?

Can I use many times one .dea to generate for example a forest? How?

If creating design in separately is better way how to keep proportions between them to protect yourself from creation man bigger than tree?

I will be very great full if somebody someone dedicates to these questions. It will cut my time to learn basic. Thanks in advance. :)

答:
I'll tell you how I do it:

1) .dea files use only for models(trees, charecters, building, etc...)

2) Game scene: floor, models, light, camera, obstacles build using Xcode scene builder or by code or mixed (based on the scene).

3) Based on size of world/level it can be split into several scenes(visible/invisible by player). Then you can create one blank scene and load/unload these scenes during runtime.

4) For a model you create a reference and after that build forest using reference of tree. If in the future you need to change the color of tree, all trees in all scenes will be updated.

5) For each model(SCNNode) (loaded from .dea file) you can set scale attribute (from code or by Xcode scene builder)

Also, 3D Apple Games by Tutorials is very good for starting.

Title: Blender + SceneKit (how-to)


问:
Transform Rotate Menu Item Circular Menu
I have modified a circular menu that I found on this pen
But I am having trouble rotating the menu items around the main circle. By default of this pen, the button's bottom part is perpendicular to it's relative position, but since I changed them with font icons, they look upside down or crooked.

I'm a CSS noob, so I need some help please, been at this for hours!

I've tried a couple of things like:

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}
```
<p>or something like</p>
<pre class="lang-css prettyprint-override"><code>menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
}
</code>```

None of them seems to be working. Currently my component looks like this:

Here is my full CSS and HTML...

menu {
  box-sizing: border-box;
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--<menu>
    <li><i className="fas fa-bell"></i></li>
    <li><i className="fas fa-cog"></i></li>
    <li><i className="fas fa-terminal"></i></li>
</menu>-->

<menu>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</menu></code>```

答:
This will fix your rotation problem.

```<code>li a {
  transform :rotate(180deg);
}
</code>```

Also if you need a proper circular design for + icon, you need to fix width and height for .menu class in CSS as follow:

```<code>  width: 30px;
  height: 70px;
</code>```

Body:
I have modified a circular menu that I found on this pen
But I am having trouble rotating the menu items around the main circle. By default of this pen, the button's bottom part is perpendicular to it's relative position, but since I changed them with font icons, they look upside down or crooked.

I'm a CSS noob, so I need some help please, been at this for hours!

I've tried a couple of things like:

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

or something like

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
}

None of them seems to be working. Currently my component looks like this:

Here is my full CSS and HTML...

menu {
  box-sizing: border-box;
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}

<menu>

1

2

3

</menu>

Body:
This will fix your rotation problem.

li a {
  transform :rotate(180deg);
}

Also if you need a proper circular design for + icon, you need to fix width and height for .menu class in CSS as follow:

  width: 30px;
  height: 70px;


问:
Secure file transfers
We are using a custom FTP application (which encrypts the files) for secure transfers.  We send the application to end users and they use it to send us confidential data.  We also use it to send information back to the end users.

The application is in need of an update - some things are no longer working consistently.  As the end users get more restrictive security environments, as OS updates are released, etc.

We have several options:

Update the application, use SFTP, etc.

Write a new custom web application to add to our aspx website.

Purchase or download SFTP software

Purchase or download web software

Setup an external sharepoint site

Use a service which is hosted elsewhere - preferably in Canada so that our laws apply

Some of features which would be nice:

We would not want decrypted files sitting on a server outside the firewall.

Resumable transfers.

Ability to move the files automatically to a specific place inside our firewall.  Though this could be easily done outside the file transfer.

Notifications for both sender and recipient by email.

Suggestions/comments?

答:
I am not sure if this product would have everything that you are looking for, but GoAnywhere Services is a secure file server that allows trading partners (both internal and external) to securely connect to your system and exchange files within a fully managed and audited solution.

GoAnywhere Services can be installed onto Windows, Linux, IBM i, IBM System p (AIX), IBM System z (Mainframe), UNIX, HP-UX, Mac OS and Solaris platforms.  IBM i is also referred to as System i, iSeries, as400, as/400 and i5.

http://www.goanywheremft.com/products/services

OwnerDisplayName: ScottStonehouse

Title: Secure file transfers

LastEditorDisplayName: ScottStonehouse


问:
Must declare the scalar variable "@id". Creating stored procedure with SQL Server
I am trying to create a stored procedure for updating a table according to id given but it is showing me error

```<code>CREATE PROCEDURE updateCategoryPro
    (@categoryName VARCHAR(64),
     @IsActive BIT,
     @IsSelected BIT,
     @mediaId INT,
     @pageTitle VARCHAR(128),
     @metaKeyword VARCHAR(512),
     @metaDescription VARCHAR(256),
     @createDate DATETIME,
     @createdBy INT,
     @updatedDate DATETIME,
     @updatedBy INT)
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName = @categoryName,
        @IsActive = IsActive,
        @IsSelected = IsSelected,
        @mediaId = mediaId,
        pageTitle = @pageTitle,
        metaKeyword = @metaKeyword,
        metaDescription = @metaDescription,
        @createDate = createDate,
        @createdBy = createdBy,
        @updatedDate = updatedDate,
        @updatedBy = updatedBy
    WHERE categoryId = @id
END
</code>```

Getting error at @id

答:
You have to declare and pass variable to stored procedure, Make sure you passing categoryid value as @id parameter to stored procedure. Below is updated stored procedure, added @id parameter.</p>

```<code>create Procedure updateCategoryPro
(
@categoryName varchar(64),
@IsActive bit,
@IsSelected bit,
@mediaId int,
@pageTitle varchar(128),
@metaKeyword varchar(512),
@metaDescription varchar(256),
@createDate datetime,
@createdBy int,
@updatedDate datetime,
@updatedBy int,
@id INT
)
As
Begin
UPDATE CategoryMaster SET categoryName=@categoryName,@IsActive =
IsActive,@IsSelected = IsSelected,@mediaId = mediaId,
pageTitle=@pageTitle,metaKeyword=@metaKeyword,
metaDescription=@metaDescriptin
,@createDate = createDate,@createdBy = createdBy,@updatedDate =
updatedDate,@updatedBy = updatedBy
WHERE categoryId = @id
End
</code>```

Body:
I am trying to create a stored procedure for updating a table according to id given but it is showing me error

CREATE PROCEDURE updateCategoryPro
    (@categoryName VARCHAR(64),
     @IsActive BIT,
     @IsSelected BIT,
     @mediaId INT,
     @pageTitle VARCHAR(128),
     @metaKeyword VARCHAR(512),
     @metaDescription VARCHAR(256),
     @createDate DATETIME,
     @createdBy INT,
     @updatedDate DATETIME,
     @updatedBy INT)
AS
BEGIN
    UPDATE CategoryMaster
    SET categoryName = @categoryName,
        @IsActive = IsActive,
        @IsSelected = IsSelected,
        @mediaId = mediaId,
        pageTitle = @pageTitle,
        metaKeyword = @metaKeyword,
        metaDescription = @metaDescription,
        @createDate = createDate,
        @createdBy = createdBy,
        @updatedDate = updatedDate,
        @updatedBy = updatedBy
    WHERE categoryId = @id
END

Getting error at @id

Body:
You have to declare and pass variable to stored procedure, Make sure you passing categoryid value as @id parameter to stored procedure. Below is updated stored procedure, added @id parameter.

create Procedure updateCategoryPro
(
@categoryName varchar(64),
@IsActive bit,
@IsSelected bit,
@mediaId int,
@pageTitle varchar(128),
@metaKeyword varchar(512),
@metaDescription varchar(256),
@createDate datetime,
@createdBy int,
@updatedDate datetime,
@updatedBy int,
@id INT
)
As
Begin
UPDATE CategoryMaster SET categoryName=@categoryName,@IsActive =
IsActive,@IsSelected = IsSelected,@mediaId = mediaId,
pageTitle=@pageTitle,metaKeyword=@metaKeyword,
metaDescription=@metaDescriptin
,@createDate = createDate,@createdBy = createdBy,@updatedDate =
updatedDate,@updatedBy = updatedBy
WHERE categoryId = @id
End


问:
react-toolbox dependences: Uncaught TypeError: Cannot read property 'string' of undefined
i trying to use react-toolbox with webpack 4 and react 16 but i have a problem loading react-toolbox dependences, they can not require prop-types, though it exist in node_modules: i getting the error:

https://monosnap.com/file/iUQAtohH4Zuv9uKeNSXqkJWG8IOZ5U

here is my webpack rules:

```<code>{
   test: /\.(js|jsx)$/,
   exclude: /node_modules/,
   loader: 'babel-loader'
},{
   // react-toolbox
   test: /\.css$/,
   include: Path.join(Config.node_modules, 'react-toolbox'),
   use: [
      {
         loader: 'css-loader',
         options: {
            modules: true,
            sourceMap: true,
            importLoaders: 1,
            localIdentName: '[name]--[local]--[hash:base64:8]'
         }
      },
      'postcss-loader'
   ]
},
</code>```

my postcss.config.js:

```<code>module.exports = {
    plugins: {
        'postcss-cssnext': {
            features: {
                customProperties: {
                    variables: {
                        'animation-duration': '0.3s',
                        'color-primary': '#00a6ba',
                        'color-accent': 'var(--palette-pink-a200)',
                        'color-accent-dark': 'var(--palette-pink-700)',
                        'color-primary-contrast': 'var(--color-dark-contrast)',
                        'color-accent-contrast': 'var(--color-dark-contrast)',
                    }
                }
            }
        }
    }
};

</code>```

my package.json:

```<code>    "prop-types": "15.6.2",
    "react": "16.8.6",
    "react-dom": "16.8.6",
    "react-intl": "2.9.0",
    "react-redux": "7.0.3",
    "react-router": "5.0.0",
    "react-router-dom": "5.0.0",
    "react-router-redux": "4.0.8",
    "react-toolbox": "^2.0.0-beta.13",
</code>```

答:
I figure out what was the problem, it was webpack provider plugin, after I removed the prop-types from provider plugin every thing worked cool, but this affected other dependencies, so I need to remove classnames and react-intl as well.

it's stranger, because I load react with provider plugin and its work fine, but prop-types and another libraries that use prop-types get a error whem importing that.

Body:
i trying to use react-toolbox with webpack 4 and react 16 but i have a problem loading react-toolbox dependences, they can not require prop-types, though it exist in node_modules: i getting the error:

https://monosnap.com/file/iUQAtohH4Zuv9uKeNSXqkJWG8IOZ5U

here is my webpack rules:

{
   test: /\.(js|jsx)$/,
   exclude: /node_modules/,
   loader: 'babel-loader'
},{
   // react-toolbox
   test: /\.css$/,
   include: Path.join(Config.node_modules, 'react-toolbox'),
   use: [
      {
         loader: 'css-loader',
         options: {
            modules: true,
            sourceMap: true,
            importLoaders: 1,
            localIdentName: '[name]--[local]--[hash:base64:8]'
         }
      },
      'postcss-loader'
   ]
},

my postcss.config.js:

module.exports = {
    plugins: {
        'postcss-cssnext': {
            features: {
                customProperties: {
                    variables: {
                        'animation-duration': '0.3s',
                        'color-primary': '#00a6ba',
                        'color-accent': 'var(--palette-pink-a200)',
                        'color-accent-dark': 'var(--palette-pink-700)',
                        'color-primary-contrast': 'var(--color-dark-contrast)',
                        'color-accent-contrast': 'var(--color-dark-contrast)',
                    }
                }
            }
        }
    }
};

my package.json:

    "prop-types": "15.6.2",
    "react": "16.8.6",
    "react-dom": "16.8.6",
    "react-intl": "2.9.0",
    "react-redux": "7.0.3",
    "react-router": "5.0.0",
    "react-router-dom": "5.0.0",
    "react-router-redux": "4.0.8",
    "react-toolbox": "^2.0.0-beta.13",


问:
How to load from database with condition
I am new to programming and I have my hands on a web app from a company and tried to mess around and do some changes. The app was built with PHP, MySQL, and CodeIgniter, as I was told, and it's used from the company to manage orders.

When a user wants to see the orders he clicks on the specified button and the app loads all the orders from the database, but because there are more than 10.000 orders it's slow at load. So, I want to add an option where the first load happens to get only the orders of the last 6 months and if the user wants to view older orders then I should add a button or something similar and load the rest.

<?php
 $count=1;
 $this->db->order_by("order_number", "desc");
 $completed_orders=$this->db->get_where('orders' , array(
                                        'order_status' => 'completed',
                                        'category' => 'mesoportes'
                                        ))->result_array();
 foreach ($completed_orders as $row):
?>
```

Any idea how i may do that.

答:
You can initially load a certain amount of orders for eg. 10, and generate an AJAX call on the click of a button to load another 10 orders and so on.

The method to load orders from the database can be -

```<code>function get_orders($start, $limit){
 return $this->db->select('*')->where(array('order_status' => 'completed','category' => 'mesoportes'))->limit($limit, $start)->order_by("order_number", "desc")->get('orders')->result_array();
}
</code>```

Each time increase a count variable by 10 and pass it to this function.

Body:
I am new to programming and I have my hands on a web app from a company and tried to mess around and do some changes. The app was built with PHP, MySQL, and CodeIgniter, as I was told, and it's used from the company to manage orders.

When a user wants to see the orders he clicks on the specified button and the app loads all the orders from the database, but because there are more than 10.000 orders it's slow at load. So, I want to add an option where the first load happens to get only the orders of the last 6 months and if the user wants to view older orders then I should add a button or something similar and load the rest.

<?php
 $count=1;
 $this->db->order_by("order_number", "desc");
 $completed_orders=$this->db->get_where('orders' , array(
                                        'order_status' => 'completed',
                                        'category' => 'mesoportes'
                                        ))->result_array();
 foreach ($completed_orders as $row):
?>

Any idea how i may do that.

Body:
You can initially load a certain amount of orders for eg. 10, and generate an AJAX call on the click of a button to load another 10 orders and so on.

The method to load orders from the database can be -

function get_orders($start, $limit){
 return $this->db->select('*')->where(array('order_status' => 'completed','category' => 'mesoportes'))->limit($limit, $start)->order_by("order_number", "desc")->get('orders')->result_array();
}

Each time increase a count variable by 10 and pass it to this function.


问:
How can I change status text color (iOS) in NativeScript?
My Application has a white background, so I can't see anything there like time and battery icon.

I would need the dark status bar text color from iOS.

答:
Solution :

Info plist fields If you’re using info.plist to adjust the default
  behaviour of your status bar, you’ll want to add rows for:

Status bar style(UIStatusBarStyle). List item

Choose from either:

Default (UIStatusBarStyleDefault)

Light   (UIStatusBarStyleLightContent)


问:
@SQLDelete does not propagate to child table
I want to implement soft delete using Spring JPA + hibernate. Suppose I have a material_group table which has one-to-many relationship with material_master table. In my mysql database I have restricted the deletion of the parent record if child record exists.

in material_group and material_master entity I have used the following

```<code>@SQLDelete(sql="update material_group set delete_ind='Y' where material_grp_id = ?")
</code>```

AND

```<code>@SQLDelete(sql="update material_master set delete_ind='Y' where material_id = ?")
</code>```

I can achieve one scenario i.e. material_group can be soft deleted if there is NO material.

But I want to restrict the soft delete of parent if the child records exist. However, it allows the soft delete of parent table without any change in the child entry. Any idea is appreciated to achieve this use case. (Programmatic approach is my last choice)

Code snippet is given below

material_group table

```<code>    @Entity
    @Table(name="material_group")
    @NamedQuery(name="MaterialGroup.findAll", query="SELECT m FROM MaterialGroup m")
    @SQLDelete(sql="update material_group set delete_ind='Y' where material_grp_id = ?")
    @Where(clause="delete_ind is NULL")
    public class MaterialGroup implements Serializable {

        @OneToMany(mappedBy="materialGroup", fetch = FetchType.LAZY, cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH})
        @Where(clause="delete_ind is NULL")
        private List<MaterialMaster> materialMasters;

    }
</code>```

material_master table

```<code>    @Entity
    @Table(name="material_master")
    @NamedQuery(name="MaterialMaster.findAll", query="SELECT m FROM MaterialMaster m")
    @SQLDelete(sql="update material_master set delete_ind='Y' where material_id = ?")
    @Where(clause="delete_ind is NULL")
    public class MaterialMaster implements Serializable {
        //bi-directional many-to-one association to MaterialGroup
        @ManyToOne
        @JoinColumn(name="material_grp_id")
        private MaterialGroup materialGroup;
    }
</code>```

答:
In your parent object, add this:

```<code>@OneToMany(cascade = CascadeType.ALL, targetEntity = MaterialGroup.class)
@JoinColumn(name = "YOUR_FOREIGN_KEY_COLUMN", nullable = false,
insertable = false)
private Set<MaterialMaster> materialMaster = new HashSet<MaterialMaster>
();
</code>```

After that it should work if other specs are right.

Body:
I want to implement soft delete using Spring JPA + hibernate. Suppose I have a material_group table which has one-to-many relationship with material_master table. In my mysql database I have restricted the deletion of the parent record if child record exists.

in material_group and material_master entity I have used the following

@SQLDelete(sql="update material_group set delete_ind='Y' where material_grp_id = ?")

AND

@SQLDelete(sql="update material_master set delete_ind='Y' where material_id = ?")

I can achieve one scenario i.e. material_group can be soft deleted if there is NO material.

But I want to restrict the soft delete of parent if the child records exist. However, it allows the soft delete of parent table without any change in the child entry. Any idea is appreciated to achieve this use case. (Programmatic approach is my last choice)

Code snippet is given below

material_group table

    @Entity
    @Table(name="material_group")
    @NamedQuery(name="MaterialGroup.findAll", query="SELECT m FROM MaterialGroup m")
    @SQLDelete(sql="update material_group set delete_ind='Y' where material_grp_id = ?")
    @Where(clause="delete_ind is NULL")
    public class MaterialGroup implements Serializable {

        @OneToMany(mappedBy="materialGroup", fetch = FetchType.LAZY, cascade={CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REFRESH})
        @Where(clause="delete_ind is NULL")
        private List<MaterialMaster> materialMasters;

    }

material_master table

    @Entity
    @Table(name="material_master")
    @NamedQuery(name="MaterialMaster.findAll", query="SELECT m FROM MaterialMaster m")
    @SQLDelete(sql="update material_master set delete_ind='Y' where material_id = ?")
    @Where(clause="delete_ind is NULL")
    public class MaterialMaster implements Serializable {
        //bi-directional many-to-one association to MaterialGroup
        @ManyToOne
        @JoinColumn(name="material_grp_id")
        private MaterialGroup materialGroup;
    }

Body:
In your parent object, add this:

@OneToMany(cascade = CascadeType.ALL, targetEntity = MaterialGroup.class)
@JoinColumn(name = "YOUR_FOREIGN_KEY_COLUMN", nullable = false,
insertable = false)
private Set<MaterialMaster> materialMaster = new HashSet<MaterialMaster>
();

After that it should work if other specs are right.


问:
How to write code to help garbage collector
On interview I got a question - "How to help garbage collector when writing code?".

In my opinion GC works really good and we don't need to use anything more than basic good code practices, later added that closing resources in finally clause help GC for sure but generally got suprised with such question.

Is there a good reply? Do we need to do something incredible to help garbage collector?

答:
The question is phrased oddly. The GC does not need help with its work. It will work with whatever constraints are imposed on it or fail if the constraints cannot be met.

Of course the work can be altered, but this is not done out of a desire to ease the burden on the GC – it is not a human that can be bored by its work – but due to some ulterior motive, such as improving overall program performance.

These things are normally framed as latency, energy consumption, throughput or memory footprint optimizations. But those are not the only metrics a programmer cares about. Simplicity and code readability also matter.

Naive code can be more readable but less performant. If your goal is easy-to-read code then performing complex optimizations that reduce the GC load could be counter-productive and thus "helping the GC" is not a goal in itself.

Now if your goal is to improve some performance metrics then some optimizations also involve writing code that reduces the work done by the memory management (allocation + GC) subsystem. Some possible optimizations are avoiding finalizers, finding memory leaks, reducing unnecessary allocations, avoiding humongous Object[] arrays, tuning GC parameters, buying better hardware and reducing object lifetimes. Which optimization is applicable depends on the application and can best be figured out with profilers, GC logging and related


问:
Update an attribute and remove duplicate element in an array from JavaScript
I've got a problem about some code.
Here's my array

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ]```
</div>
</div>
</p>

<p>The problem is I need to make my array looks like this.</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>[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: (1+2+4)/(1+1+1),
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: (3+5)/(1+3),
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]</code>```

which is equivalent to this

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: 2.33,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: 2,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]```
</div>
</div>
</p>

<p>First I find the same objects in array if they have the same "name" attributes.Then I sum all numberHoursSpent attributes and divide them by sum of numberSoldLodgings attributes from those objects.
Then I remove all the same elements, only keep an unique one.
P/S: The objects are the same if they have the same "name" attributes.
Here's what I've tried.</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>handleData = arr => {
  var firstElementIndex =0;
  const final = []
  var filteredArray = []
  arr.map((e,i)=>{
    if(final.includes(e.name)){
      var k = k+arr[i].numberHoursSpent;
      firstElementIndex = final.indexOf(e.name);
      arr[firstElementIndex].numberHoursSpent +=  arr[i].numberHoursSpent
      filteredArray= arr.filter(item => item !== arr[i] )
    }
    else{
      final.push(e.name)
    }
    if(i == arr.length-1){
      arr[firstElementIndex].numberHoursSpent /= k
    }
  })

  return filteredArray;
}</code>```

Please help me, thanks.

答:
Use reduce and map with destructuring, spreading, and Object.values:

const data = [{name:"Sale Network 1",numberSoldLodging:1,numberHoursSpent:1,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810},{name:"Sale Network 1",numberSoldLodging:1,numberHoursSpent:2,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810},{name:"Sale Network 2",numberSoldLodging:1,numberHoursSpent:3,mail:"sale2@gmail.com",id:"5cef5a62b9c3113764e2183b",created:1559190114548,updated:1559190114548},{name:"Sale Network 1",numberSoldLodging:1,numberHoursSpent:4,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810},{name:"Sale Network 2",numberSoldLodging:3,numberHoursSpent:5,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810}];
const res = Object.values(data.reduce((acc, { name, numberSoldLodging, numberHoursSpent, ...rest }) => {
  acc[name] = acc[name] || { name, numberSoldLodging: 0, numberHoursSpent: 0, ...rest };
  acc[name].numberSoldLodging += numberSoldLodging;
  acc[name].numberHoursSpent += numberHoursSpent;
  return acc;
}, {})).map(({ numberSoldLodging, numberHoursSpent, ...rest }) => ({ numberSoldLodging, numberHoursSpent: numberHoursSpent / numberSoldLodging, ...rest }));
console.log(res);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: auto; }</code>```

Note that the first line in the reduce function does the duplicate work, so you don't need an additional filter call at the end.

Body:
I've got a problem about some code.
Here's my array

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 1,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 2,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 1,
    numberHoursSpent: 3,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },
  {
    name: "Sale Network 1",
    numberSoldLodging: 1,
    numberHoursSpent: 4,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 3,
    numberHoursSpent: 5,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  }
  ]

The problem is I need to make my array looks like this.

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: (1+2+4)/(1+1+1),
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: (3+5)/(1+3),
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]

which is equivalent to this

[
  {
    name: "Sale Network 1",
    numberSoldLodging: 3,
    numberHoursSpent: 2.33,
    mail: "lanlehoang10@gmail.com",
    id: "5ceb9b5aff2d5732b4282886",
    created: 1558944602810,
    updated: 1558944602810
  },
  {
    name: "Sale Network 2",
    numberSoldLodging: 2,
    numberHoursSpent: 2,
    mail: "sale2@gmail.com",
    id: "5cef5a62b9c3113764e2183b",
    created: 1559190114548,
    updated: 1559190114548
  },

  ]

First I find the same objects in array if they have the same "name" attributes.Then I sum all numberHoursSpent attributes and divide them by sum of numberSoldLodgings attributes from those objects.
Then I remove all the same elements, only keep an unique one.
P/S: The objects are the same if they have the same "name" attributes.
Here's what I've tried.

handleData = arr => {
  var firstElementIndex =0;
  const final = []
  var filteredArray = []
  arr.map((e,i)=>{
    if(final.includes(e.name)){
      var k = k+arr[i].numberHoursSpent;
      firstElementIndex = final.indexOf(e.name);
      arr[firstElementIndex].numberHoursSpent +=  arr[i].numberHoursSpent
      filteredArray= arr.filter(item => item !== arr[i] )
    }
    else{
      final.push(e.name)
    }
    if(i == arr.length-1){
      arr[firstElementIndex].numberHoursSpent /= k
    }
  })

  return filteredArray;
}

Please help me, thanks.

Body:
Use reduce and map with destructuring, spreading, and Object.values:

const data = [{name:"Sale Network 1",numberSoldLodging:1,numberHoursSpent:1,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810},{name:"Sale Network 1",numberSoldLodging:1,numberHoursSpent:2,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810},{name:"Sale Network 2",numberSoldLodging:1,numberHoursSpent:3,mail:"sale2@gmail.com",id:"5cef5a62b9c3113764e2183b",created:1559190114548,updated:1559190114548},{name:"Sale Network 1",numberSoldLodging:1,numberHoursSpent:4,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810},{name:"Sale Network 2",numberSoldLodging:3,numberHoursSpent:5,mail:"lanlehoang10@gmail.com",id:"5ceb9b5aff2d5732b4282886",created:1558944602810,updated:1558944602810}];
const res = Object.values(data.reduce((acc, { name, numberSoldLodging, numberHoursSpent, ...rest }) => {
  acc[name] = acc[name] || { name, numberSoldLodging: 0, numberHoursSpent: 0, ...rest };
  acc[name].numberSoldLodging += numberSoldLodging;
  acc[name].numberHoursSpent += numberHoursSpent;
  return acc;
}, {})).map(({ numberSoldLodging, numberHoursSpent, ...rest }) => ({ numberSoldLodging, numberHoursSpent: numberHoursSpent / numberSoldLodging, ...rest }));
console.log(res);

.as-console-wrapper { max-height: 100% !important; top: auto; }

Note that the first line in the reduce function does the duplicate work, so you don't need an additional filter call at the end.


问:
How to Bold first line of :before content in Firefox?
I'm using a framework where I can add attributes to an element, but can't add dom elements myself. What I'm trying to do is add two lines of content to the :before pseudo-element, then make the first line bold.

[data-text]::before {
  content: attr(data-text);
  display: block;
  white-space: pre;
}

[data-text]::first-line {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-text="Here's some text.
Here's a new line with more text.">
  ...
</div></code>```

This effect works exactly as I want it to in Chrome, Edge and IE11 (which was a shock), but not in Firefox (also a shock). Why does Firefox not bold the first line while the other browsers do? How do I get the first line bolded?

答:
Hey can you try like this;

[data-text]::before {
  content: attr(data-text);
  /*display: block;*/
  white-space: pre;
}

[data-text]::first-line {
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-text="Here's some text.
Here's a new line with more text.
">
  ...
</div></code>```

Body:
I'm using a framework where I can add attributes to an element, but can't add dom elements myself. What I'm trying to do is add two lines of content to the :before pseudo-element, then make the first line bold.

[data-text]::before {
  content: attr(data-text);
  display: block;
  white-space: pre;
}

[data-text]::first-line {
  font-weight: bold;
}

  ...

This effect works exactly as I want it to in Chrome, Edge and IE11 (which was a shock), but not in Firefox (also a shock). Why does Firefox not bold the first line while the other browsers do? How do I get the first line bolded?

Body:
Hey can you try like this;

[data-text]::before {
  content: attr(data-text);
  /*display: block;*/
  white-space: pre;
}

[data-text]::first-line {
  font-weight: bold;
}

<div data-text="Here's some text.
Here's a new line with more text.
">
  ...
</div>


问:
Why JWT is considered as can't be managed from server?
I know perfectly what JWT is. But it is a known fact that there is a problem with revoking the JWT .

For example, I've read here:

We had several cases where we wanted the users at HelpTap to logout by
  cleaning up the cookies, but we cannot ask them to do so every time.
  As well consider the case that a user’s mobile is stolen, and he wants
  to logout of all existing sessions(e.g. Gmail’s logout other sessions
  feature). Well it's not possible in case of JWT.

But if I can store the user's info in the jwt data section, then I can also create a DB in the server which will check whether a specific user should be revoked or not.

If it should, then I can send a new JWT.

Question:

What am I missing? I sure can revoke the specific user's JWT and send him a new one.

答:
Sure, you can create a JWT, store it (or its JTI) in a database, and you can use the database to look up tokens and reject revoked tokens.

But the point in JWT is that it's stateless. If you have to make a database query to check it, you could just as well send your user a plain old random session id, and retrieve user data on the server side, which in fact would be more secure than any JWT. By using a database lookup, you pretty much only have the drawbacks of a JWT and a session combined, and your JWT is hardly more than just a stateful session id.


问:
multiple aggregate functions with multiple tables in SQL Server
I am trying to get data for entered person, I want to pull out data as No of invoices and No of line items for particular person.

The output is

```<code>Entered_by  No of line items
CD               9
CD               136084
deepa             7
deepa             18
dolly             757
dolly             22350
kroshni         666
kroshni         16161
lokesh           4
lokesh           999
MHeera           639
MHeera             20427
nandini            7
nandini            5318
</code>```

Here the data in No of line items is mixing of both ’ No of line items’ count and  ‘No of invoices’ count, I want to show like

```<code>Entered_by  No of line items    No of invoices
CD               136084              9
deepa               18                7
dolly               22350               757
</code>```

Please help me with this somebody ….. 

Here is the T-SQL query

```<code>select ENTERED_BY, count(entered_by) 'NO OF LINE ITEMS'
from im_invoice, im_invoice_line_item, im_invoice_inventory
where invoice_rid = invoice_fk
and invoice_inventory_rid = invoice_inv_fk
and enter_date between dateadd(mm, -3, getdate()) and dateadd(mm,0,getdate())
group by entered_by

union

select entered_by, count(invoice_num) 'NO OF INVOICES' from im_invoice
where enter_date between dateadd(mm, -3, getdate()) and dateadd(mm,0,getdate())
group by entered_by
</code>```

答:
As Joe said, if you give us a more detailed description we can give you better answers, but until then, quick and dirty way to accomplish this is as follows:

Get rid of the union

Turn the 2 queries into derived tables

Select from them joining on entered_by.

Eg.

```<code>SELECT LineItems.ENTERED_BY, [NO OF LINE ITEMS], [NO OF INVOICES]
FROM
(SELECT ENTERED_BY,COUNT(entered_by) 'NO OF LINE ITEMS'
FROM im_invoice, im_invoice_line_item,im_invoice_inventory
WHERE invoice_rid = invoice_fk
AND invoice_inventory_rid = invoice_inv_fk
AND enter_date BETWEEN dateadd(mm, -3, getdate()) AND dateadd(mm,0,getdate())
GROUP BY entered_by) AS LineItems
INNER JOIN
(SELECT entered_by, count(invoice_num) 'NO OF INVOICES'
FROM im_invoice
WHERE enter_date BETWEEN dateadd(mm, -3, getdate()) AND dateadd(mm,0,getdate())
GROUP BY entered_by ) AS invoices
ON invoices.entered_by = LineItems.ENTERED_BY
</code>```

Body:
I am trying to get data for entered person, I want to pull out data as No of invoices and No of line items for particular person.

The output is

Entered_by  No of line items
CD               9
CD               136084
deepa             7
deepa             18
dolly             757
dolly             22350
kroshni         666
kroshni         16161
lokesh           4
lokesh           999
MHeera           639
MHeera             20427
nandini            7
nandini            5318

Here the data in No of line items is mixing of both ’ No of line items’ count and  ‘No of invoices’ count, I want to show like

Entered_by  No of line items    No of invoices
CD               136084              9
deepa               18                7
dolly               22350               757

Please help me with this somebody ….. 

Here is the T-SQL query

select ENTERED_BY, count(entered_by) 'NO OF LINE ITEMS'
from im_invoice, im_invoice_line_item, im_invoice_inventory
where invoice_rid = invoice_fk
and invoice_inventory_rid = invoice_inv_fk
and enter_date between dateadd(mm, -3, getdate()) and dateadd(mm,0,getdate())
group by entered_by

union

select entered_by, count(invoice_num) 'NO OF INVOICES' from im_invoice
where enter_date between dateadd(mm, -3, getdate()) and dateadd(mm,0,getdate())
group by entered_by

Body:
As Joe said, if you give us a more detailed description we can give you better answers, but until then, quick and dirty way to accomplish this is as follows:

Get rid of the union

Turn the 2 queries into derived tables

Select from them joining on entered_by.

Eg.

SELECT LineItems.ENTERED_BY, [NO OF LINE ITEMS], [NO OF INVOICES]
FROM
(SELECT ENTERED_BY,COUNT(entered_by) 'NO OF LINE ITEMS'
FROM im_invoice, im_invoice_line_item,im_invoice_inventory
WHERE invoice_rid = invoice_fk
AND invoice_inventory_rid = invoice_inv_fk
AND enter_date BETWEEN dateadd(mm, -3, getdate()) AND dateadd(mm,0,getdate())
GROUP BY entered_by) AS LineItems
INNER JOIN
(SELECT entered_by, count(invoice_num) 'NO OF INVOICES'
FROM im_invoice
WHERE enter_date BETWEEN dateadd(mm, -3, getdate()) AND dateadd(mm,0,getdate())
GROUP BY entered_by ) AS invoices
ON invoices.entered_by = LineItems.ENTERED_BY