问:
How to Integrate prettier-js.el into spacemacs
I'm trying to get prettier working in spacemacs.

I have (prettier-js :location (recipe :url "https://raw.githubusercontent.com/prettier/prettier/master/editors/emacs/prettier-js.el" :fetcher url)) which is somewhat working, but then in Messages I see

```<code>Contacting host: raw.githubusercontent.com:443
Wrote /Users/travis/.emacs.d/.cache/quelpa/build/prettier-js/prettier-js.el
File: /Users/travis/.emacs.d/.cache/quelpa/build/prettier-js/prettier-js.stamp
Error getting PACKAGE-DESC: (search-failed ;;; prettier-js.el ends here)
Cannot load prettier-js
</code>```

I don't know enough emacs yet to know know what a PACKAGE-DESC does, or if I need it to get prettier to load.

I'm trying to do this in a private layer

The docs say:

Add this to your init

```<code>(require 'prettier-js)
(add-hook 'js-mode-hook
          (lambda ()
            (add-hook 'before-save-hook 'prettier-before-save)))
</code>```

I think I should have something like:

```<code>(defun myJS/post-init-prettier-js ()
  "Initialize prettier-js"
  (use-package prettier-js)
  :defer t
  :init
  (progn
    (add-hook 'before-save-hook 'prettier-before-save)
    )
  )
</code>```

in my layer

答: The prettier-js package is now on melpa to install it add prettier-js to dotspacemacs-additional-packages in your spacemacs file.</p>

Body:
I'm trying to get prettier working in spacemacs.

I have (prettier-js :location (recipe :url "https://raw.githubusercontent.com/prettier/prettier/master/editors/emacs/prettier-js.el" :fetcher url)) which is somewhat working, but then in Messages I see

Contacting host: raw.githubusercontent.com:443
Wrote /Users/travis/.emacs.d/.cache/quelpa/build/prettier-js/prettier-js.el
File: /Users/travis/.emacs.d/.cache/quelpa/build/prettier-js/prettier-js.stamp
Error getting PACKAGE-DESC: (search-failed ;;; prettier-js.el ends here)
Cannot load prettier-js

I don't know enough emacs yet to know know what a PACKAGE-DESC does, or if I need it to get prettier to load.

I'm trying to do this in a private layer

The docs say:

Add this to your init

(require 'prettier-js)
(add-hook 'js-mode-hook
          (lambda ()
            (add-hook 'before-save-hook 'prettier-before-save)))

I think I should have something like:

(defun myJS/post-init-prettier-js ()
  "Initialize prettier-js"
  (use-package prettier-js)
  :defer t
  :init
  (progn
    (add-hook 'before-save-hook 'prettier-before-save)
    )
  )

in my layer


来源: stackexchange

问:
When I publish c# app the command line args are NOT passed through
I have an app that works in debug. The command line args are passed into the application.

But when I publish from VS to a directory on disk, and then launch the application with

MyApp.application "MyArg"

Then the arguments do not appear to be passed to the app.

```<code>static class Program
{
    public static string[] Args;
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        Args = args;
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
</code>```

答:
You must define the main class and output type in the project properties.
Example</p>

ContentLicense: CC BY-SA 3.0

Body:
I have an app that works in debug. The command line args are passed into the application.

But when I publish from VS to a directory on disk, and then launch the application with

MyApp.application "MyArg"

Then the arguments do not appear to be passed to the app.

static class Program
{
    public static string[] Args;
    ///
    /// The main entry point for the application.
    ///
    [STAThread]
    static void Main(string[] args)
    {
        Args = args;
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}


问:
Reference all indexes in list and check for existence of value in python
I'm trying to create if block in my python3 script that checks if a value exists within a list I pull from JSON. The JSON data is below:

```<code>[
  {
    "id": 59616405645,
    "name": "Foo"
  },
  {
    "id": 990164054345,
    "name": "FindMe"
  },
  {
    "id": 2009167874,
    "name": "Bar"
  }
]
</code>```

I'm trying to determine whether or not the value of Bar exists within the list. To do so I'm doing the following which directly references the index:

```<code>if "FindMe" in m_orgs[1].values():
    print("Yo it's here")
else:
    print("Yo it's not here.")
</code>```

But the JSON data I'm pulling will always have different results and we will never know the index numbers, so direct reference will not work. How do I reference all indexes in a list at once?

答:
You can first translate the original json data to set of data, and then simply check through set operations,</p>

```<code>name_set = {org['name'] for org in m_orgs}
print 'FindMe' in name_set
</code>```

Body:
I'm trying to create if block in my python3 script that checks if a value exists within a list I pull from JSON. The JSON data is below:

[
  {
    "id": 59616405645,
    "name": "Foo"
  },
  {
    "id": 990164054345,
    "name": "FindMe"
  },
  {
    "id": 2009167874,
    "name": "Bar"
  }
]

I'm trying to determine whether or not the value of Bar exists within the list. To do so I'm doing the following which directly references the index:

if "FindMe" in m_orgs[1].values():
    print("Yo it's here")
else:
    print("Yo it's not here.")

But the JSON data I'm pulling will always have different results and we will never know the index numbers, so direct reference will not work. How do I reference all indexes in a list at once?

Body:
You can first translate the original json data to set of data, and then simply check through set operations,

name_set = {org['name'] for org in m_orgs}
print 'FindMe' in name_set


问:
Printing debug values in a cryptographic exchange
I have created this basic program to implement the Diffie-Hellman algorithm. I want s to be a randomly generated prime number, and q to be a randomly generated integer. sk1 and sk2 are shared keys which are also generated randomly. pk1 and pk2 are modulus calculated values which I have to prove are equal to each other. I think my formula is correct but I am not sure how to print the values of s, q, sk1, sk2, pk1 and pk2 to verify my requirements. My code is pasted below and I would really appreciate if anyone could help me with the print statements.

package javaapplication1;
import java.util.Random;
import java.math.*;

public class DH {
    public static void main(String [] arg) {

        int s, q;
        double sk1, sk2, pk1 = 0, pk2 = 0;
        Random generator = new Random();
        s = generator.nextInt(50000);
        q = generator.nextInt(50000);

        sk1 = generator.nextInt();
        sk2 = generator.nextInt();

        if(s==1 || s==2) {
            for(int i = 2; i< (int)(s/2); i++) {
                if(s/i != (int)(s/i)) {
                    double a= Math.pow(q,sk1);
                    pk1 = a%s;

                    double b= Math.pow(q, sk2);
                    pk2 = b%s;

                    if(pk1==pk2) {
                        System.out.println("true");
                    }

                    System.out.println(s);
                    System.out.println(q);
                    System.out.println(sk1);
                    System.out.println(sk2);
                    System.out.println(pk1);
                    System.out.println(pk2);
                }
            }
        }
    }
}
```

答:
Your print statements are inside of your if case.  Have you considered that s != 1 or s != 2 ?

```<code>package javaapplication1;
import java.util.Random;
import java.math.*;

public class DH {
    public static void main(String [] arg) {

        int s, q;
        double sk1, sk2, pk1 = 0, pk2 = 0;
        Random generator = new Random();
        s = generator.nextInt(50000);
        q = generator.nextInt(50000);

        sk1 = generator.nextInt();
        sk2 = generator.nextInt();

        if(s==1 || s==2) {
            for(int i = 2; i< (int)(s/2); i++) {
                if(s/i != (int)(s/i)) {
                    double a= Math.pow(q,sk1);
                    pk1 = a%s;
                    double b= Math.pow(q, sk2);
                    pk2 = b%s;

                    if(pk1==pk2) {
                        System.out.println("true");
                    }
                }
            }
        }
        System.out.println(s);
        System.out.println(q);
        System.out.println(sk1);
        System.out.println(sk2);
        System.out.println(pk1);
        System.out.println(pk2);
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Your print statements are inside of your if case.  Have you considered that s != 1 or s != 2 ?

package javaapplication1;
import java.util.Random;
import java.math.*;

public class DH {
    public static void main(String [] arg) {

        int s, q;
        double sk1, sk2, pk1 = 0, pk2 = 0;
        Random generator = new Random();
        s = generator.nextInt(50000);
        q = generator.nextInt(50000);

        sk1 = generator.nextInt();
        sk2 = generator.nextInt();

        if(s==1 || s==2) {
            for(int i = 2; i< (int)(s/2); i++) {
                if(s/i != (int)(s/i)) {
                    double a= Math.pow(q,sk1);
                    pk1 = a%s;
                    double b= Math.pow(q, sk2);
                    pk2 = b%s;

                    if(pk1==pk2) {
                        System.out.println("true");
                    }
                }
            }
        }
        System.out.println(s);
        System.out.println(q);
        System.out.println(sk1);
        System.out.println(sk2);
        System.out.println(pk1);
        System.out.println(pk2);
    }
}

ContentLicense: CC BY-SA 2.5


问:
How can get_string error get avoided?
I'm doing the CS50 course, pset2 initials. The only error I get is a problem with get_string: it would have an 'incompatible pointer types initializing 'string' with an expression of type 'string (void)'. I really don't understand what I am doing wrong, because my code for get_string worked for the last problem set.. Here's my code: </p>

```<code>#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    // ask user for input
    printf("What are your names?");
    string s = get_string;

    // print first letter from string & capitalize
    printf("%c", toupper(s[0]));

    //iterate over characters in current string + start loop
    for (int i = 0; i < strlen(s); i++)
    {
        //find space character
        if (s[i] == ' ')
        {
            // print character next to space & capitalize
            printf("%c", toupper(s[i++]));
        }
    // new rule
    printf("\n");
    }
}
</code>```

答:
Although you have not shown us cs50.h, we can guess that get_string is a function, so this:

```<code>string s = get_string;
</code>```

Needs to be:

```<code>string s = get_string();
</code>```

Title: How can get_string error get avoided?

Body:
I'm doing the CS50 course, pset2 initials. The only error I get is a problem with get_string: it would have an 'incompatible pointer types initializing 'string' with an expression of type 'string (void)'. I really don't understand what I am doing wrong, because my code for get_string worked for the last problem set.. Here's my code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    // ask user for input
    printf("What are your names?");
    string s = get_string;

    // print first letter from string & capitalize
    printf("%c", toupper(s[0]));

    //iterate over characters in current string + start loop
    for (int i = 0; i < strlen(s); i++)
    {
        //find space character
        if (s[i] == ' ')
        {
            // print character next to space & capitalize
            printf("%c", toupper(s[i++]));
        }
    // new rule
    printf("\n");
    }
}

Body:
Although you have not shown us cs50.h, we can guess that get_string is a function, so this:

string s = get_string;

Needs to be:

string s = get_string();


问:
SQL - WHERE clause Return results with next working day
I seem to be asking a lot of SQL questions at the moment. (I would normally write a program to sort the data into a report table, however at the moment that is not possible, and needs to be done using SQL)

The Question
I need a where clause that returns results with the next working day. i.e. Monday 01/01/01 the next working day would be Tuesday 02/01/01 which could be achieved with a simple date add. However on a Friday 05/01/01 the next working day is Monday 08/01/01. Is there anything built in to help cope with this easily?

Thanks for your advice.

答:
It's been basically answered above, but it took me a while to get it and I thought maybe this will help somebody. Is used a simple CASE-WHEN.

This is a check in order to find out which days are weekdays

```<code>DATEPART(dw, date) -> MON through FRI = 1,2,3,4,5    SAT = 6,     SUN = 7
</code>```

This is the CASE-WHEN:

```<code>CASE
    WHEN DATEPART(weekday, date) <= 5 THEN date       -- weekdays, no change
    WHEN DATEPART(weekday, date)  = 6 THEN date + 2   -- SAT + 2 = MON
    WHEN DATEPART(weekday, date)  = 6 THEN date + 1   -- SUN + 1 = MON
END AS 'WEEKDAY_DATES'
</code>```

Check, if the statement actually gets you weekdays only:

```<code>CASE
    WHEN DATEPART(weekday, date) <= 5 THEN DATENAME(weekday, date)
    WHEN DATEPART(weekday, date)  = 6 THEN DATENAME(weekday, date + 2)
    WHEN DATEPART(weekday, date)  = 6 THEN DATENAME(weekday, date + 1)
END AS 'WEEKDAY_NAMES'
</code>```

Body:
It's been basically answered above, but it took me a while to get it and I thought maybe this will help somebody. Is used a simple CASE-WHEN.

This is a check in order to find out which days are weekdays

DATEPART(dw, date) -> MON through FRI = 1,2,3,4,5    SAT = 6,     SUN = 7

This is the CASE-WHEN:

CASE
    WHEN DATEPART(weekday, date) <= 5 THEN date       -- weekdays, no change
    WHEN DATEPART(weekday, date)  = 6 THEN date + 2   -- SAT + 2 = MON
    WHEN DATEPART(weekday, date)  = 6 THEN date + 1   -- SUN + 1 = MON
END AS 'WEEKDAY_DATES'

Check, if the statement actually gets you weekdays only:

CASE
    WHEN DATEPART(weekday, date) <= 5 THEN DATENAME(weekday, date)
    WHEN DATEPART(weekday, date)  = 6 THEN DATENAME(weekday, date + 2)
    WHEN DATEPART(weekday, date)  = 6 THEN DATENAME(weekday, date + 1)
END AS 'WEEKDAY_NAMES'


问:
How to apply styles to a component programatically angular 2?
I have a component with four different possible styles files that could be applied depending on some variable. How could I apply the styles of that component before it renders? </p>

```<code>@Component({
    selector: 'settings-editor',
    templateUrl: './settings-editor.component.html',
    styleUrls: [ './a.less', './b.less' , './c.less' ]
})
export class SettingsEditorComponent implements OnInit {
   @Input()
   public styleType: string;

   ngOnInit() {
     if (this.styleType === 'A') {
        // Apply styles  from a.less only

     }
   }

}
</code>```

答:
Günter is right. Here's a Plunker that implements such a strategy: https://plnkr.co/edit/LfjCS6DMSi8d44O4Uhkj?p=preview

I actually wrote a blog post on dynamically styling components and just noticed I missed this possibility. Gonna add it.

If you don't have the necessity to scope it to a single component, but if it's rather a "global" theming story, you could also take a look at handling this at a CSS level. Like having for instance a CSS class card which in style1.css is styled one way and in style2.css in the other.

I'd also try to look into the Angular Material 2 repo. They also talk about theming on the official site.

Body:
I have a component with four different possible styles files that could be applied depending on some variable. How could I apply the styles of that component before it renders?

@Component({
    selector: 'settings-editor',
    templateUrl: './settings-editor.component.html',
    styleUrls: [ './a.less', './b.less' , './c.less' ]
})
export class SettingsEditorComponent implements OnInit {
   @Input()
   public styleType: string;

   ngOnInit() {
     if (this.styleType === 'A') {
        // Apply styles  from a.less only

     }
   }

}


问:
What are the chronological steps in building a cross browser compatible site?
I am working on my first project that requires me to worry about cross browser compatibility.  Since this is my first time doing so, I dont know how to go about completing the project.  I am specifically worried about IE.  Should I complete my project in a more graceful browser then hack it to work in IE, or should I simultaneously build my program up in both environments?</p>

答:
there is alot of greate tools that makes life alot easier for you there is for example a
css framework called blueprint you could use, it has already everything set for every specific browser so that you get the same outcome in all browsers. And using jquery as your javascript framework does add an extra insurance that you'll have it working in most browser.

but remeber there is no such thing as 100% cross browser compatibility for all the browsers and all the versions in world.


问:
Getting internal server error when setting up .htaccess file to web.config file
I am trying to upload codeigniter project on windows server. when i uploades project on windows server my index page running perfectly but wheb i enter username and password to login page an error come with message.

```<code>HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       BeginRequest
Handler    Not yet determined
Error Code     0x80070003
Config Error       Cannot read configuration file
Config File    \\?\D:\Inetpub\vhosts\sp-tapi.in\clean-note.rudra-infotech.com\test\web.config
Requested URL      http://clean-note.rudra-infotech.com:80/test
Physical Path      D:\Inetpub\vhosts\sp-tapi.in\clean-note.rudra-infotech.com\test
Logon Method       Not yet determined
Logon User     Not yet determined
</code>```

I have converted my .htaccess file to web.config file for IIS server (using IIS 8.5)
my web.config file is

```<code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="rule 1S" stopProcessing="true">
<match url="^(.*)$"  />
<action type="Rewrite" url="/index.php/{R:1}"  appendQueryString="true" />
</rule>

      </rules>
    </rewrite>
    <httpErrors>
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" path="/somedir/oops404.htm" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
  <system.web>
    <customErrors mode="Off" />
  </system.web>
</configuration>
</code>```

答:
I had identical issue, please check with this modifications, it worked for me.</p>

```<code>        <?xml version="1.0" encoding="UTF-8"?>
    <configuration>

    <system.webServer>

        <httpErrors errorMode="Detailed" />
    <asp scriptErrorSentToBrowser="true"/>

    <rewrite>
    <rules>
        <rule name="RuleRemoveIndex" stopProcessing="true">
            <match url="^(.*)$" ignoreCase="false" />
            <conditions>
                     <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
            <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true"/>
        </rule>
    </rules>
    </rewrite>

</system.webServer>

<system.web>
    <customErrors mode="Off"/>
    <compilation debug="true"/>
</system.web>

</configuration>
</code>```

Body:
I am trying to upload codeigniter project on windows server. when i uploades project on windows server my index page running perfectly but wheb i enter username and password to login page an error come with message.

HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.

Detailed Error Information:
Module     IIS Web Core
Notification       BeginRequest
Handler    Not yet determined
Error Code     0x80070003
Config Error       Cannot read configuration file
Config File    \\?\D:\Inetpub\vhosts\sp-tapi.in\clean-note.rudra-infotech.com\test\web.config
Requested URL      http://clean-note.rudra-infotech.com:80/test
Physical Path      D:\Inetpub\vhosts\sp-tapi.in\clean-note.rudra-infotech.com\test
Logon Method       Not yet determined
Logon User     Not yet determined

I have converted my .htaccess file to web.config file for IIS server (using IIS 8.5)
my web.config file is

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="rule 1S" stopProcessing="true">
<match url="^(.*)$"  />
<action type="Rewrite" url="/index.php/{R:1}"  appendQueryString="true" />
</rule>

      </rules>
    </rewrite>
    <httpErrors>
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" path="/somedir/oops404.htm" responseMode="ExecuteURL" />
    </httpErrors>
  </system.webServer>
  <system.web>
    <customErrors mode="Off" />
  </system.web>
</configuration>

Body:
I had identical issue, please check with this modifications, it worked for me.

        <?xml version="1.0" encoding="UTF-8"?>
    <configuration>

    <system.webServer>

        <httpErrors errorMode="Detailed" />
    <asp scriptErrorSentToBrowser="true"/>

    <rewrite>
    <rules>
        <rule name="RuleRemoveIndex" stopProcessing="true">
            <match url="^(.*)$" ignoreCase="false" />
            <conditions>
                     <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
                <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            </conditions>
            <action type="Rewrite" url="index.php/{R:1}" appendQueryString="true"/>
        </rule>
    </rules>
    </rewrite>

</system.webServer>

<system.web>
    <customErrors mode="Off"/>
    <compilation debug="true"/>
</system.web>

</configuration>


问:
Executing data validation rules from a table using a procedure with runtime values
I have a table that is filled with many data validation queries. For example a row:

```<code>SELECT end_time - start_time
FROM mt_process_status
WHERE process_id = <PROCESS_ID> AND ref_date = <REF_DATE>
</code>```

I have to execute all these SQL statements filling the values within '<>' with run time values and check if the performance of the process has not changed.

Can this be done with a stored procedure? I want to understand what the solution would look like.  Any links to documentation of this sort of thing, anything to guide me in the right direction.

答: I would put the reference data in another table and do it as a join</p>

Body:
I have a table that is filled with many data validation queries. For example a row:

SELECT end_time - start_time
FROM mt_process_status
WHERE process_id = <PROCESS_ID> AND ref_date = <REF_DATE>

I have to execute all these SQL statements filling the values within '<>' with run time values and check if the performance of the process has not changed.

Can this be done with a stored procedure? I want to understand what the solution would look like.  Any links to documentation of this sort of thing, anything to guide me in the right direction.


问:
"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal
So got this project which worked just fine before the weekend (have other problems, but at least Tomcat launched). Now when I try to launch the Tomcat server it immediately gives the following error:

```<code>Server Tomcat v7.0 Server at localhost failed to start.
</code>```

However, I can start Tomcat just fine via Terminal, and this problem is occurring in Eclipse (Eclipse Java EE IDE for Web Developers. Version: Juno Service Release 1
Build id: 20121004-1855)

I scoured several forums trying to find a solution but to no avail.

答:
open your web.xml file. (if you don't know where is it, then just google it.)
it is like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
.
.
.
.
</web-app>
</code>```

just below the <?xml version="1.0" encoding="UTF-8"?> line, add a tag <element> and close it in the very bottom with </element> tag. Done.

Body:
So got this project which worked just fine before the weekend (have other problems, but at least Tomcat launched). Now when I try to launch the Tomcat server it immediately gives the following error:

Server Tomcat v7.0 Server at localhost failed to start.

However, I can start Tomcat just fine via Terminal, and this problem is occurring in Eclipse (Eclipse Java EE IDE for Web Developers. Version: Juno Service Release 1
Build id: 20121004-1855)

I scoured several forums trying to find a solution but to no avail.

Body:
open your web.xml file. (if you don't know where is it, then just google it.)
it is like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
.
.
.
.
</web-app>

just below the <?xml version="1.0" encoding="UTF-8"?> line, add a tag <element> and close it in the very bottom with </element> tag. Done.


问:
Get logged in user details from identity in service
I can get details of logged in user from controller injecting IHttpContextAccessor httpContextAccessor. But when I try it in my service, it does not work. I get these error

```<code>{System.Exception: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you a...
</code>```

What I have done is create an IUserService interface. Then added GetUser method there with its implementation as:

```<code>public class UserService : IUserService
{
    private readonly IHttpContextAccessor _context;
    private readonly UserManager<User> _userManager;
    public UserService(IHttpContextAccessor context, UserManager<User> userManager)
    {
        _context = context;
        _userManager = userManager;
    }
    public async Task<User> GetUser()
    {
        return await _userManager.FindByNameAsync(_context.HttpContext.User.Identity.Name);
    }
}
</code>```

I have added  services.AddSingleton<IUserService, UserService>(); in my IServiceCollection too.

答:
Don't add UserService as a singleton. It has an injected UserManager that itself has an injected DbContext that will explode if you try to use it like this and it is almost certainly getting disposed so on second use it won't work. Instead you are safest adding it as a transient object:

```<code>services.AddTransient<IUserService, UserService>();
</code>```

To add to this, you must consider your hierarchy of objects. If a singleton object has a transient one injected into it, that transient object will remain with the singleton for the lifetime and will likely be disposed by the DI framework, leaving your singleton in an unsafe state.

Body:
I can get details of logged in user from controller injecting IHttpContextAccessor httpContextAccessor. But when I try it in my service, it does not work. I get these error

{System.Exception: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you a...

What I have done is create an IUserService interface. Then added GetUser method there with its implementation as:

public class UserService : IUserService
{
    private readonly IHttpContextAccessor _context;
    private readonly UserManager<User> _userManager;
    public UserService(IHttpContextAccessor context, UserManager<User> userManager)
    {
        _context = context;
        _userManager = userManager;
    }
    public async Task<User> GetUser()
    {
        return await _userManager.FindByNameAsync(_context.HttpContext.User.Identity.Name);
    }
}

I have added  services.AddSingleton<IUserService, UserService>(); in my IServiceCollection too.

Body:
Don't add UserService as a singleton. It has an injected UserManager that itself has an injected DbContext that will explode if you try to use it like this and it is almost certainly getting disposed so on second use it won't work. Instead you are safest adding it as a transient object:

services.AddTransient<IUserService, UserService>();

To add to this, you must consider your hierarchy of objects. If a singleton object has a transient one injected into it, that transient object will remain with the singleton for the lifetime and will likely be disposed by the DI framework, leaving your singleton in an unsafe state.


问:
Running an executable under Scheduled Task with web access
I'm looking to find out if there are any inherent restrictions when running an executable from a scheduled task that calls a web service while there are no users logged on?

I can't see any inhernt issue if the user that the taski runs under has the correct permissions but would there be any issues connecting over port 80 to a web service?

Thanks in advance.

答:
If any authentication is required for either a web proxy, the web service, or anything else, you'll need to store the password.

You will find a bit of an overview at https://blogs.technet.microsoft.com/askperf/2015/02/18/help-my-scheduled-task-does-not-run/ that covers this.


问:
Using Environment.UserName on a StreamReader
I need help in changing the \bob\ part to something like \%username%\ when locating the file to read.

I've been reading and everything is saying Environment.UserName but how do I add this to my current code?

```<code>Imports System.IO
Imports System

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim sr As New StreamReader("C:\Users\bob\Dropbox\Apps\Attachments\my.txt")
        Dim word As String = ""
        Dim words(1000) As String
        Dim i As Integer = 0

        Do Until sr.Peek = -1
            word = sr.ReadLine()
            words(i) = word

            mytext.AppendText(vbNewLine + vbNewLine + TimeOfDay + vbNewLine + vbNewLine + words(i) + vbNewLine + "__________________________________________")
            i += 1

        Loop

        sr.Close()

    End Sub

End Class
</code>```

答:
Adding on from Bali C's answer I would also implement Using which will help with the disposing of the StreamReader and it would be good practice to use Path.Combine:

```<code>Using sr As New StreamReader(Path.Combine("C:\Users", Environment.UserName, "Dropbox\Apps\Attachments\my.txt"))

    'Do your work

End Using
</code>```

Body:
I need help in changing the \bob\ part to something like \%username%\ when locating the file to read.

I've been reading and everything is saying Environment.UserName but how do I add this to my current code?

Imports System.IO
Imports System

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim sr As New StreamReader("C:\Users\bob\Dropbox\Apps\Attachments\my.txt")
        Dim word As String = ""
        Dim words(1000) As String
        Dim i As Integer = 0

        Do Until sr.Peek = -1
            word = sr.ReadLine()
            words(i) = word

            mytext.AppendText(vbNewLine + vbNewLine + TimeOfDay + vbNewLine + vbNewLine + words(i) + vbNewLine + "__________________________________________")
            i += 1

        Loop

        sr.Close()

    End Sub

End Class

Body:
Adding on from Bali C's answer I would also implement Using which will help with the disposing of the StreamReader and it would be good practice to use Path.Combine:

Using sr As New StreamReader(Path.Combine("C:\Users", Environment.UserName, "Dropbox\Apps\Attachments\my.txt"))

    'Do your work

End Using


问:
Distinct() returns duplicates with a user-defined type
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

```<code>class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}
</code>```

答:
It seems that a simple Distinct operation can be implemented more elegantly as follows:

```<code>var distinct = items.GroupBy(x => x.ID).Select(x => x.First());
</code>```

where ID is the property that determines if two objects are semantically equivalent.  From the confusion here (including that of myself), the default implementation of Distinct() seems to be a little convoluted.

Body:
I'm trying to write a Linq query which returns an array of objects, with unique values in their constructors.  For integer types, Distinct returns only one copy of each value, but when I try creating my list of objects, things fall apart.  I suspect it's a problem with the equality operator for my class, but when I set a breakpoint, it's never hit.

Filtering out the duplicate int in a sub-expression solves the problem, and also saves me from constructing objects that will be immediately discarded, but I'm curious why this version doesn't work.

UPDATE: 11:04 PM  Several folks have pointed out that MyType doesn't override GetHashCode().  I'm afraid I oversimplified the example.  The original MyType does indeed implement it.  I've added it below, modified only to put the hash code in a temp variable before returning it.

Running through the debugger, I see that all five invocations of GetHashCode return a different value. And since MyType only inherits from Object, this is presumably the same behavior Object would exhibit.

Would I be correct then to conclude that the hash should instead be based on the contents of Value?  This was my first attempt at overriding operators, and at the time, it didn't appear that GetHashCode needed to be particularly fancy.  (This is the first time one of my equality checks didn't seem to work properly.)

class Program
{
    static void Main(string[] args)
    {
        int[] list = { 1, 3, 4, 4, 5 };
        int[] list2 =
            (from value in list
             select value).Distinct().ToArray();    // One copy of each value.
        MyType[] distinct =
            (from value in list
             select new MyType(value)).Distinct().ToArray(); // Two objects created with 4.

        Array.ForEach(distinct, value => Console.WriteLine(value));
    }
}

class MyType
{
    public int Value { get; private set; }

    public MyType(int arg)
    {
        Value = arg;
    }

    public override int GetHashCode()
    {
        int retval = base.GetHashCode();
        return retval;
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        MyType rhs = obj as MyType;
        if ((Object)rhs == null)
            return false;

        return this == rhs;
    }

    public static bool operator ==(MyType lhs, MyType rhs)
    {
        bool result;

        if ((Object)lhs != null && (Object)rhs != null)
            result = lhs.Value == rhs.Value;
        else
            result = (Object)lhs == (Object)rhs;

        return result;
    }

    public static bool operator !=(MyType lhs, MyType rhs)
    {
        return !(lhs == rhs);
    }
}

Body:
It seems that a simple Distinct operation can be implemented more elegantly as follows:

var distinct = items.GroupBy(x => x.ID).Select(x => x.First());

where ID is the property that determines if two objects are semantically equivalent.  From the confusion here (including that of myself), the default implementation of Distinct() seems to be a little convoluted.


问:
Listen to PanResponder to change state values
I'm pretty new to React Native and I'm facing a problem:

I understood the transformations that you can do with a PanResponder and then using the interpolate function.

Example:

```<code>let cardOpacity = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [0.9, 0, 0.9]})};
</code>```

The problem I'm facing is a bit more tricky because I want to extract values from this interpolation and not any style:

I want that code to work basically:

```<code>_renderApplyOrDislikeHint() {
  let cardOpacity = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [0.9, 0, 0.9]})};
  let value = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [1, 0, 1]})};
  this.state.pan.x.addListener(({value}) => {
    this.x = value._value
    console.log('Value changed', this.x);
  });
  let dimensionStyle = {
    backgroundColor: 'white',
    width: this.props.cardWidth,
    height: this.props.cardHeight,
    position: 'absolute'
  };
  return (
    <Animated.View style={[dimensionStyle, cardOpacity]}>
      {this.renderHint()}
    </Animated.View>
  )
}

renderHint(){
  console.log('X in render hint', this.x)
  return this.x > 0 ? <Text>Yes</Text> : <Text>Nope</Text>
}
</code>```

The problem is that animated value work great for styles but they do not force the re-rendering of the renderHint() function.
And it is a very bad idea to change state during the render process.

How can I achieve that?

答:
Soooo, I found a solution

Basically in React, the views are listening to the state of the component: so to "re-render" we need to change the state.

Therefore I added a simple change in the pan responder:

```<code>onPanResponderGrant: (e, gestureState) => {
    this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
    this.state.pan.setValue({x: 0, y: 0});
    this.state.pan.x.addListener(({value}) => {
      if (value < 0 && this.state.right){
        this.setState({right: false})
      }
      else if (value > 0 && !this.state.right){
        this.setState({right: true})
      }
    });
}
</code>```

And then just listen to the property:

```<code>renderHint(){
  return this.state.right > 0 ? <Text>Right</Text> : <Text>Left</Text>
}
</code>```

Body:
I'm pretty new to React Native and I'm facing a problem:

I understood the transformations that you can do with a PanResponder and then using the interpolate function.

Example:

let cardOpacity = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [0.9, 0, 0.9]})};

The problem I'm facing is a bit more tricky because I want to extract values from this interpolation and not any style:

I want that code to work basically:

_renderApplyOrDislikeHint() {
  let cardOpacity = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [0.9, 0, 0.9]})};
  let value = {opacity: this.state.pan.x.interpolate({inputRange: [-150, 0, 150], outputRange: [1, 0, 1]})};
  this.state.pan.x.addListener(({value}) => {
    this.x = value._value
    console.log('Value changed', this.x);
  });
  let dimensionStyle = {
    backgroundColor: 'white',
    width: this.props.cardWidth,
    height: this.props.cardHeight,
    position: 'absolute'
  };
  return (
    <Animated.View style={[dimensionStyle, cardOpacity]}>
      {this.renderHint()}
    </Animated.View>
  )
}

renderHint(){
  console.log('X in render hint', this.x)
  return this.x > 0 ? <Text>Yes</Text> : <Text>Nope</Text>
}

The problem is that animated value work great for styles but they do not force the re-rendering of the renderHint() function.
And it is a very bad idea to change state during the render process.

How can I achieve that?

Body:
Soooo, I found a solution

Basically in React, the views are listening to the state of the component: so to "re-render" we need to change the state.

Therefore I added a simple change in the pan responder:

onPanResponderGrant: (e, gestureState) => {
    this.state.pan.setOffset({x: this.state.pan.x._value, y: this.state.pan.y._value});
    this.state.pan.setValue({x: 0, y: 0});
    this.state.pan.x.addListener(({value}) => {
      if (value < 0 && this.state.right){
        this.setState({right: false})
      }
      else if (value > 0 && !this.state.right){
        this.setState({right: true})
      }
    });
}

And then just listen to the property:

renderHint(){
  return this.state.right > 0 ? <Text>Right</Text> : <Text>Left</Text>
}


问:
DefaultWebSessionManager not works on Chrome
Well, I have posted following question on Shiro's forum for 1 week but no response until now.

I am just trying to use Shiro with a simple Spring application. The security manager is defined as DefaultWebSecurityManager which set session manager as ServletContainerSessionManager by default and it works for me. However, after I changed the session manager to DefaultWebSessionManager which means I want to use Shiro's native session, it not works on Chrome. I dug out some following information:-

When using DefaultWebSessionManager, Shiro tries to get session id from request cookie. The logic SimpleCookie is looping all request cookies and return when a cookie's name is 'JSESSIONID'. However, in the requests come from Chrome, there are 2 cookies with name 'JSESSIONID'. The value of the first one is different with 'requestedSessionid' in request and the other one equals. That result in a new redirect to login page after authentication successfully. To make it simple, the process now is: access any address -> redirect to login page by Shiro -> submit principals and credentials -> authentication successfully and redirect to home page by Shiro -> a new request comes and found another session id which is not cached in Shiro, result in a InvalidSessionException in resolveSession method in DefaultSecurityManager -> redirect back to login
page.

When using ServletContainerSessionManager, since the session id is come from request.getSession(false), the session could be found after redirect.

My question is if this is a defect or anything configurations or codes can fix this problem? Note only Chrome fires this problem. I guess it's about Chrome's cache but can you explain more?

Below is the necessary sources for you to replicate:-

web.xml

```<code><listener>
  <listener-class>test.shiro.framework.WebSessionListener</listener-class>
</listener>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>

<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
  <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/controller/*</url-pattern>
</servlet-mapping>
</code>```

spring-servlet.xml:

```<code><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  <property name="securityManager" ref="securityManager" />
  <property name="loginUrl" value="/login.jsp"/>
  <property name="successUrl" value="/home.jsp"/>
  <property name="unauthorizedUrl" value="/unauthorized.jsp"/>

  <property name="filterChainDefinitions">
    <value>
      /** = authc
    </value>
  </property>
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

  <property name="realm" ref="myRealm" />
  <property name="sessionManager">
    <bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"></bean>
  </property>

</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

<bean id="myRealm" class="org.apache.shiro.realm.text.TextConfigurationRealm">
  <property name="userDefinitions">
    <value>
      huzj=12345678,authc
      guodg=12345678,operator
      sadd=12345678,guest
    </value>
  </property>
  <property name="roleDefinitions">
    <value>
      authc=*
      operator=book:*
      guest=book:view:*
    </value>
  </property>
</bean>
</code>```

Feb 18 UPDATE:
A further testing shows that the problem only occured when I tried to change from ServletContainerSessionManager to DefaultWebSessionManager. I guess chrome records a junk cookie in this situation by mistake.

After all I tried @paulochf's solution and it does work. I debugged again and believe you got the point. Many thanks!

答:
For those who configure Shiro via Spring, here's how to override the JSESSIONID as the default cookie name (to "JSESSID" in this case).</p>

```<code><bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    <property name="globalSessionTimeout" value="..." />
    <property name="sessionListeners">
        <util:list>
            <ref bean="..." />
        </util:list>
    </property>
    <property name="sessionIdCookie">
        <bean class="org.apache.shiro.web.servlet.SimpleCookie">
            <property name="name" value="JSESSID" />
        </bean>
    </property>
</bean>
</code>```

Body:
Well, I have posted following question on Shiro's forum for 1 week but no response until now.

I am just trying to use Shiro with a simple Spring application. The security manager is defined as DefaultWebSecurityManager which set session manager as ServletContainerSessionManager by default and it works for me. However, after I changed the session manager to DefaultWebSessionManager which means I want to use Shiro's native session, it not works on Chrome. I dug out some following information:-

When using DefaultWebSessionManager, Shiro tries to get session id from request cookie. The logic SimpleCookie is looping all request cookies and return when a cookie's name is 'JSESSIONID'. However, in the requests come from Chrome, there are 2 cookies with name 'JSESSIONID'. The value of the first one is different with 'requestedSessionid' in request and the other one equals. That result in a new redirect to login page after authentication successfully. To make it simple, the process now is: access any address -> redirect to login page by Shiro -> submit principals and credentials -> authentication successfully and redirect to home page by Shiro -> a new request comes and found another session id which is not cached in Shiro, result in a InvalidSessionException in resolveSession method in DefaultSecurityManager -> redirect back to login
page.

When using ServletContainerSessionManager, since the session id is come from request.getSession(false), the session could be found after redirect.

My question is if this is a defect or anything configurations or codes can fix this problem? Note only Chrome fires this problem. I guess it's about Chrome's cache but can you explain more?

Below is the necessary sources for you to replicate:-

web.xml

<listener>
  <listener-class>test.shiro.framework.WebSessionListener</listener-class>
</listener>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>/WEB-INF/spring-servlet.xml</param-value>
</context-param>

<filter>
  <filter-name>shiroFilter</filter-name>
  <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
  </init-param>
</filter>

<filter-mapping>
  <filter-name>shiroFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

<servlet>
  <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/controller/*</url-pattern>
</servlet-mapping>

spring-servlet.xml:

<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
  <property name="securityManager" ref="securityManager" />
  <property name="loginUrl" value="/login.jsp"/>
  <property name="successUrl" value="/home.jsp"/>
  <property name="unauthorizedUrl" value="/unauthorized.jsp"/>

  <property name="filterChainDefinitions">
    <value>
      /** = authc
    </value>
  </property>
</bean>

<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">

  <property name="realm" ref="myRealm" />
  <property name="sessionManager">
    <bean class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"></bean>
  </property>

</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

<bean id="myRealm" class="org.apache.shiro.realm.text.TextConfigurationRealm">
  <property name="userDefinitions">
    <value>
      huzj=12345678,authc
      guodg=12345678,operator
      sadd=12345678,guest
    </value>
  </property>
  <property name="roleDefinitions">
    <value>
      authc=*
      operator=book:*
      guest=book:view:*
    </value>
  </property>
</bean>

Feb 18 UPDATE:
A further testing shows that the problem only occured when I tried to change from ServletContainerSessionManager to DefaultWebSessionManager. I guess chrome records a junk cookie in this situation by mistake.

After all I tried @paulochf's solution and it does work. I debugged again and believe you got the point. Many thanks!

Body:
For those who configure Shiro via Spring, here's how to override the JSESSIONID as the default cookie name (to "JSESSID" in this case).

<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
    <property name="globalSessionTimeout" value="..." />
    <property name="sessionListeners">
        <util:list>
            <ref bean="..." />
        </util:list>
    </property>
    <property name="sessionIdCookie">
        <bean class="org.apache.shiro.web.servlet.SimpleCookie">
            <property name="name" value="JSESSID" />
        </bean>
    </property>
</bean>


答:
get_string is a function that takes no parameters:

```<code>string get_string(void);
</code>```

so

```<code>string s = get_string;
</code>```

must be

```<code>string s = get_string();
</code>```

Title: How can get_string error get avoided?

Body:
I'm doing the CS50 course, pset2 initials. The only error I get is a problem with get_string: it would have an 'incompatible pointer types initializing 'string' with an expression of type 'string (void)'. I really don't understand what I am doing wrong, because my code for get_string worked for the last problem set.. Here's my code:

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main(void)
{
    // ask user for input
    printf("What are your names?");
    string s = get_string;

    // print first letter from string & capitalize
    printf("%c", toupper(s[0]));

    //iterate over characters in current string + start loop
    for (int i = 0; i < strlen(s); i++)
    {
        //find space character
        if (s[i] == ' ')
        {
            // print character next to space & capitalize
            printf("%c", toupper(s[i++]));
        }
    // new rule
    printf("\n");
    }
}

Body:
get_string is a function that takes no parameters:

string get_string(void);

so

string s = get_string;

must be

string s = get_string();


问:
How do I get my ajax function to handle requests one by one?
I have a bunch of twitch channels with their names as ID and want to ascribe the correct status to the channel and keep it at "offline" if I don't get a result. It all works fine, except which channel is getting which status is pretty much random, most of the time the last one is the only one that's affected. How do I get .ajax to simply do one request at a time? (I already tried putting async: false)

$(document).ready(function() {
  var names = [];
  var status = 'Offline';
  var iconColor = "#B00";

  $('.channel').each(function(index) {
    names.push($(this).attr('id'));
  });

  $(".channel").each(function(index) {
    iconColor = "#B00";
    $(this).html('

Offline
');
    $(this).children("a").children(".nameChannel").text(names[index]);
    $.ajax({
      url: 'https://wind-bow.glitch.me/twitch-api/streams/' + names[index],
      dataType: 'jsonp',
      type: 'GET',
      async: false,
      jsonpCallback: 'JSON_CALLBACK',
      success: function(data) {
        if (data.stream !== null) {
          assignProps(names[index], data.stream.channel.status, '#0B0');
        }
      }
    });
  });
});

function assignProps(name, status, iconColor) {
  $('#' + name).children('.status').text(status);
  $('#' + name).children('.iconStatus').children('i').css('color', iconColor);
};
```

答:
I have removed async and jsonpCallback. The reason is, for async, requests will freeze browser for request time. jsonpCallback is maintained by jQuery, so there is no need to set it.

I moved names to global scope from onload handler, and added nameIndex to track for what name I will fetch stream data next.

Then, instead of calling ajax for each channel in the second $(".channel").each(function(index), I made function fetchStream that will call it for next name for names based on nameIndex and it will then call itself on complete handler of last ajax request, it means it will call itself either on error or success. You may want to handle error yourself to decrement nameIndex and call fetchStream will make a request for the same index again, but be careful to not pitfall into infinite loop if error will occur every time.

var names = [];
var nameIndex = 0;

$(document).ready(function() {
  var status = 'Offline';
  var iconColor = "#B00";

  $('.channel').each(function(index) {
    names.push($(this).attr('id'));
  });

  $(".channel").each(function(index) {
    iconColor = "#B00";
    $(this).html('

Offline
');
    $(this).children("a").children(".nameChannel").text(names[index]);
  });

  fetchStream();
});

function fetchStream(){
  if(nameIndex < names.length){
    var name = names[nameIndex];
    console.log('Fetching for ' + name);
    $.ajax({
      url: 'https://wind-bow.glitch.me/twitch-api/streams/' + name,
      dataType: 'jsonp',
      type: 'GET',
      success: function(data) {
        if (data.stream !== null) {
          assignProps(name, data.stream.channel.status, '#0B0');
        }
      },
      complete: function(){
        fetchStream();
      }
    });

    nameIndex++;
  } else {
    console.log('Finished');
  }
}

function assignProps(name, status, iconColor) {
  $('#' + name).children('.status').text(status);
  $('#' + name).children('.iconStatus').children('i').css('color', iconColor);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="channel" id="lirik"></div>
<div class="channel" id="yuuhi"></div>
<div class="channel" id="esl_overwatch"></div></code>```

Body:
I have removed async and jsonpCallback. The reason is, for async, requests will freeze browser for request time. jsonpCallback is maintained by jQuery, so there is no need to set it.

I moved names to global scope from onload handler, and added nameIndex to track for what name I will fetch stream data next.

Then, instead of calling ajax for each channel in the second $(".channel").each(function(index), I made function fetchStream that will call it for next name for names based on nameIndex and it will then call itself on complete handler of last ajax request, it means it will call itself either on error or success. You may want to handle error yourself to decrement nameIndex and call fetchStream will make a request for the same index again, but be careful to not pitfall into infinite loop if error will occur every time.

var names = [];
var nameIndex = 0;

$(document).ready(function() {
  var status = 'Offline';
  var iconColor = "#B00";

  $('.channel').each(function(index) {
    names.push($(this).attr('id'));
  });

  $(".channel").each(function(index) {
    iconColor = "#B00";
    $(this).html('<div class="iconStatus col-md-1"><i class="fa fa-television" aria-hidden="true"></i></div><a href="https://www.twitch.tv/' + names[index] + '"><div class="nameChannel col-md-3"></div></a><div class="status col-md-8">Offline</div>');
    $(this).children("a").children(".nameChannel").text(names[index]);
  });

  fetchStream();
});

function fetchStream(){
  if(nameIndex < names.length){
    var name = names[nameIndex];
    console.log('Fetching for ' + name);
    $.ajax({
      url: 'https://wind-bow.glitch.me/twitch-api/streams/' + name,
      dataType: 'jsonp',
      type: 'GET',
      success: function(data) {
        if (data.stream !== null) {
          assignProps(name, data.stream.channel.status, '#0B0');
        }
      },
      complete: function(){
        fetchStream();
      }
    });

    nameIndex++;
  } else {
    console.log('Finished');
  }
}

function assignProps(name, status, iconColor) {
  $('#' + name).children('.status').text(status);
  $('#' + name).children('.iconStatus').children('i').css('color', iconColor);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="channel" id="lirik"></div>
<div class="channel" id="yuuhi"></div>
<div class="channel" id="esl_overwatch"></div>


问:
Merging dev and live prestashop databases
I have extensive modifications to carry out on a prestashop 1.6 site.

I have created a local copy, and am tracking filesystem changes in git.

However a lot of changes in prestashop are stored in the database, specifically in my case:

Installing and configuring a new module

Uninstalling a module

Adding shop categories and changing the hierarchy

Changing module positions

and generally modifying what modules appear in what hooks.

During the dev process, the live site has received numerous new orders, customers, subscribers etc, so the databases are out of sync.

I have solved similar problems in other frameworks by dumping and importing specific tables in the db, or using the frameworks built in migrations functionality, but i cannot find any advise specifically for prestashop.

How is this handled?

Considering that the dev site has probably undergone more diverse changes than the live one, i wonder if it would be easier to copy the new orders etc over to the dev site then overwrite the whole thing?

答:
I don't think that it is possible to achieve this in PrestaShop. You must have immense knowledge of PrestaShop DB (i.e. have knowledge of each and every table and columns in it) to merge the databases.

It is never recommended to do that either.

I suggest you do the syncing manually as it is a very risky task and you might lose all the data in your live store, which will be even more painful.


问:
create associative array from collection in laravel for checking purposes
I am having an hard time trying to create an associative array from a collection in Laravel. The array should then be used for case checking.

I get my collection like this:

```<code>$collected_items = $user->collected_items()->where('model_id', '=', $model_id)->get();
</code>```

I need to extract only some relevant data from this collection like 'color_id'

I need to check the color_id because I should run different code if the color_id = 0, 1 or 2

Since I don't want to do a DB query for every case I thought I'd better eager load the data and then put it in an associative array;

However for the life of me I can't create this array
I tried:

```<code>$array_of_colors = []

    foreach ($collected_items as $i) {

                    if ($i['color_id'] == 0) {

                        $array_of_colors += ['black' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 1) {

                        $array_of_colors += ['colored' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 2) {

                        $array_of_colors += ['white' => $i->model_color_id];
                    }

                }
</code>```

Then I would use the $array_of_colors to check if I have a case of black then do something, is white something else etc etc.

答:
Instead of doing it that way I highly recommend using the Collection functions available in Laravel. In particular I think filter() will work well for you.

https://laravel.com/docs/5.4/collections#method-filter

Something like this:

```<code>$black_items = $collected_items->filter(function ($value, $key) {
  return $value->model_color_id == 1;
});
</code>```

Body:
I am having an hard time trying to create an associative array from a collection in Laravel. The array should then be used for case checking.

I get my collection like this:

$collected_items = $user->collected_items()->where('model_id', '=', $model_id)->get();

I need to extract only some relevant data from this collection like 'color_id'

I need to check the color_id because I should run different code if the color_id = 0, 1 or 2

Since I don't want to do a DB query for every case I thought I'd better eager load the data and then put it in an associative array;

However for the life of me I can't create this array
I tried:

$array_of_colors = []

    foreach ($collected_items as $i) {

                    if ($i['color_id'] == 0) {

                        $array_of_colors += ['black' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 1) {

                        $array_of_colors += ['colored' => $i->model_color_id];
                    }
                    if ($i['color_id'] == 2) {

                        $array_of_colors += ['white' => $i->model_color_id];
                    }

                }

Then I would use the $array_of_colors to check if I have a case of black then do something, is white something else etc etc.

Body:
Instead of doing it that way I highly recommend using the Collection functions available in Laravel. In particular I think filter() will work well for you.

https://laravel.com/docs/5.4/collections#method-filter

Something like this:

$black_items = $collected_items->filter(function ($value, $key) {
  return $value->model_color_id == 1;
});


问:
FTP in Flash/Flex - sandbox error
I'm trying to embed an FTP client in to a web page using Flash. I'm using FlexFTP, which appears to be designed for AIR. I've modified it to use a FileReference so it can run in the Flash plugin. I only need to connect to one server, and I have an appropriate socket policy server running on that server.

I can connect and log in just fine, but when I try to upload a file, I get a security sandbock violation (error 2048) saying "cannot load data from 127.0.0.1:38422" thrown from ceatePassiveSocket().

I'm beginning to think that it is not possible to do FTP from Flash because of the need to open a port locally. Is there a way around it, or can I get authoritative confirmation that it is not possible?

答: You can do it in flash (browser), but you need to create an socket policy/crossdomain.xml, which allows flash to connect on the port , even if its local( testing it inside the browser).The file spec is located here http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html</p>

Title: FTP in Flash/Flex - sandbox error


问:
Concise recursive invocation of function with many parameters, changing only one parameter
I have an R function, fun, with many parameters. I need to run fun several times, varying the parameters y and z but keeping the others the same. Rather than wrap every call of fun in a loop, I made y and z both NA by default; the function checks if is.na(y) or is.na(z) and, if so, calls itself recursively with each desired value of y and z in turn, like this:

```<code>fun <- function(a=defaultA, b=defaultB, ..., y = NA, z=NA) {
  if (is.na(y)) {
    for (yValue in 1:maxY) {
      fun(a, b, ..., y = yvalue, z = z)
    }
    return()
  }
  if (is.na(z)) {
    for (zValue in 1:maxZ) {
      fun(a, b, ..., y, z=zValue)
    }
    return()
  }
  stopifnot(!is.na(y) && !is.na(z))
  # Part of fun that does actual work follows.
  ...
}
</code>```

The recursive fun calls are actually inconveniently long, a few hundred characters each, because they need to repeat every parameter given to fun. Is there any shortcut by which I can call fun recursively with all parameters but one preserved, or is there another, better way to accomplish what I'm trying to do?

For the curious: my actual fun produces a graph with data sets and options specified in the parameters, and y and z are Booleans that determine whether to graph specific outliers. This lets me produce with- and without-outliers versions of the graphs without duplicating the function calls or wrapping them in for-loops as for (y in c(TRUE, FALSE)) {for (z in c(TRUE, FALSE)) {fun(...)}}.

答:
match.call and sys.call are your friends here. See Why is match call useful?

In your case, here's a rewritten version of the first loop:

```<code>fun <- function(a = defaultA, b = defaultB, ..., y = NA, z = NA) {
  if (is.na(y)) {
    mc <- match.call(expand.dots = FALSE)
    for (yvalue in 1:maxY) {
      mc[['y']] <- yvalue
      eval(mc)
    }
  }
  ...
</code>```

Body:
I have an R function, fun, with many parameters. I need to run fun several times, varying the parameters y and z but keeping the others the same. Rather than wrap every call of fun in a loop, I made y and z both NA by default; the function checks if is.na(y) or is.na(z) and, if so, calls itself recursively with each desired value of y and z in turn, like this:

fun <- function(a=defaultA, b=defaultB, ..., y = NA, z=NA) {
  if (is.na(y)) {
    for (yValue in 1:maxY) {
      fun(a, b, ..., y = yvalue, z = z)
    }
    return()
  }
  if (is.na(z)) {
    for (zValue in 1:maxZ) {
      fun(a, b, ..., y, z=zValue)
    }
    return()
  }
  stopifnot(!is.na(y) && !is.na(z))
  # Part of fun that does actual work follows.
  ...
}

The recursive fun calls are actually inconveniently long, a few hundred characters each, because they need to repeat every parameter given to fun. Is there any shortcut by which I can call fun recursively with all parameters but one preserved, or is there another, better way to accomplish what I'm trying to do?

For the curious: my actual fun produces a graph with data sets and options specified in the parameters, and y and z are Booleans that determine whether to graph specific outliers. This lets me produce with- and without-outliers versions of the graphs without duplicating the function calls or wrapping them in for-loops as for (y in c(TRUE, FALSE)) {for (z in c(TRUE, FALSE)) {fun(...)}}.

Body:
match.call and sys.call are your friends here. See Why is match call useful?

In your case, here's a rewritten version of the first loop:

fun <- function(a = defaultA, b = defaultB, ..., y = NA, z = NA) {
  if (is.na(y)) {
    mc <- match.call(expand.dots = FALSE)
    for (yvalue in 1:maxY) {
      mc[['y']] <- yvalue
      eval(mc)
    }
  }
  ...


问:
EF Migration object already exists error
I am working on an ASP.NET MVC project with Entity Framework with code first from database. I get the models for each table in the database. I made some changes in the models, enabled migrations and when I initial the migration I get an error:

There is already an object named 'TableName' in the database."

I tried with update-database -force but didn't help. The initial migration creates the tables that already exist!

How to make the initial migration apply the changes on the models and not create the tables from beginning?

And what is the best practice to sync changes between database and models in this case?

答:
Amr Alaa solution works, but the database didn't migrate to the latest model.

Here's how it worked (using automatic migration) :

Delete Migrations folder

Execute enable-migrations

Set this two properties to true in the newly created Configuration.cs

```<code>public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}
</code>```

Execute Update-Database -Force

Your database will be updated to latest scheme and ready.

hope this helps.

Body:
Amr Alaa solution works, but the database didn't migrate to the latest model.

Here's how it worked (using automatic migration) :

Delete Migrations folder

Execute enable-migrations

Set this two properties to true in the newly created Configuration.cs

public Configuration()
{
    AutomaticMigrationsEnabled = true;
    AutomaticMigrationDataLossAllowed = true;
}

Execute Update-Database -Force

Your database will be updated to latest scheme and ready.

hope this helps.


问:
Dplyr tally/count by multiple filters
I am trying to create a summarise/filter dplyr pipeline which will be equivalent to the below:

```<code>iris %>%
mutate(Sepal.Area = Sepal.Length * Sepal.Width,
       Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
      filter(Sepal.Area < 17) %>%
        tally() %>%
      filter(Sepal.Area > 17 & Sepal.Area < 22) %>%
        tally() %>%
      filter(Sepal.Area > 22) %>%
        tally()
</code>```

Or another potential approach:

```<code>iris %>%
  mutate(Sepal.Area = Sepal.Length * Sepal.Width,
         Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
    summarise(n(Sepal.Area < 17),
              n(Sepal.Area > 17 & Sepal.Area < 22),
              n(Sepal.Area > 22))
</code>```

What is the easiest way to get counts by multiple filters on a grouping?
Or simply run each one and join them later?

答:
You have to create groups for different Sepal.Area ranges you want and then group and count by those. Try this:

```<code>iris %>%
mutate(Sepal.Area = Sepal.Length * Sepal.Width,
       Petal.Area = Petal.Length * Petal.Width) %>% mutate(Sepal.Area.Groups = ifelse(Sepal.Area < 17, 'Sep_less_17', ifelse(Sepal.Area > 17 & Sepal.Area < 22, 'Sep_bet_1722', ifelse(Sepal.Area > 22, 'Sep_gre_22', 'other')))) %>%
  group_by(Sepal.Area.Groups) %>%
        tally()

# A tibble: 4 x 2
  Sepal.Area.Groups     n
              <chr> <int>
1      Sep_bet_1722    74
2        Sep_gre_22    13
3       Sep_less_17    61
4             other     2
</code>```

Using dplyr, if you apply a filter after doing a tally, you are basically filtering on the tallied table.

Title: Dplyr tally/count by multiple filters

Body:
I am trying to create a summarise/filter dplyr pipeline which will be equivalent to the below:

iris %>%
mutate(Sepal.Area = Sepal.Length * Sepal.Width,
       Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
      filter(Sepal.Area < 17) %>%
        tally() %>%
      filter(Sepal.Area > 17 & Sepal.Area < 22) %>%
        tally() %>%
      filter(Sepal.Area > 22) %>%
        tally()

Or another potential approach:

iris %>%
  mutate(Sepal.Area = Sepal.Length * Sepal.Width,
         Petal.Area = Petal.Length * Petal.Width) %>%
  group_by(Species) %>%
    summarise(n(Sepal.Area < 17),
              n(Sepal.Area > 17 & Sepal.Area < 22),
              n(Sepal.Area > 22))

What is the easiest way to get counts by multiple filters on a grouping?
Or simply run each one and join them later?

Body:
You have to create groups for different Sepal.Area ranges you want and then group and count by those. Try this:

iris %>%
mutate(Sepal.Area = Sepal.Length * Sepal.Width,
       Petal.Area = Petal.Length * Petal.Width) %>% mutate(Sepal.Area.Groups = ifelse(Sepal.Area < 17, 'Sep_less_17', ifelse(Sepal.Area > 17 & Sepal.Area < 22, 'Sep_bet_1722', ifelse(Sepal.Area > 22, 'Sep_gre_22', 'other')))) %>%
  group_by(Sepal.Area.Groups) %>%
        tally()

# A tibble: 4 x 2
  Sepal.Area.Groups     n
              <chr> <int>
1      Sep_bet_1722    74
2        Sep_gre_22    13
3       Sep_less_17    61
4             other     2

Using dplyr, if you apply a filter after doing a tally, you are basically filtering on the tallied table.


问:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined Error on text field

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

```<code>at Object.<anonymous> (<anonymous>:16:76)
at Function.each (jquery.js?v=1.4.4:34)
at Object.success (<anonymous>:10:13)
at Function.handleSuccess (jquery.js?v=1.4.4:143)
at XMLHttpRequest.w.onreadystatechange (jquery.js?v=1.4.4:142)
</code>```

I keep getting the above error when trying to use the toLowerCase() function on the description in the commented out if code for the following code:

```<code>(function($) {
    $.ajax({
      url: "/node.json",
      data: {'type': "resource_page", 'page': 3},
      dataType: "json",
      type: "GET",
      success: function (response) {

          $.each(response.list, function(k, resource) {

            var title = resource.title;
            var description = resource.body.value;

              if(title.toLowerCase().indexOf("biology") >= 0) { console.log(description.toLowerCase().indexOf("biology")); };
              //if(title.toLowerCase().indexOf("biology") >= 0 || description.toLowerCase().indexOf("biology") >=0) { console.log(title); };

          });
      }
    });
}(jQuery));
</code>```

When I consol.log() it everything works fine (I get the result of 226 saying that "biology" does show up in the string). I can even put:

```<code>if(title.toLowerCase().indexOf("biology") >= 0) { console.log(description.toLowerCase()); };
</code>```

and still get the correct console.log of
this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.

I am not sure why I get the error for description and not for the title. I have tried using toLowerCase() on the description before using it in the if but that did not work. I can only use it when console.logging it. Can anyone help me please. Thank you very very much!

答:
The reason that you'are getting the error is when you have either "title" or description equal undefined. The following example throws the very same exception error:

var title;
var description = '
this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.
';

console.log(description.toLowerCase().indexOf("biology"))
if(title.toLowerCase().indexOf("biology") >= 0 || description.toLowerCase().indexOf("biology") >=0) {

console.log(title);

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

<p>However, I would recommend you to check whether they are not null or undefined at your if statement like following:</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>var title;
var description = '<p>this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.</p>';

console.log(description.toLowerCase().indexOf("biology"))
if((title && title.toLowerCase().indexOf("biology") >= 0) || (description && description.toLowerCase().indexOf("biology") >=0)) {

console.log(title);
console.log('It works fine');
};</code>```

You see that it works fine.

Body:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

at Object.<anonymous> (<anonymous>:16:76)
at Function.each (jquery.js?v=1.4.4:34)
at Object.success (<anonymous>:10:13)
at Function.handleSuccess (jquery.js?v=1.4.4:143)
at XMLHttpRequest.w.onreadystatechange (jquery.js?v=1.4.4:142)

I keep getting the above error when trying to use the toLowerCase() function on the description in the commented out if code for the following code:

(function($) {
    $.ajax({
      url: "/node.json",
      data: {'type': "resource_page", 'page': 3},
      dataType: "json",
      type: "GET",
      success: function (response) {

          $.each(response.list, function(k, resource) {

            var title = resource.title;
            var description = resource.body.value;

              if(title.toLowerCase().indexOf("biology") >= 0) { console.log(description.toLowerCase().indexOf("biology")); };
              //if(title.toLowerCase().indexOf("biology") >= 0 || description.toLowerCase().indexOf("biology") >=0) { console.log(title); };

          });
      }
    });
}(jQuery));

When I consol.log() it everything works fine (I get the result of 226 saying that "biology" does show up in the string). I can even put:

if(title.toLowerCase().indexOf("biology") >= 0) { console.log(description.toLowerCase()); };

and still get the correct console.log of
this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.

I am not sure why I get the error for description and not for the title. I have tried using toLowerCase() on the description before using it in the if but that did not work. I can only use it when console.logging it. Can anyone help me please. Thank you very very much!

Body:
The reason that you'are getting the error is when you have either "title" or description equal undefined. The following example throws the very same exception error:

var title;
var description = '<p>this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.</p>';

console.log(description.toLowerCase().indexOf("biology"))
if(title.toLowerCase().indexOf("biology") >= 0 || description.toLowerCase().indexOf("biology") >=0) {

console.log(title);

};

However, I would recommend you to check whether they are not null or undefined at your if statement like following:

var title;
var description = '<p>this video database is designed to teach laboratory fundamentals through simple, easy to understand video demonstrations. this collection demonstrates how to execute basic techniques commonly used in cellular and molecular biology. to enhance your understanding of the methods each video is paired with additional video resources to show practical applications of the techniques and other complementary skills.</p>';

console.log(description.toLowerCase().indexOf("biology"))
if((title && title.toLowerCase().indexOf("biology") >= 0) || (description && description.toLowerCase().indexOf("biology") >=0)) {

console.log(title);
console.log('It works fine');
};

You see that it works fine.


问:
JavaScript and HTML Assignment .getElementById and .innerHTML
The assignment has me follow step by step instructions to execute code using an HTML button, then getElementById and innerHTML JavaScript. I got the button part to work, but I cannot get the JavaScript to work.

Here's the body of my code:

```<code><body>
    <script type="text/javascript">
        var x= "JavaScript is fun. ";

        document.writeln(x);

        document.writeln(x + x + x + x + x);

        function statement(x)
        {
            return document.writeln(x);
        }

        document.getElementById("change").innerHTML = x+x+x+x+x;
    </script>

    <button onclick="statement(x)">Click me!</button>
    <p id="change">This will change</p>

</body>
</code>```

Here are the instructions I was given:

So if we wanted to print out that JavaScript is fun below the button, we could instead of having it write to the document itself, we could have it replace some text within a certain element (HTML tag) within the document.

So underneath the button, let’s put a paragraph tag and have it read “this will change”

We are going to change the innerHTML property of this tag. The innerHTML of a tag is the stuff that is in between the opening and closing tags, which in this case is the text “this will change”

First we need to, within JavaScript, identify the tag that we want to change. We can do this by using the getElementById() method. This method simply locates an element with a specified id (similar to intrapage links). So place an id attribute in the opening paragraph tag (i.e. ) and then place the same id in the () (i.e. getElementById(“change”).

Once again I said we will change the innerHTML property of this element, so we will attach the innerHTML property to it by saying getElementById(“change”).innerHTML

Not all we need to do is say which object this element is associated with. It is within the document, so we can use the document object and specify that by saying document.getElementById(“change”).innerHTML

Now that we have identified what we want to change, let’s change it. We do that by setting what we want to change to be equal to the new value, so for me it is: document.getElementById(“change”).innerHTML = x+x+x+x+x;

答:
Try this:

var x = "JavaScript is fun. ";

function statement(x) {
  document.getElementById("change").innerHTML = x + x + x + x + x;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <button onclick="statement(x)">Click me!</button>
  <p id="change">This will change</p>

</body></code>```

Body:
The assignment has me follow step by step instructions to execute code using an HTML button, then getElementById and innerHTML JavaScript. I got the button part to work, but I cannot get the JavaScript to work.

Here's the body of my code:

    <button onclick="statement(x)">Click me!</button>

This will change

Here are the instructions I was given:

So if we wanted to print out that JavaScript is fun below the button, we could instead of having it write to the document itself, we could have it replace some text within a certain element (HTML tag) within the document.

So underneath the button, let’s put a paragraph tag and have it read “this will change”

We are going to change the innerHTML property of this tag. The innerHTML of a tag is the stuff that is in between the opening and closing tags, which in this case is the text “this will change”

First we need to, within JavaScript, identify the tag that we want to change. We can do this by using the getElementById() method. This method simply locates an element with a specified id (similar to intrapage links). So place an id attribute in the opening paragraph tag (i.e. ) and then place the same id in the () (i.e. getElementById(“change”).

Once again I said we will change the innerHTML property of this element, so we will attach the innerHTML property to it by saying getElementById(“change”).innerHTML

Not all we need to do is say which object this element is associated with. It is within the document, so we can use the document object and specify that by saying document.getElementById(“change”).innerHTML

Now that we have identified what we want to change, let’s change it. We do that by setting what we want to change to be equal to the new value, so for me it is: document.getElementById(“change”).innerHTML = x+x+x+x+x;

Body:
Try this:

var x = "JavaScript is fun. ";

function statement(x) {
  document.getElementById("change").innerHTML = x + x + x + x + x;
}

<body>

  <button onclick="statement(x)">Click me!</button>
  <p id="change">This will change</p>

</body>


问:
How to retrieve user's birthday data via Facebook Graph API 2.8?
I wonder if it's possible to obtain user's birthday via Facebook Graph API 2.8. I am using Graph API Explorer and it requests me to put {user-id}. Can I retrieve the birthday information only knowing the user's name and surname? How should I specify the query? For example, GET/v2.8/"NameSurname"

All my attepts to write a request are finishing with this error:

```<code>{
  "error": {
    "message": "(#803) Some of the aliases you requested do not exist: \"NameSurname\"",
    "type": "OAuthException",
    "code": 803,
    "fbtrace_id": "FRE/aemzTRL"
  }
</code>```

}

UPDATE:

I was able to only retrieve the data for myself using something like me?fields=name,email,gender. But is it possible to get the same data for another person knowing his/her name and surname?

答:
You can only get data of users who authorized your App, by using their Access Token with /me?fields=name,email,gender,birthday

You need to authorize them with the email and user_birthday permissions, btw.

Body:
I wonder if it's possible to obtain user's birthday via Facebook Graph API 2.8. I am using Graph API Explorer and it requests me to put {user-id}. Can I retrieve the birthday information only knowing the user's name and surname? How should I specify the query? For example, GET/v2.8/"NameSurname"

All my attepts to write a request are finishing with this error:

{
  "error": {
    "message": "(#803) Some of the aliases you requested do not exist: \"NameSurname\"",
    "type": "OAuthException",
    "code": 803,
    "fbtrace_id": "FRE/aemzTRL"
  }

}

UPDATE:

I was able to only retrieve the data for myself using something like me?fields=name,email,gender. But is it possible to get the same data for another person knowing his/her name and surname?


问:
List sorting - two lists into one
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

```<code>names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])
</code>```

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

答:
Alright fine. If you don't want to merge the lists in ANY way then you need to write a sorting algorithm manually that returns a sequence of moves you can apply to both lists to get them into the same order. You can simplify this if you only have unique elements in your lists by sorting one list then see where each element has moved to and apply the same changes to the other list as well.

More sane answer

You have two lists which have a dependency on each other, namely the position of elements in the list.

You need to decide by what you want to sort them, by name or by wage?

You can zip those two lists easily with loops

```<code>i = 0
merged = []
while i < len(wages):
  merged.append((wages[i], names[i]))
</code>```

And then use sort with key = lambda x: x[0] to sort by wages and key = lambda x: x[1] to sort by names.

Title: List sorting - two lists into one

Body:
I have to make two list. One with names (str) and second one with wage (int). And then, i have to sort the wages with the names. The problem is that, always when I do this, only wages are sorted.

names = ["Asia","Łukasz","Aneta","Ola","Mikołaj"]
wages = [15000,1500,200,14500,2600]

print("Here(should) be sorted list")
wages.sort()
for i in range (len(wages)) :
    print(wages[i],names[i])

To be clear, I want to set on hold these two lists into one and sort both of them. With the simple method as it can be. Without functions, sets, zips etc. Just with loops.

Body:
Alright fine. If you don't want to merge the lists in ANY way then you need to write a sorting algorithm manually that returns a sequence of moves you can apply to both lists to get them into the same order. You can simplify this if you only have unique elements in your lists by sorting one list then see where each element has moved to and apply the same changes to the other list as well.

More sane answer

You have two lists which have a dependency on each other, namely the position of elements in the list.

You need to decide by what you want to sort them, by name or by wage?

You can zip those two lists easily with loops

i = 0
merged = []
while i < len(wages):
  merged.append((wages[i], names[i]))

And then use sort with key = lambda x: x[0] to sort by wages and key = lambda x: x[1] to sort by names.


问:
MySQL query aggregate MAX and subquery
Is there a way to get value from a subquery in where inside select?

stop_link Table

```<code>id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1
</code>```

Result that I want (assume domain_id = 2)

```<code>duid    | domain_id
3       | 2
</code>```

Query (not working):

```<code>INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
</code>```

Query working but I wish to avoid the Set Variable:

```<code>SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;
</code>```

答:
No need of max():

```<code>SELECT
  IFNULL(sl.duid, 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
ORDER by sl.id DESC
LIMIT 1
</code>```

Title: MySQL query aggregate MAX and subquery

Body:
Is there a way to get value from a subquery in where inside select?

stop_link Table

id | duid | domain_id
1  | 1    | 1
2  | 2    | 1
3  | 1    | 2
4  | 2    | 2
5  | 3    | 1

Result that I want (assume domain_id = 2)

duid    | domain_id
3       | 2

Query (not working):

INSERT INTO stop_link (
              duid,

              domain_id)
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)

Query working but I wish to avoid the Set Variable:

SET @domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1);
SELECT
  IFNULL(MAX(sl.duid), 0) + 1 AS duid
  , @domain_id
FROM
  stop_link sl
WHERE sl.domain_id = @domain_id;

Body:
No need of max():

SELECT
  IFNULL(sl.duid, 0) + 1 AS duid,
  sl.domain_id
FROM
  stop_link sl
WHERE sl.domain_id = (SELECT sd.id FROM stop_domain sd LIMIT 1)
ORDER by sl.id DESC
LIMIT 1