问:
Spring CSRF Mutltipart File Upload
I followed this guide:

http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/reference/htmlsingle/#csrf-multipartfilter?

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart

to setup a file upload on my spring mvc project but I'm getting this error:

```<code>Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
</code>```

My web.xml (full)

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
        <location>/tmp</location>
        <max-file-size>1000000</max-file-size>
        <max-request-size>1000000</max-request-size>
        <file-size-threshold>10000</file-size-threshold>
    </multipart-config>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/appServlet/spring-security.xml,
            /WEB-INF/spring/appServlet/spring-datasource.xml
        </param-value>
    </context-param>

    <!-- Spring Security  Filter -->
    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>
</code>```

Spring servlet content (full)

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    </beans:bean>

    <context:component-scan base-package="com.at.ccts.controller" />

 </beans:beans>
</code>```

jsp

```<code>        <h1>Please upload a file</h1>
    <form method="post" action="${pageContext.request.contextPath}/create/form" enctype="multipart/form-data">
        <input type="text" name="name"/>
        <input type="file" name="file"/>
        <input type="submit"/>
    </form>
</code>```

controller

```<code>@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name,
    @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // store the bytes somewhere
       return "redirect:uploadSuccess";
   } else {
       return "redirect:uploadFailure";
   }
}
</code>```

Anyone has any ideas as to why it still asking for token?

答:
Spring Security by default now requires CSRF tokens on all "modifying" requests (POST, DELETE, etc.). To make dealing with CSRF easier, you can use the Spring taglibs (for JSP) or the Spring Security dialect (for Thymeleaf). For JSP, you'd simply write your form as

```<code><form:form ...>
</code>```

and the taglib will insert an <input type="hidden"> with the CSRF token for you.

Title: Spring CSRF Mutltipart File Upload

Body:
I followed this guide:

http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/reference/htmlsingle/#csrf-multipartfilter?

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-multipart

to setup a file upload on my spring mvc project but I'm getting this error:

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

My web.xml (full)

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
        <location>/tmp</location>
        <max-file-size>1000000</max-file-size>
        <max-request-size>1000000</max-request-size>
        <file-size-threshold>10000</file-size-threshold>
    </multipart-config>
    </servlet>

    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

   <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring/appServlet/spring-security.xml,
            /WEB-INF/spring/appServlet/spring-datasource.xml
        </param-value>
    </context-param>

    <filter>
        <filter-name>MultipartFilter</filter-name>
        <filter-class>org.springframework.web.multipart.support.MultipartFilter</filter-class>
    </filter>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>MultipartFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

Spring servlet content (full)

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <annotation-driven />

    <resources mapping="/resources/**" location="/resources/" />

    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
    </beans:bean>

    <context:component-scan base-package="com.at.ccts.controller" />

 </beans:beans>

jsp

Please upload a file

    <form method="post" action="${pageContext.request.contextPath}/create/form" enctype="multipart/form-data">
        <input type="text" name="name"/>
        <input type="file" name="file"/>
        <input type="submit"/>
    </form>

controller

@RequestMapping(value = "/form", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("name") String name,
    @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            byte[] bytes = file.getBytes();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // store the bytes somewhere
       return "redirect:uploadSuccess";
   } else {
       return "redirect:uploadFailure";
   }
}

Anyone has any ideas as to why it still asking for token?

Body:
Spring Security by default now requires CSRF tokens on all "modifying" requests (POST, DELETE, etc.). To make dealing with CSRF easier, you can use the Spring taglibs (for JSP) or the Spring Security dialect (for Thymeleaf). For JSP, you'd simply write your form as

<form:form ...>

and the taglib will insert an <input type="hidden"> with the CSRF token for you.


来源: stackexchange

问:
How to add a BearerToken to React API Requests?
I am a beginner to React. I'm using React to make API requests like so:

```<code>class CatsApi {
  static createCat(cat) {
    const request = new Request('http://localhost:4300/api/v1/cats', {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify(cat)
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }
</code>```

Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js

How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?

答:
You can use the Authorization header like:

```<code>{ 'Authorization': `Bearer ${authToken}` }
</code>```

Using fetch you could try with something like:

```<code>fetch('http://localhost:4300/api/v1/cats', {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${token}`
        'Accept'       : 'application/json',
        'Content-Type' : 'application/json',
    },
    body: JSON.stringify({
        cat : cat_value,
    })
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()
</code>```

Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner to React. I'm using React to make API requests like so:

class CatsApi {
  static createCat(cat) {
    const request = new Request('http://localhost:4300/api/v1/cats', {
      method: 'POST',
      headers: new Headers({
        'Content-Type': 'application/json'
      }),
      body: JSON.stringify(cat)
    });

    return fetch(request).then(response => {
      return response.json();
    }).catch(error => {
      return error;
    });
  }

Meanwhile, I have authentication to my API via react-devise:
https://github.com/timscott/react-devise
Which has a method getBearerToken like so: https://github.com/timscott/react-devise/blob/master/src/actions/authTokenStore.js

How do I use getBearerToken to pass the API the token so API requests are authenticated with the token?

Body:
You can use the Authorization header like:

{ 'Authorization': `Bearer ${authToken}` }

Using fetch you could try with something like:

fetch('http://localhost:4300/api/v1/cats', {
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${token}`
        'Accept'       : 'application/json',
        'Content-Type' : 'application/json',
    },
    body: JSON.stringify({
        cat : cat_value,
    })
})
.then((response) => response.json())
.then((responseData) => { console.log(responseData) })
.catch((error) => { console.log(error) })
.done()

Also, it'd be great to see what's the Rails output in the console when you make a request, or the browser console.

ContentLicense: CC BY-SA 3.0


问:
Struggling to store token for AdSense API
I've successfully managed to connect to the AdSense API and run a report. However, it requires a log in each time I run it, so it won't run as a cron job.

I've found a few other questions related to this. Some advise a service account, while others point out that a service account does not work with AdSense. The proposed solution is to store a token on my server, but I've been struggling to get that to work. Here is my code so far (which works, but requires manual log in):

```<code>$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApplicationName('My Application name');
$client->setClientId(' MY ID ');
$client->setClientSecret(' MY SECRET ');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(' MY KEY '); // API key

$accountId = " MY ACCOUNT " ;
$adClientId = " MY CLIENT " ;

// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

$startDate = '2015-11-01';
$endDate = 'today';
$optParams = array(
  'metric' => array(
    'EARNINGS'),
  'dimension' => array('DATE'),
  'sort' => '+DATE',
  'filter' => array(
    'CUSTOM_CHANNEL_NAME==Mega Seating Plan'
  )
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
    $endDate, $optParams);
if (isset($report) && isset($report['rows'])) {

  // Get results.
  foreach($report['rows'] as $row) {

    $date = $row[0] ;
    $earnings[$date] = $row[1] ;

  }
} else {
  print "No rows returned.\n";
}
</code>```

Can anybody give me any pointers about how I can incorporate token storage into the above code, please?

答:
Thank you to @jkns.co for the previous answer here which helped me to get it working.

Here's my final code:

```<code>$scriptUri = "I HAD TO PUT MY ABSOLUTE URL HERE, OTHERWISE THE CRON JOB WOULD LOOK IN THE WRONG PLACE" ;

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");  // This line had to be added to force the approval prompt and request a new token
$client->setApplicationName('My Application name');
$client->setClientId('BLAH');
$client->setClientSecret('BLAH');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('BLAH'); // API key

$accountId = "BLAH" ;
$adClientId = "BLAH" ;

// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();

    // If it successfully authenticates, I request the refresh token
    $refreshToken = $client->getRefreshToken();

    storeRefreshToken($refreshToken) ;  // This function stores the token in MySQL
}

else {      // Otherwise it loads the refresh token from MySQL

    $refreshToken = getRefreshToken() ;

    $client->refreshToken($refreshToken);
    $_SESSION['token'] = $client->getAccessToken();

}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);

}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}
</code>```

Body:
I've successfully managed to connect to the AdSense API and run a report. However, it requires a log in each time I run it, so it won't run as a cron job.

I've found a few other questions related to this. Some advise a service account, while others point out that a service account does not work with AdSense. The proposed solution is to store a token on my server, but I've been struggling to get that to work. Here is my code so far (which works, but requires manual log in):

$scriptUri = "http://".$_SERVER["HTTP_HOST"].$_SERVER['PHP_SELF'];

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApplicationName('My Application name');
$client->setClientId(' MY ID ');
$client->setClientSecret(' MY SECRET ');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey(' MY KEY '); // API key

$accountId = " MY ACCOUNT " ;
$adClientId = " MY CLIENT " ;

// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();
}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);
}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}

$startDate = '2015-11-01';
$endDate = 'today';
$optParams = array(
  'metric' => array(
    'EARNINGS'),
  'dimension' => array('DATE'),
  'sort' => '+DATE',
  'filter' => array(
    'CUSTOM_CHANNEL_NAME==Mega Seating Plan'
  )
);
// Run report.
$report = $service->accounts_reports->generate($accountId, $startDate,
    $endDate, $optParams);
if (isset($report) && isset($report['rows'])) {

  // Get results.
  foreach($report['rows'] as $row) {

    $date = $row[0] ;
    $earnings[$date] = $row[1] ;

  }
} else {
  print "No rows returned.\n";
}

Can anybody give me any pointers about how I can incorporate token storage into the above code, please?

Body:
Thank you to @jkns.co for the previous answer here which helped me to get it working.

Here's my final code:

$scriptUri = "I HAD TO PUT MY ABSOLUTE URL HERE, OTHERWISE THE CRON JOB WOULD LOOK IN THE WRONG PLACE" ;

$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
$client->setApprovalPrompt ("force");  // This line had to be added to force the approval prompt and request a new token
$client->setApplicationName('My Application name');
$client->setClientId('BLAH');
$client->setClientSecret('BLAH');
$client->setRedirectUri($scriptUri);
$client->setDeveloperKey('BLAH'); // API key

$accountId = "BLAH" ;
$adClientId = "BLAH" ;

// $service implements the client interface, has to be set before auth call
$service = new Google_Service_AdSense($client);

if (isset($_GET['logout'])) { // logout: destroy token
    unset($_SESSION['token']);
    die('Logged out.');
}

if (isset($_GET['code'])) { // we received the positive auth callback, get the token and store it in session
    $client->authenticate($_GET['code']);
    $_SESSION['token'] = $client->getAccessToken();

    // If it successfully authenticates, I request the refresh token
    $refreshToken = $client->getRefreshToken();

    storeRefreshToken($refreshToken) ;  // This function stores the token in MySQL
}

else {      // Otherwise it loads the refresh token from MySQL

    $refreshToken = getRefreshToken() ;

    $client->refreshToken($refreshToken);
    $_SESSION['token'] = $client->getAccessToken();

}

if (isset($_SESSION['token'])) { // extract token from session and configure client
    $token = $_SESSION['token'];
    $client->setAccessToken($token);

}

if (!$client->getAccessToken()) { // auth call to google
    $authUrl = $client->createAuthUrl();
    header("Location: ".$authUrl);
    die;
}


问:
Many To Many Relationship EF 6 (4 table and 1 many to many relationship) how to select with linq
I have 4 tables and between them there is one that is an intermediate table AM_PERFIL_APLICACIONES_TBL and when the mapping the intermediate table does not appreciate me in the edmx and I have read that several articles in which they explain that it is a matter of relations of many to many.

The question is how could I do a select to the 4 tables with Linq.

How can I UPDATE, INSERT or DELETE the table AM_PERFIL_APLICACIONES_TBL.

I have something like this

```<code>var query_modulo = (from a in menu.AM_USUARIOS_TBL
                                    join b in menu.AM_PERFIL_APLICACIONES_TBL on a.ID_PERFIL equals b.ID_PERFIL
                                    join c in menu.AM_APLICACIONES_TBL on b.ID_APLICACION equals c.ID_APLICACION
                                    join d in menu.AM_MODULOS_TBL on c.ID_MODULO equals d.ID_MODULO
                                    where a.ID_USUARIO == _usrid
                                    select new { d.ID_MODULO, d.DESCRIPCION }).Distinct().ToList();
</code>```

答:
When you set up your object model if it is a Many-to-Many table between Usuarios (U) and Aplicaniones (A) you would likely have a collection of (A) inside each (U), and a collection of (U) inside of each (A).

However, this is on the assumption that your linking table, Perfil_Aplicaniones (PA) is set up to just contain the ID of (U) (assumed to be ID_Perfil) and the ID of the Aplicanion. (A) (assumed to be ID_Aplicanion)

If this is the case, Entity Framework will handle the intermediary table automatically. To set up a new link between (U) and (A) you add the (A) reference to your u.Aplicaniones collection, and you add the (U) reference to your A.Usarios (or Perfils, whichever it is) When you persist the objects, EF should create the joining record automatically.

If instead though your (U) and (A) entities contain collections of PAs instead, then you will need to create the (PA) entity explicitly, set the references to the (U) and (A) records, then add that (PA) record to the U.Perfil_Aplicaniones and the A.Perfil_Aplicaniones respectively.

It all depends on how your entities (classes) are structured.  EF can manage linking tables automatically, but from memory the linking table must contain only the linking ID columns. Otherwise you have to map the linking table manually and manage the associations.

Body:
I have 4 tables and between them there is one that is an intermediate table AM_PERFIL_APLICACIONES_TBL and when the mapping the intermediate table does not appreciate me in the edmx and I have read that several articles in which they explain that it is a matter of relations of many to many.

The question is how could I do a select to the 4 tables with Linq.

How can I UPDATE, INSERT or DELETE the table AM_PERFIL_APLICACIONES_TBL.

I have something like this

var query_modulo = (from a in menu.AM_USUARIOS_TBL
                                    join b in menu.AM_PERFIL_APLICACIONES_TBL on a.ID_PERFIL equals b.ID_PERFIL
                                    join c in menu.AM_APLICACIONES_TBL on b.ID_APLICACION equals c.ID_APLICACION
                                    join d in menu.AM_MODULOS_TBL on c.ID_MODULO equals d.ID_MODULO
                                    where a.ID_USUARIO == _usrid
                                    select new { d.ID_MODULO, d.DESCRIPCION }).Distinct().ToList();


问:
python + selenium - how to select the dropdown list which the hidden = true
I'm beginner both in Selenium, and I want to select the option of the dropdown. But it always doesn't work with the error message "selenium.common.exceptions.ElementNotInteractableException: Message: "

the HTML code is below

```<code><div id="template-select-dialog" class="modal fade in" tabindex="-1" data-keyboard="true" style="display: block;" aria-hidden="false" hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<div class="modal-body">
<div class="modal-body-title">
<div class="modal-body-message">
<div class="template-names">
<select id="template-select-dialog_template-names">
<option class="select-none"></option>
<option value="Sample server">Sample server</option>
<option value="Sample network">Sample network</option>
<option value="Sample server in network">Sample server in network</option>
<option value="KST stack">KST stack</option>
<option value="KST stack for LRT">KST stack for LRT</option>
</select>
</code>```

my selenium code is below

```<code>dropM = browser.find_element_by_id("template-select-dialog_template-names")
dropM.find_element_by_xpath("//option[@value='KST stack for LRT']").click()
</code>```

I don't know the reason whether is the " hidden="true" " or not, so shall you give me some advice, thank you !

答:
There is special class to dealing with dropdown select elements

```<code>from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id("template-select-dialog_template-names"))
select.select_by_visible_text('KST stack for LRT')
</code>```

More info is here - http://selenium-python.readthedocs.io/navigating.html#filling-in-forms

Body:
I'm beginner both in Selenium, and I want to select the option of the dropdown. But it always doesn't work with the error message "selenium.common.exceptions.ElementNotInteractableException: Message: "

the HTML code is below

<select id="template-select-dialog_template-names">
<option class="select-none"></option>
<option value="Sample server">Sample server</option>
<option value="Sample network">Sample network</option>
<option value="Sample server in network">Sample server in network</option>
<option value="KST stack">KST stack</option>
<option value="KST stack for LRT">KST stack for LRT</option>
</select>

my selenium code is below

dropM = browser.find_element_by_id("template-select-dialog_template-names")
dropM.find_element_by_xpath("//option[@value='KST stack for LRT']").click()

I don't know the reason whether is the " hidden="true" " or not, so shall you give me some advice, thank you !

Body:
There is special class to dealing with dropdown select elements

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id("template-select-dialog_template-names"))
select.select_by_visible_text('KST stack for LRT')

More info is here - http://selenium-python.readthedocs.io/navigating.html#filling-in-forms


问:
Copying Checked rows from one table to another table
Actually i am looking to copy the checked rows from the table of one div (table 1) to table of another div(table 2). But with the below script, when i check more than one checkbox, the first checked row is replaced by the lastly checked row. But i want like each checked row of table 1 should come in table 2 as one by one.

Any help appreciated. Thanks in advance!!!

HTML

```<code> <div class="form-group" id="jqcc" >

         <table id="order-table" name="order-table">
             <tr>
                 <th>Select</th>
                 <th>Medication</th>
                 <th>Max Issue Limit</th>
             </tr>
             <tbody></tbody>
         </table>
</div>
</code>```

Javascript

```<code><script>
        var tableControl = document.getElementById('order-table');
        $('#jqcc').click(function () {
        var result = []
        var x1;
        var tab;

       var count = document.querySelectorAll('input[type="checkbox"]:checked').length;

      $('input:checkbox:checked', tableControl).each(function () {

           result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product

           $(this).closest('tr').find('input').each(function () {

           x1 = $(this).val(); // refers price of product

       })

       tab = "<tr><td>" + result + "</td>";
       tab += "<td>" + x1 + "</td>";
       tab += "<td>" + x1 + " </td>";
       tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
       tab += "</tr>";
       tab += "</tbody>"

       $("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th> <th>Claim Amount</th> <th></th></tr></thead>" + tab + "</table>").show();

    });

});
</script>
</code>```

答:
You try to change:</p>

```<code><script>
    var tableControl = document.getElementById('order-table');
    $('#jqcc').click(function () {
    var result = []
    var x1;
    var tab = "";

   var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
    $("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th><th>Claim Amount</th> <th></th></tr></thead><tbody></tbody></table>").show();

  $('input:checkbox:checked', tableControl).each(function () {

       result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product

       $(this).closest('tr').find('input').each(function () {

       x1 = $(this).val(); // refers price of product

       //
       tab = "<tr><td>" + result + "</td>";
       tab += "<td>" + x1 + "</td>";
       tab += "<td>" + x1 + " </td>";
       tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
       tab += "</tr>";

       // append row html to table with id
       $("#peopleTable").append(tab);

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

<p>});
</p>

Body:
Actually i am looking to copy the checked rows from the table of one div (table 1) to table of another div(table 2). But with the below script, when i check more than one checkbox, the first checked row is replaced by the lastly checked row. But i want like each checked row of table 1 should come in table 2 as one by one.

Any help appreciated. Thanks in advance!!!

HTML

                 Select
                 Medication
                 Max Issue Limit

Javascript

Body:
You try to change:

<script>
    var tableControl = document.getElementById('order-table');
    $('#jqcc').click(function () {
    var result = []
    var x1;
    var tab = "";

   var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
    $("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th><th>Claim Amount</th> <th></th></tr></thead><tbody></tbody></table>").show();

  $('input:checkbox:checked', tableControl).each(function () {

       result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product

       $(this).closest('tr').find('input').each(function () {

       x1 = $(this).val(); // refers price of product

       //
       tab = "<tr><td>" + result + "</td>";
       tab += "<td>" + x1 + "</td>";
       tab += "<td>" + x1 + " </td>";
       tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
       tab += "</tr>";

       // append row html to table with id
       $("#peopleTable").append(tab);

   })
});

});


问:
Need help to change file format after the users download it from Database
Did I miss something in this code?  cuz when I test it I get the file type as "File" not as PDF.

```<code>protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString);
    conn.Open();
    string pdffile = "select pdf from users where ID='" + TextBoxLic.Text + "'";
    SqlCommand pdfcom = new SqlCommand(pdffile, conn);
    SqlDataReader reader = pdfcom.ExecuteReader();
    if (reader.Read())
    {
        Byte[] pdfData = (byte[])reader.GetValue(0);
        Response.ContentType = "Application/pdf";
        Response.AppendHeader("content-disposition", "attachment; filename=" + TextBoxLic.Text);
        Response.BinaryWrite(pdfData);
        Response.End();
        conn.Close();
    }
}
</code>```

https://i.gyazo.com/8eb75d4e55bed17155690531841d80c7.png

答: You need to set the Content-Type header to application/pdf.

Body:
Did I miss something in this code?  cuz when I test it I get the file type as "File" not as PDF.

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString);
    conn.Open();
    string pdffile = "select pdf from users where ID='" + TextBoxLic.Text + "'";
    SqlCommand pdfcom = new SqlCommand(pdffile, conn);
    SqlDataReader reader = pdfcom.ExecuteReader();
    if (reader.Read())
    {
        Byte[] pdfData = (byte[])reader.GetValue(0);
        Response.ContentType = "Application/pdf";
        Response.AppendHeader("content-disposition", "attachment; filename=" + TextBoxLic.Text);
        Response.BinaryWrite(pdfData);
        Response.End();
        conn.Close();
    }
}

https://i.gyazo.com/8eb75d4e55bed17155690531841d80c7.png


问:
MySQL load data: This command is not supported in the prepared statement protocol yet
I'm trying to write a MySQL script to import data into a table for my Linux server. Here is the script named update.sql:

```<code>SET @query = CONCAT("LOAD DATA LOCAL INFILE '", @spaceName, "' INTO TABLE tmp FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';");
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
</code>```

And also, I write a bash script named main.sh:

```<code>mysql -h "localhost" -u "root" "-pmypassword" "mydb" -e "set @spaceName=\"$1\";source update.sql;"
</code>```

Then I execute ./main.sh France.list. The France.list is the data file that I'm trying to import into my database.

However I get an error:

ERROR 1295 (HY000) at line 2 in file: 'update.sql': This command is
  not supported in the prepared statement protocol yet

I've found this question:

MySQL - Load Data Infile with variable path

So, does it mean that there is no way to pass arguments to LOAD DATA query?

答:
You can't use PREPARE to run LOAD DATA INFILE.

The list of statements that you can run with PREPARE are documented in this page: https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html under the subheading "SQL Syntax Allowed in Prepared Statements". Note this list may be different in earlier versions of MySQL.

Because you can't use PREPARE, you can't do the method you're using by setting a variable and making a dynamic SQL statement.

But you can run LOAD DATA INFILE without using PREPARE. You have to interpolate the filename into the statement using shell variable substitution and then run it as a direct SQL statement.

Your update.sql file might look like this:

```<code>LOAD DATA LOCAL INFILE '%spacename%' INTO TABLE tmp
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';
</code>```

Then you can substitute your shell variable into the file and run the result this way:

```<code>sed s/%spacename%/$1/ update.sql |
  mysql -h "localhost" -u "root" "-pmypassword" "mydb"
</code>```

Another simpler way is to use mysqlimport, except this requires that the input filename be the same as your table name. You can either rename your input file to match the table you want to load into (which you call tmp), or else create a symbolic link:

```<code>ln -s $1 /tmp/tmp.list
mysqlimport --local -h "localhost" -u "root" "-pmypassword" "mydb" /tmp/tmp.list
rm -f /tmp/tmp.list
</code>```

The ".list" extension is ignored by mysqlimport, so you can use any file extension, or none.

Body:
I'm trying to write a MySQL script to import data into a table for my Linux server. Here is the script named update.sql:

SET @query = CONCAT("LOAD DATA LOCAL INFILE '", @spaceName, "' INTO TABLE tmp FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';");
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

And also, I write a bash script named main.sh:

mysql -h "localhost" -u "root" "-pmypassword" "mydb" -e "set @spaceName=\"$1\";source update.sql;"

Then I execute ./main.sh France.list. The France.list is the data file that I'm trying to import into my database.

However I get an error:

ERROR 1295 (HY000) at line 2 in file: 'update.sql': This command is
  not supported in the prepared statement protocol yet

I've found this question:

MySQL - Load Data Infile with variable path

So, does it mean that there is no way to pass arguments to LOAD DATA query?

Body:
You can't use PREPARE to run LOAD DATA INFILE.

The list of statements that you can run with PREPARE are documented in this page: https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html under the subheading "SQL Syntax Allowed in Prepared Statements". Note this list may be different in earlier versions of MySQL.

Because you can't use PREPARE, you can't do the method you're using by setting a variable and making a dynamic SQL statement.

But you can run LOAD DATA INFILE without using PREPARE. You have to interpolate the filename into the statement using shell variable substitution and then run it as a direct SQL statement.

Your update.sql file might look like this:

LOAD DATA LOCAL INFILE '%spacename%' INTO TABLE tmp
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';

Then you can substitute your shell variable into the file and run the result this way:

sed s/%spacename%/$1/ update.sql |
  mysql -h "localhost" -u "root" "-pmypassword" "mydb"

Another simpler way is to use mysqlimport, except this requires that the input filename be the same as your table name. You can either rename your input file to match the table you want to load into (which you call tmp), or else create a symbolic link:

ln -s $1 /tmp/tmp.list
mysqlimport --local -h "localhost" -u "root" "-pmypassword" "mydb" /tmp/tmp.list
rm -f /tmp/tmp.list

The ".list" extension is ignored by mysqlimport, so you can use any file extension, or none.


问:
All cygwin git repos becoming corrupt on reboot
So I have a gitolite setup currently running in cygwin and everything works fine during the initial gl-setup; I can push/pull from the repositories all day long with no problem.  However, the second I reboot my machine, every single repository becomes corrupt.  I took pre/post reboot tars and, using kdiff, see that all of the files under the "objects" directory have changed... significantly.  The files in my local copy (still on windows but not in cygwin) do not change however.

To give you an example of how extreme the changes are... here are the hex dumps of a random object:

Pre:

```<code>78 01 2B 29 4A 4D 55 30 33 61 30 31 00 02 85 E4  x.+)JMU03a01..…ä
FC BC 34 86 90 9D 41 31 26 67 84 8E BB 38 BD 5D  ü¼4†..A1&g„Ž»8½]
BC 48 30 55 EB C5 A2 EB B6 10 E9 EC D4 CA 94 CC  ¼H0UëÅ¢ë¶.éìÔÊ”Ì
22 86 AD DF DE D6 27 44 FC 7C FA 6D DA 89 15 7B  "†ßÞÖ'Dü|úmÚ‰.{
37 4D EC 11 54 B9 F2 14 00 C6 66 1F 3E           7Mì.T¹ò..Æf.>
</code>```

Post:

```<code>39 D5 AD B9 06 05 A0 7D 8F D2 16 F9 34 DA 62 EE  9Õ¹.. }.Ò.ù4Úbî
21 2C D3 17 7D 35 11 4C 5E 88 58 C2 DA 09 FA C3  !,Ó.}5.L^ˆXÂÚ.úÃ
25 48 C9 07 29 A3 E3 E5 F6 7F 91 C4 29 D9 45 A3  %HÉ.)£ãåö.‘Ä)ÙE£
20 A6 07 DB 94 77 F4 7C 6D 59 E5 CC C0 08 35 91   ¦.Û”wô|mYåÌÀ.5‘
FF 22 6A 3E F5 0A 44 94 18 39 8E D0 6B           ÿ"j>õ.D”.9ŽÐk
</code>```

I came across a post from git-users where somebody else had the same problem and it turns out that I'm using full-disk encryption as well (PGP Desktop) so I wonder if that's the root cause.

If anybody has any ideas, I'd be incredibly grateful!

答:
First, it is not clear in your question if you are using yourself a full disk encryption.

Then, an anti-virus might have some unintended side-effect: deactivating it just for one reboot might be interesting to check if the problem persists.

Finally, it could be about a mount issue, as illustrated by this thread:

The problem was that the working directory from which imports and adds where done resided on a text mount. After mounting it in binary mode and starting a fresh repository,
  everything is fine.

ContentLicense: CC BY-SA 2.5

Body:
So I have a gitolite setup currently running in cygwin and everything works fine during the initial gl-setup; I can push/pull from the repositories all day long with no problem.  However, the second I reboot my machine, every single repository becomes corrupt.  I took pre/post reboot tars and, using kdiff, see that all of the files under the "objects" directory have changed... significantly.  The files in my local copy (still on windows but not in cygwin) do not change however.

To give you an example of how extreme the changes are... here are the hex dumps of a random object:

Pre:

78 01 2B 29 4A 4D 55 30 33 61 30 31 00 02 85 E4  x.+)JMU03a01..…ä
FC BC 34 86 90 9D 41 31 26 67 84 8E BB 38 BD 5D  ü¼4†..A1&g„Ž»8½]
BC 48 30 55 EB C5 A2 EB B6 10 E9 EC D4 CA 94 CC  ¼H0UëÅ¢ë¶.éìÔÊ”Ì
22 86 AD DF DE D6 27 44 FC 7C FA 6D DA 89 15 7B  "†ßÞÖ'Dü|úmÚ‰.{
37 4D EC 11 54 B9 F2 14 00 C6 66 1F 3E           7Mì.T¹ò..Æf.>

Post:

39 D5 AD B9 06 05 A0 7D 8F D2 16 F9 34 DA 62 EE  9Õ¹.. }.Ò.ù4Úbî
21 2C D3 17 7D 35 11 4C 5E 88 58 C2 DA 09 FA C3  !,Ó.}5.L^ˆXÂÚ.úÃ
25 48 C9 07 29 A3 E3 E5 F6 7F 91 C4 29 D9 45 A3  %HÉ.)£ãåö.‘Ä)ÙE£
20 A6 07 DB 94 77 F4 7C 6D 59 E5 CC C0 08 35 91   ¦.Û”wô|mYåÌÀ.5‘
FF 22 6A 3E F5 0A 44 94 18 39 8E D0 6B           ÿ"j>õ.D”.9ŽÐk

I came across a post from git-users where somebody else had the same problem and it turns out that I'm using full-disk encryption as well (PGP Desktop) so I wonder if that's the root cause.

If anybody has any ideas, I'd be incredibly grateful!


问:
How to get id and input data when onChange event is happening React js?
I am new to React js.I am little bit confused that how get id and onChange evt value at the same time when all the data inside map function.Yes there are already answers out there but nothing worked for me.Any method or help would be appreciated.
Thanks in advance.</p>

```<code>import React from 'react'
import {connect} from 'react-redux'

class Upload extends React.Component{

    constructor(props){
        super(props);
        this.handleChangeSinglePost = this.handleChangeSinglePost.bind(this)
        this.handleID = this.handleID.bind(this)
    }
    handleChangeSinglePost(data){
        console.log(data)//Get the input//Not working

    }
    handleID(e){

        console.log(e.target.value)get the Id
    }
    renderMaptheSingleUpload(){
        return(
            this.props.photos.photos.map((data) => {
                return(
                    <div key={data.id} className="WholeWrapperForSingleUpload">
                        <div className="imageContainerUpload">
                            <img src={data.blobData} />
                        </div>
                        <div className="ImageTitleForUpload">
                            <form onChange={this.handleID}>
                                <input onChange={this.handleChangeSinglePost(data.id)}  name="caption" type="text" placeholder="Caption This" />
                            </form>
                        </div>
                    </div>
                )
            })
        )
    }
    render(){
        // console.log(this.props.photos)
        return(
            <div className="UploaContainer">
                <div className="UploadContainerContents">

                    {this.renderMaptheSingleUpload()}

                    <div className="tagsForupload">
                        <ul>
                            <li>OrdinaryLife</li>
                            <li>OrdinaryLife</li>
                            <li>OrdinaryLife</li>
                            <li>OrdinaryLife</li>
                            <li>OrdinaryLife</li>
                        </ul>
                    </div>
                    <div className="TagItForUpload">
                        <form>
                            <input type="text" placeholder="Tag it" />
                            <input type="submit" defaultValue="Post " />
                        </form>
                        <div className="suggestionSystemForTagging">
                            <ul>
                                <li>Drake</li>
                                <li>LetMeChoose</li>
                                <li>LetMeChoose</li>
                                <li>LetMeChoose</li>
                                <li>LetMeChoose</li>
                                <li>LetMeChoose</li>
                                <li>LetMeChoose</li>
                                <li>LetMeChoose</li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        photos:state.photoUpload
    }
};

export default connect(mapStateToProps)(Upload)
</code>```

答:
How about using Closures

```<code> handleChangeSinglePost = (id) => (e) => {
    console.log("value>>>",e.target.value);
    console.log("id>>>",id);
 }

 <input onChange={this.handleChangeSinglePost(data.id)} " />
</code>```

If you prefer not to use experimental syntax

```<code> handleChangeSinglePost(id) {
  return (e) => {
     console.log("value>>>",e.target.value);
     console.log("id>>>",id);
   }
 }
</code>```

Body:
I am new to React js.I am little bit confused that how get id and onChange evt value at the same time when all the data inside map function.Yes there are already answers out there but nothing worked for me.Any method or help would be appreciated.
Thanks in advance.

import React from 'react'
import {connect} from 'react-redux'

class Upload extends React.Component{

    constructor(props){
        super(props);
        this.handleChangeSinglePost = this.handleChangeSinglePost.bind(this)
        this.handleID = this.handleID.bind(this)
    }
    handleChangeSinglePost(data){
        console.log(data)//Get the input//Not working

    }
    handleID(e){

        console.log(e.target.value)get the Id
    }
    renderMaptheSingleUpload(){
        return(
            this.props.photos.photos.map((data) => {
                return(

                            <form onChange={this.handleID}>
                                <input onChange={this.handleChangeSinglePost(data.id)}  name="caption" type="text" placeholder="Caption This" />
                            </form>

                )
            })
        )
    }
    render(){
        // console.log(this.props.photos)
        return(

                    {this.renderMaptheSingleUpload()}

OrdinaryLife

OrdinaryLife

OrdinaryLife

OrdinaryLife

OrdinaryLife

                        <form>
                            <input type="text" placeholder="Tag it" />
                            <input type="submit" defaultValue="Post " />
                        </form>

Drake

LetMeChoose

LetMeChoose

LetMeChoose

LetMeChoose

LetMeChoose

LetMeChoose

LetMeChoose

        )
    }
}

const mapStateToProps = (state) => {
    return {
        photos:state.photoUpload
    }
};

export default connect(mapStateToProps)(Upload)

Body:
How about using Closures

 handleChangeSinglePost = (id) => (e) => {
    console.log("value>>>",e.target.value);
    console.log("id>>>",id);
 }

 <input onChange={this.handleChangeSinglePost(data.id)} " />

If you prefer not to use experimental syntax

 handleChangeSinglePost(id) {
  return (e) => {
     console.log("value>>>",e.target.value);
     console.log("id>>>",id);
   }
 }


问:
Getting a text file of asian characters with C++
I am completely new to programming, and I am teaching myself C++ via Dr. Bronson's book.

I have looked at other fixes and I don't understand them.

I am trying to do a project where I convert numbers to their phrase value. 1 = One, 2 = Two, etc. I cannot have spaces between one and two so I am outputting with no spaces. When I opened up the text file, I had only Asian characters in the file. Being a novice, my first concern was that I have been hacked. Anyhow, here is my code.

```<code>int main()
{
    int i;
    int length, mod, number1, number2,number3,numbera,numberb;
    string  str1;
    string filename = "C:\\Users\\miram\\OneDrive\\Documents\\Visual Studio 2017\\CPlusPlusProjects\\Project Euler\\Files\\17.WordSum1.txt";
    ofstream outFile;

    outFile.open(filename.c_str());
    if (outFile.fail())
    {
        cout << "\nThe file named " << filename << " did not successfully open."
             << "\Please check to make sure the file exists.";
    }

    for (i = 900; i <= 999; i++)
    {
        if (i <= 999)
        {
            length = (log(i) / log(10)) + 1;

            cout << "i: " << i << " " << length << endl;
        }

        else if (i == 1000)
        {
            length = 4;
            cout << "i: " << i << " " << length << endl;
        }

        if (length == 3)
        {
            number1 = i % 10;
            numbera = i / 10;
            number2 = numbera % 10;
            numberb = i / 100;
            number3 = numberb;
            cout << "Number 3: " << number3 << endl;
            cout << "Number 2: " << number2 << endl;
            cout << "Number 1: " << number1 << endl;
        }

        switch (length)
        {

        case 4:
        {
        outFile << "OneThousand";
        break;
        }

        case 3:
        {
            if (number3 == 1)
            {
                outFile << "OneHundredand";
            }
            else if (number3 == 2)
            {
                outFile << "TwoHundredand";
            }
            else if (number3 == 3)
            {
                outFile << "ThreeHundredand";
            }
            else if (number3 == 4)
            {
                outFile << "FourHundredand";
            }
            else if (number3 == 5)
            {
                outFile << "FiveHundredand";
            }
            else if (number3 == 6)
            {
                outFile << "SixHundredand";
            }
            else if (number3 == 7)
            {
                outFile << "SevenHundredand";
            }
            else if (number3 == 8)
            {
                outFile << "EightHundredand";
            }
            else if (number3 == 9);
            {
                outFile << "NineHundredand";
            }
            break;
        }
        }

    }

    return 0;
}
</code>```

Text file with Asian characters

答:
I complie your code by gcc in linux, there are some errors.

```<code>as.cpp: In function ‘int main()’:
as.cpp:9: error: aggregate ‘std::ofstream outFile’ has incomplete type and cannot be defined
as.cpp:15: error: unknown escape sequence '\P'
as.cpp:23: error: ‘log’ was not declared in this scope
</code>```

And I add math.h to correct log problem.Changing \P to \nP to correct the second one.As to the first one correct by using fstream.My code is on the below.(only provide first 17 lines,others are equals to yours)

```<code>1 #include<iostream>
  2 #include<fstream>
  3 #include<math.h>
  4 using namespace std;
  5 int main()
  6 {
  7         int i;
  8         int length, mod, number1, number2,number3,numbera,numberb;
  9         string  str1;
 10         string filename = "C:\\Users\\miram\\OneDrive\\Documents\\Visual Studio 2017\\CPlus    PlusProjects\\Project Euler\\Files\\17.WordSum1.txt";
 11         std::ofstream outFile;
 12         outFile.open(filename.c_str());
 13         if (outFile.fail())
 14         {
 15                 cout << "\nThe file named " << filename << " did not successfully open."
 16                         << "\nPlease check to make sure the file exists.";
 17         }
</code>```

And here is part of outputs.

```<code>  1 i: 900 3
  2 Number 3: 9
  3 Number 2: 0
  4 Number 1: 0
  5 i: 901 3
  6 Number 3: 9
  7 Number 2: 0
  8 Number 1: 1
  9 i: 902 3
 10 Number 3: 9
 11 Number 2: 0
 12 Number 1: 2
 13 i: 903 3
 14 Number 3: 9
 15 Number 2: 0
 16 Number 1: 3
 17 i: 904 3
 18 Number 3: 9
 19 Number 2: 0
 20 Number 1: 4
 21 i: 905 3
 22 Number 3: 9
 23 Number 2: 0
 24 Number 1: 5
 25 i: 906 3
 26 Number 3: 9
 27 Number 2: 0
 28 Number 1: 6
 29 i: 907 3
 30 Number 3: 9
 31 Number 2: 0
 32 Number 1: 7
</code>```

Body:
I am completely new to programming, and I am teaching myself C++ via Dr. Bronson's book.

I have looked at other fixes and I don't understand them.

I am trying to do a project where I convert numbers to their phrase value. 1 = One, 2 = Two, etc. I cannot have spaces between one and two so I am outputting with no spaces. When I opened up the text file, I had only Asian characters in the file. Being a novice, my first concern was that I have been hacked. Anyhow, here is my code.

int main()
{
    int i;
    int length, mod, number1, number2,number3,numbera,numberb;
    string  str1;
    string filename = "C:\\Users\\miram\\OneDrive\\Documents\\Visual Studio 2017\\CPlusPlusProjects\\Project Euler\\Files\\17.WordSum1.txt";
    ofstream outFile;

    outFile.open(filename.c_str());
    if (outFile.fail())
    {
        cout << "\nThe file named " << filename << " did not successfully open."
             << "\Please check to make sure the file exists.";
    }

    for (i = 900; i <= 999; i++)
    {
        if (i <= 999)
        {
            length = (log(i) / log(10)) + 1;

            cout << "i: " << i << " " << length << endl;
        }

        else if (i == 1000)
        {
            length = 4;
            cout << "i: " << i << " " << length << endl;
        }

        if (length == 3)
        {
            number1 = i % 10;
            numbera = i / 10;
            number2 = numbera % 10;
            numberb = i / 100;
            number3 = numberb;
            cout << "Number 3: " << number3 << endl;
            cout << "Number 2: " << number2 << endl;
            cout << "Number 1: " << number1 << endl;
        }

        switch (length)
        {

        case 4:
        {
        outFile << "OneThousand";
        break;
        }

        case 3:
        {
            if (number3 == 1)
            {
                outFile << "OneHundredand";
            }
            else if (number3 == 2)
            {
                outFile << "TwoHundredand";
            }
            else if (number3 == 3)
            {
                outFile << "ThreeHundredand";
            }
            else if (number3 == 4)
            {
                outFile << "FourHundredand";
            }
            else if (number3 == 5)
            {
                outFile << "FiveHundredand";
            }
            else if (number3 == 6)
            {
                outFile << "SixHundredand";
            }
            else if (number3 == 7)
            {
                outFile << "SevenHundredand";
            }
            else if (number3 == 8)
            {
                outFile << "EightHundredand";
            }
            else if (number3 == 9);
            {
                outFile << "NineHundredand";
            }
            break;
        }
        }

    }

    return 0;
}

Text file with Asian characters

Body:
I complie your code by gcc in linux, there are some errors.

as.cpp: In function ‘int main()’:
as.cpp:9: error: aggregate ‘std::ofstream outFile’ has incomplete type and cannot be defined
as.cpp:15: error: unknown escape sequence '\P'
as.cpp:23: error: ‘log’ was not declared in this scope

And I add math.h to correct log problem.Changing \P to \nP to correct the second one.As to the first one correct by using fstream.My code is on the below.(only provide first 17 lines,others are equals to yours)

1 #include<iostream>
  2 #include<fstream>
  3 #include<math.h>
  4 using namespace std;
  5 int main()
  6 {
  7         int i;
  8         int length, mod, number1, number2,number3,numbera,numberb;
  9         string  str1;
 10         string filename = "C:\\Users\\miram\\OneDrive\\Documents\\Visual Studio 2017\\CPlus    PlusProjects\\Project Euler\\Files\\17.WordSum1.txt";
 11         std::ofstream outFile;
 12         outFile.open(filename.c_str());
 13         if (outFile.fail())
 14         {
 15                 cout << "\nThe file named " << filename << " did not successfully open."
 16                         << "\nPlease check to make sure the file exists.";
 17         }

And here is part of outputs.

  1 i: 900 3
  2 Number 3: 9
  3 Number 2: 0
  4 Number 1: 0
  5 i: 901 3
  6 Number 3: 9
  7 Number 2: 0
  8 Number 1: 1
  9 i: 902 3
 10 Number 3: 9
 11 Number 2: 0
 12 Number 1: 2
 13 i: 903 3
 14 Number 3: 9
 15 Number 2: 0
 16 Number 1: 3
 17 i: 904 3
 18 Number 3: 9
 19 Number 2: 0
 20 Number 1: 4
 21 i: 905 3
 22 Number 3: 9
 23 Number 2: 0
 24 Number 1: 5
 25 i: 906 3
 26 Number 3: 9
 27 Number 2: 0
 28 Number 1: 6
 29 i: 907 3
 30 Number 3: 9
 31 Number 2: 0
 32 Number 1: 7


问:
Display values in a textbox or listbox c#
I am trying to display my values in a textbox or a listbox. I have a student class, main form, another form to add students. I was successful to add students into a dictionary and key is student Id, and there are other values(first name, last name, etc). Now I want to retrieve first name to a listbox or textbox. How can I do that?
I added a screen show to make it little bit clear.

答:
Try this

Create a student class

```<code>public class Student
{
        public string StudentID { get; set; }
       public string StudentName { get; set; }
       //remaining properties
}
</code>```

Create repo

```<code>public static class StudentRepository
{
     private static List<Student> students = new List<Student>();
     public static void AddOrUpdateStudent(Student s)
     {
          var stu = students.Where(m=>m.StudentID = s.StudentID).FirstOrDefault();
           if(stu == null)
            {
                students.Add(s);
             }
             else
             {
                 students.remove(stu);
                 students.Add(s);
             }

     }
}
</code>```

in the form use this as below

```<code>StudentRepository.AddOrUpdateStudent(s);
</code>```

Body:
Try this

Create a student class

public class Student
{
        public string StudentID { get; set; }
       public string StudentName { get; set; }
       //remaining properties
}

Create repo

public static class StudentRepository
{
     private static List<Student> students = new List<Student>();
     public static void AddOrUpdateStudent(Student s)
     {
          var stu = students.Where(m=>m.StudentID = s.StudentID).FirstOrDefault();
           if(stu == null)
            {
                students.Add(s);
             }
             else
             {
                 students.remove(stu);
                 students.Add(s);
             }

     }
}

in the form use this as below

StudentRepository.AddOrUpdateStudent(s);


问:
Disable IPython console in PyCharm
I use the PyCharm community edition and also IPython. PyCharm automatically recognizes IPython and sets it as the default console (PyCharm webhelp link), so when in debugging mode, it accepts to runs IPython magic commands, like list? or ls or %timeit.

It is very nice, but I would like to use the plain old python console. Is there a simple way to do that? Note that I do not want to uninstall IPython (which obviously solves my problem) nor do I want to set up a virtualenv.

I use Python 3.3.2, but the problem is the same with 2.7.

答:
I am using PyCharm Community Edition 2017.1.3 on CentOS 7.2. To disable the use of Ipython for current project. Go to File-->Settings-->Build, Execution, Deployment-->Console, uncheck the box Use Ipython if available.

Then close the current python console window and open it again or Rerun it. You should see that plain python is used. In my case, there is no need to restart Pycharm for this change to take effect.

Also, if you want to use Ipython instead of plain Python, do the opposite.

Title: Disable IPython console in PyCharm


问:
js can't add timezone offset to '1900-01-01T00:00:00'?
I try to new Date() to get UTC local time,

but now js can't add timezone offset (eg. add 8 hours for china).

before it works right.

In the blog On the nightmare that is JSON Dates. Plus, JSON.NET and ASP.NET Web API

WebAPI json result with ISO 8601 date format is

'2017-05-10T07:50:16'.

答:
You'll want to include timezone information within the string.

For UTC, that can be represented by Z.

```<code>new Date("2017-05-10T07:50:16Z").toUTCString()
// Wed, 10 May 2017 07:50:16 GMT
</code>```

The change in behavior reflects a change in the standard.

2011, 5th edition (the behavior you're familiar with and expecting)

The value of an absent time zone offset is “Z”.

2015, 6th edition

If the time zone offset is absent, the date-time is interpreted as a local time.

2016, 7th edition (the current behavior)

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.

Body:
You'll want to include timezone information within the string.

For UTC, that can be represented by Z.

new Date("2017-05-10T07:50:16Z").toUTCString()
// Wed, 10 May 2017 07:50:16 GMT

The change in behavior reflects a change in the standard.

2011, 5th edition (the behavior you're familiar with and expecting)

The value of an absent time zone offset is “Z”.

2015, 6th edition

If the time zone offset is absent, the date-time is interpreted as a local time.

2016, 7th edition (the current behavior)

When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as a local time.


问:
Play a youtube video when an image is clicked and go back to the image when video ends
I am developing an website where my client wants to be able to play an youtube video when he clicks an image and when the video finishes, the video disappears and the same image reappears again.

For example, view the website below and click the image on the home page.
https://www.oldbankruptcypapers.com/

答:
From the API :

```<code>function onPlayerStateChange(event) {
            if(event.data === 0) {
                //replace video with image
            }

//status states from API
  // -1 – unstarted
  // 0 – ended
  // 1 – playing
  // 2 – paused
  // 3 – buffering
  // 5 - Video Cued
</code>```

https://developers.google.com/youtube/iframe_api_reference#Retrieving_video_information

Body:
From the API :

function onPlayerStateChange(event) {
            if(event.data === 0) {
                //replace video with image
            }

//status states from API
  // -1 – unstarted
  // 0 – ended
  // 1 – playing
  // 2 – paused
  // 3 – buffering
  // 5 - Video Cued

https://developers.google.com/youtube/iframe_api_reference#Retrieving_video_information


问:
What are the best keyboard macros for programming in windows?
I like putting shortcuts of the form "g - google.lnk" in my start menu so google is two keystrokes away. Win, g.

My eight or so most frequent applications go there.

I also make links to my solution files I am always opening "x - Popular Project.lnk"

Are there any better ways to automate opening frequently used applications?

答:
AutoHotkey is a reasonably good program for implementing windows key shortcuts.  You might instead define WIN + G to be "open browser to google" which gives you a better response time (don't have to wait for start menu to popup, etc)

There are macro programs that change the macros used based on the window that's in focus.  I've never needed that much control, but you might want to look into that.

-Adam

OwnerDisplayName: Adam Davis


问:
Rails Paperclip how to delete attachment?
I am using Paperclip (w/ Amazon s3) on Rails 3. I want to delete an existing attachment without replacing it using an update action.

I've only found one example of this here and could not get that to work, it just wouldn't delete and there was nothing in the logs to say why. I wanted to do something like this on the form:

```<code><%- unless @page.new_record? || !@page.image? -%>
    <%= f.check_box :image_delete, :label => 'Delete Image' %>
<%- end -%>
</code>```

(page is the name of the model, image is the attribute name which holds the attachment)

But how do I detect that checkbox and more importantly, how do I delete the image? I appreciate any help!

答:
First off, when you create a check_box in a form_for (which it looks like you are), then the form should by default send :image_delete as "1" if checked and "0" if unchecked. The method declaration looks like this:

```<code>def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")
</code>```

Which shows that you can assign other values if you want to, but that is of course optional.

Secondly, the call to manually delete an attachment without deleting the model instance to which it is attached to is:

```<code>@page.image.destroy #Will remove the attachment and save the model
@page.image.clear #Will queue the attachment to be deleted
</code>```

And to accomplish your way of deleting the images through a checkbox, perhaps add something like this to your Page model:

```<code>class Page < ActiveRecord::Base
  has_attached_file :image

  before_save :destroy_image?

  def image_delete
    @image_delete ||= "0"
  end

  def image_delete=(value)
    @image_delete = value
  end

private
  def destroy_image?
    self.image.clear if @image_delete == "1"
  end
end
</code>```

This way, when you create your form and add the :image_delete checkbox, it will load the default value "0" from the User instance. And if that field is checked then the controller will update the image_delete to "1" and when the User is saved, it will check if the image is to be deleted.

Body:
I am using Paperclip (w/ Amazon s3) on Rails 3. I want to delete an existing attachment without replacing it using an update action.

I've only found one example of this here and could not get that to work, it just wouldn't delete and there was nothing in the logs to say why. I wanted to do something like this on the form:

<%- unless @page.new_record? || !@page.image? -%>
    <%= f.check_box :image_delete, :label => 'Delete Image' %>
<%- end -%>

(page is the name of the model, image is the attribute name which holds the attachment)

But how do I detect that checkbox and more importantly, how do I delete the image? I appreciate any help!

Body:
First off, when you create a check_box in a form_for (which it looks like you are), then the form should by default send :image_delete as "1" if checked and "0" if unchecked. The method declaration looks like this:

def check_box(method, options = {}, checked_value = "1", unchecked_value = "0")

Which shows that you can assign other values if you want to, but that is of course optional.

Secondly, the call to manually delete an attachment without deleting the model instance to which it is attached to is:

@page.image.destroy #Will remove the attachment and save the model
@page.image.clear #Will queue the attachment to be deleted

And to accomplish your way of deleting the images through a checkbox, perhaps add something like this to your Page model:

class Page < ActiveRecord::Base
  has_attached_file :image

  before_save :destroy_image?

  def image_delete
    @image_delete ||= "0"
  end

  def image_delete=(value)
    @image_delete = value
  end

private
  def destroy_image?
    self.image.clear if @image_delete == "1"
  end
end

This way, when you create your form and add the :image_delete checkbox, it will load the default value "0" from the User instance. And if that field is checked then the controller will update the image_delete to "1" and when the User is saved, it will check if the image is to be deleted.


问:
Textmate: Remove a list of email addresses from a larger list
This feels like something that ought to be very simple, but i've been unable to find any way to accomplish it.

i have a list of over 10,000 email addresses in a text file. i have another, shorter list of 100+ addresses i need to remove from the original list. The problem is, there is an unknown number of addresses between each one to be removed.

i want to know: Is there a way to remove this list of addresses from the main list without doing a find/replace for each of the 100+ addresses individually?

答:
If I were you, I'd use either

Python(or any language)

Excel

Python:
  make the larger file A into list_A, smaller file B into list_B
and then just for loop through list_A: if element of list_A exists in list_B, kick it out.

Excel:
  Paste file A to column A, file B to column B. And then column C, using formula "countif" to show if any element of A exists in column B.


答:
It looks like you've found a corner case where Notepad's encoding detection guesses wrong.

The string "NineHundredand", encoded using ASCII gives the byte sequence 0x4E 0x69 0x6E 0x48 0x75 0x6E 0x64 0x72 0x65 0x64 0x61 0x6E 0x64.  It turns out that same sequence of bytes is also valid UTF-16 encoding for the string "楎敮畈摮敲慤摮".  Since there's nothing to tell Notepad which interpretation of the bytes is correct, it has to guess.  How it makes the guess it does is likely quite complicated and probably not documented anywhere (at least not publicly), but in this case it guessed wrong.  Strangely enouough, it seems to depend on how many times you repeat the phrase "NineHundredand".  Less than 15 times and it will guess the encoding as ASCII; more than that and it decides the file is encoded using UTF-16.

Title: Getting a text file of asian characters with C++


问:
How to echo values from two indexed arrays in an alternating fashion?
I have this code:

```<code><?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>
</code>```

And it brings: 123567abcdef. How can I get 123abc567def?

答:
Here is a one-liner using array_map() and implode():

```<code>$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');

$result=implode(array_map(function($v1,$v2){return $v1.$v2;},$arrayName2,$arrayName3));
echo $result;
// output: 123abc567def
</code>```

Or if you are simply echoing and don't need a variable, this will be more efficient than Adhan's solution because it doesn't have to modify the input data:

```<code>array_map(function($v1,$v2){echo $v1,$v2;},$arrayName2,$arrayName3);
// output: 123abc567def
</code>```

And finally, this is a more efficient foreach version because array_combine() is unnecessary:

```<code>foreach($arrayName2 as $k=>$a){
    echo $a,$arrayName3[$k];
}
// output: 123abc567def
</code>```

Body:
I have this code:

<?php
$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');
$arrayName[] = $arrayName2;
$arrayName[] = $arrayName3;
foreach ($arrayName as $key) {
    foreach($key as $innerKey) {
        echo $innerKey;
    }
}
?>

And it brings: 123567abcdef. How can I get 123abc567def?

Body:
Here is a one-liner using array_map() and implode():

$arrayName2 = array('123', '567');
$arrayName3 = array('abc', 'def');

$result=implode(array_map(function($v1,$v2){return $v1.$v2;},$arrayName2,$arrayName3));
echo $result;
// output: 123abc567def

Or if you are simply echoing and don't need a variable, this will be more efficient than Adhan's solution because it doesn't have to modify the input data:

array_map(function($v1,$v2){echo $v1,$v2;},$arrayName2,$arrayName3);
// output: 123abc567def

And finally, this is a more efficient foreach version because array_combine() is unnecessary:

foreach($arrayName2 as $k=>$a){
    echo $a,$arrayName3[$k];
}
// output: 123abc567def


问:
wso2 Greg - Service Registry and Discover with Rest
I have all wso2 products, but I don't understand how I can use Governance Registry in conjunction with rest webservices.

For example: I published a Rest Webservice in Governance, and now I want to use the service discovery to get the endpoint for this Webservice.

It's possible to do this with wso2 products?

Thanks

答:
With WSO2 Governance Registry, you can discover endpoint details in three different ways: As example, if you are using WSO2 ESB(integration scenarios for Governance)

Share Registry space with both ESB and G-Reg

Use G-Reg to push artifacts into ESB node

ESB pull artifact from the G-Reg

Since you have already created a Rest Service in the G-Reg side, you can retrieve Endpoint details using Governance Rest API. It has an inbuilt functionality to retrieve Endpoint associated with a given RestService instance. You can find more details from this doc.


问:
Airflow unpause dag programmatically?
I have a dag that we'll deploy to multiple different airflow instances and in our airflow.cfg we have dags_are_paused_at_creation = True but for this specific dag we want it to be turned on without having to do so manually by clicking on the UI. Is there a way to do it programmatically?

答:
I created the following function to do so if anyone else runs into this issue:</p>

```<code>import airflow.settings
from airflow.models import DagModel
def unpause_dag(dag):
    """
    A way to programatically unpause a DAG.
    :param dag: DAG object
    :return: dag.is_paused is now False
    """
    session = airflow.settings.Session()
    try:
        qry = session.query(DagModel).filter(DagModel.dag_id == dag.dag_id)
        d = qry.first()
        d.is_paused = False
        session.commit()
    except:
        session.rollback()
    finally:
        session.close()
</code>```

Title: Airflow unpause dag programmatically?

Body:
I created the following function to do so if anyone else runs into this issue:

import airflow.settings
from airflow.models import DagModel
def unpause_dag(dag):
    """
    A way to programatically unpause a DAG.
    :param dag: DAG object
    :return: dag.is_paused is now False
    """
    session = airflow.settings.Session()
    try:
        qry = session.query(DagModel).filter(DagModel.dag_id == dag.dag_id)
        d = qry.first()
        d.is_paused = False
        session.commit()
    except:
        session.rollback()
    finally:
        session.close()


问:
Java almostIncreasingSequence
Okay so i just started out on CodeFight, I got this question:

After a couple of hours of trying to figure a way by myself to solve it i got it fully functional but apperently its not within the time limit, and I do not know how to fix it even more to solve it.

```<code>boolean almostIncreasingSequence(int[] sequence) {
    List<Integer> A = new ArrayList<Integer>();
    for (int i = 0; i < sequence.length; i++){
        A.add(sequence[i]);
    }
    for (int i = 0; i < A.size(); i++){
        ArrayList<Integer> AC = new ArrayList<Integer>(A);
        AC.remove(i);
        boolean ps = true;
        for (int x = 0; x < AC.size()-1; x++){
            if (AC.get(x) >= AC.get(x+1)){
                ps = false;
                break;
            }
        }
        if (ps){
            return true;
        }
    }
    return false;
}
</code>```

This what I'm getting

I know there are questions just like this out there but i haven't found a solution. I hope someone can help. I have been stuck for hours on this.

答:
I think the code for your problem should have looked like this

```<code>public static void main( String[] args )
{
    System.out.println( "Output: " + almostIncreasingSequence( new int[]{1,3,2,1} ) );
    System.out.println("\r\n");
    System.out.println( "Output: " + almostIncreasingSequence( new int[]{1,3,2} ) ) ;
    System.out.println("\r\n");
    System.out.println( "Output: " + almostIncreasingSequence( new int[]{1,3,5,12,15,2} ) );
}

public static boolean almostIncreasingSequence( int[] array )
{
    boolean hasIncreasingSequenceNature = false;
    for( int x = 0; x < array.length; x++ )
    {
        boolean almostIncreasingWithRemovedElement = assumeRemovedElement(x , array);
        System.out.println( "Removing " + array[x] + " would produce INCREASING SEQUENCE?: " + almostIncreasingWithRemovedElement);
        if( almostIncreasingWithRemovedElement )
        {
            hasIncreasingSequenceNature = true;
        }
    }
    return hasIncreasingSequenceNature;
}

public static boolean assumeRemovedElement( int assumeRemovedIndex , int[] data )
{
    boolean isIncreasing = false;
    for( int x = 0; x < data.length - 1; x++ )
    {
        if( x == ( assumeRemovedIndex - 1 ) )
        {
            if( (x < data.length - 2 ) )
            {
                if( data[x] < data[x + 2] )
                {
                    isIncreasing = true;
                }
                else
                {
                    isIncreasing = false;
                    break;
                }
            }
        }
        else if( x != assumeRemovedIndex )
        {
            if( data[x] < data[x + 1] )
            {
                isIncreasing = true;
            }
            else
            {
                isIncreasing = false;
                break;
            }
        }
    }
    return isIncreasing;
}
</code>```

I guess the part where you are confusing is the removing an element from an array, but this does not require that you actually make attempts to remove things from the array, rather find an iterative approach, that helps you skip the assumed removed element and let the code keep track of the increasing sequence within the array, during the iteration

Explaining the code, boolean almostIncreasingSequence(int[]) really does nothing but makes a brute-force kind of attempt, on every element in the list, to see how would assumeRemovedElement(int byIndex , int[] yourSequence) return when the incrementing-sequence checking algo is applied by skipping the array element with byIndex variable. Once we find that assumeRemovedElement(int , int[]) returns true, almostIncreasingSequence(int[]) flags it's hasIncreasingSequenceNature as true or false, so that the final output could be analyzed, because remember, you have to check the sequence by assuming the removal of each and every element in the array, hence the term brute force

assumeRemovedElement( int assumeRemovedIndex , int[] data) applies the algo where the increasing sequence within array is checked by making sure that we don't encounter any kind of situation involving the comparison with the assumed removed element in the array and those safety measures are taken when if( x == ( assumeRemovedIndex - 1 ) ) and else if( x != assumeRemovedIndex ) execute within the loop where we struggle to maintain our increasing sequence checking code with basic if/else constructs, Hope that clarifies a lot, but certainly open to further discussions

Title: Java almostIncreasingSequence

Body:
Okay so i just started out on CodeFight, I got this question:

After a couple of hours of trying to figure a way by myself to solve it i got it fully functional but apperently its not within the time limit, and I do not know how to fix it even more to solve it.

boolean almostIncreasingSequence(int[] sequence) {
    List<Integer> A = new ArrayList<Integer>();
    for (int i = 0; i < sequence.length; i++){
        A.add(sequence[i]);
    }
    for (int i = 0; i < A.size(); i++){
        ArrayList<Integer> AC = new ArrayList<Integer>(A);
        AC.remove(i);
        boolean ps = true;
        for (int x = 0; x < AC.size()-1; x++){
            if (AC.get(x) >= AC.get(x+1)){
                ps = false;
                break;
            }
        }
        if (ps){
            return true;
        }
    }
    return false;
}

This what I'm getting

I know there are questions just like this out there but i haven't found a solution. I hope someone can help. I have been stuck for hours on this.

Body:
I think the code for your problem should have looked like this

public static void main( String[] args )
{
    System.out.println( "Output: " + almostIncreasingSequence( new int[]{1,3,2,1} ) );
    System.out.println("\r\n");
    System.out.println( "Output: " + almostIncreasingSequence( new int[]{1,3,2} ) ) ;
    System.out.println("\r\n");
    System.out.println( "Output: " + almostIncreasingSequence( new int[]{1,3,5,12,15,2} ) );
}

public static boolean almostIncreasingSequence( int[] array )
{
    boolean hasIncreasingSequenceNature = false;
    for( int x = 0; x < array.length; x++ )
    {
        boolean almostIncreasingWithRemovedElement = assumeRemovedElement(x , array);
        System.out.println( "Removing " + array[x] + " would produce INCREASING SEQUENCE?: " + almostIncreasingWithRemovedElement);
        if( almostIncreasingWithRemovedElement )
        {
            hasIncreasingSequenceNature = true;
        }
    }
    return hasIncreasingSequenceNature;
}

public static boolean assumeRemovedElement( int assumeRemovedIndex , int[] data )
{
    boolean isIncreasing = false;
    for( int x = 0; x < data.length - 1; x++ )
    {
        if( x == ( assumeRemovedIndex - 1 ) )
        {
            if( (x < data.length - 2 ) )
            {
                if( data[x] < data[x + 2] )
                {
                    isIncreasing = true;
                }
                else
                {
                    isIncreasing = false;
                    break;
                }
            }
        }
        else if( x != assumeRemovedIndex )
        {
            if( data[x] < data[x + 1] )
            {
                isIncreasing = true;
            }
            else
            {
                isIncreasing = false;
                break;
            }
        }
    }
    return isIncreasing;
}

I guess the part where you are confusing is the removing an element from an array, but this does not require that you actually make attempts to remove things from the array, rather find an iterative approach, that helps you skip the assumed removed element and let the code keep track of the increasing sequence within the array, during the iteration

Explaining the code, boolean almostIncreasingSequence(int[]) really does nothing but makes a brute-force kind of attempt, on every element in the list, to see how would assumeRemovedElement(int byIndex , int[] yourSequence) return when the incrementing-sequence checking algo is applied by skipping the array element with byIndex variable. Once we find that assumeRemovedElement(int , int[]) returns true, almostIncreasingSequence(int[]) flags it's hasIncreasingSequenceNature as true or false, so that the final output could be analyzed, because remember, you have to check the sequence by assuming the removal of each and every element in the array, hence the term brute force

assumeRemovedElement( int assumeRemovedIndex , int[] data) applies the algo where the increasing sequence within array is checked by making sure that we don't encounter any kind of situation involving the comparison with the assumed removed element in the array and those safety measures are taken when if( x == ( assumeRemovedIndex - 1 ) ) and else if( x != assumeRemovedIndex ) execute within the loop where we struggle to maintain our increasing sequence checking code with basic if/else constructs, Hope that clarifies a lot, but certainly open to further discussions


问:
Queuing YouTube Videos
I want to know how to add selected YouTube videos to a temporary playlist / playing queue?

I have an option where user have to select what all videos to be included in the playing queue.

Click on the ADD icon (black background box) and that selected video will be displayed in the purple background and it also has to be included in the playlist/Queue.

I am able to add the videos in the purple box but unable to add them in the queue.

I tried using this code

```<code>player.cuePlaylist({
    list:  ["83uA6kS_6LE", "RVYU9Be2RtA", "DkQRcjKTqiU", "5NUZtQRgLSQ"]  //array of videos ID
});
</code>```

After that when currently playing video ends I tried to play next video using

```<code>function onPlayerStateChange(event) {
if(event.data==0){     //when video ends event.data becomes 0
      player.nextVideo();
}
</code>```

But it neither do anything nor shows any error in the console.
I even tried replacing player.nextVideo(); with player.playVideo(); then instead of starting next video it re-plays the current one.

I tried looking for it in the YouTube documentation but couldn't find anything
https://developers.google.com/youtube/js_api_reference#Queueing_Functions

EDIT 1

TRIED with

cueVideoById(); loadVideoById();
But not working.

I would really appreciate if you guys can provide me an answer or a way to reach the correct audience for this question.

答:
I think the issue is that you have a typo in your call to cuePlaylist. The argument is "playlist" and not "list". Try this:</p>

```<code>player.cuePlaylist({
    playlist:  ["83uA6kS_6LE", "RVYU9Be2RtA", "DkQRcjKTqiU", "5NUZtQRgLSQ"]
});
</code>```

Title: Queuing YouTube Videos

Body:
I want to know how to add selected YouTube videos to a temporary playlist / playing queue?

I have an option where user have to select what all videos to be included in the playing queue.

Click on the ADD icon (black background box) and that selected video will be displayed in the purple background and it also has to be included in the playlist/Queue.

I am able to add the videos in the purple box but unable to add them in the queue.

I tried using this code

player.cuePlaylist({
    list:  ["83uA6kS_6LE", "RVYU9Be2RtA", "DkQRcjKTqiU", "5NUZtQRgLSQ"]  //array of videos ID
});

After that when currently playing video ends I tried to play next video using

function onPlayerStateChange(event) {
if(event.data==0){     //when video ends event.data becomes 0
      player.nextVideo();
}

But it neither do anything nor shows any error in the console.
I even tried replacing player.nextVideo(); with player.playVideo(); then instead of starting next video it re-plays the current one.

I tried looking for it in the YouTube documentation but couldn't find anything
https://developers.google.com/youtube/js_api_reference#Queueing_Functions

EDIT 1

TRIED with

cueVideoById(); loadVideoById();
But not working.

I would really appreciate if you guys can provide me an answer or a way to reach the correct audience for this question.

Body:
I think the issue is that you have a typo in your call to cuePlaylist. The argument is "playlist" and not "list". Try this:

player.cuePlaylist({
    playlist:  ["83uA6kS_6LE", "RVYU9Be2RtA", "DkQRcjKTqiU", "5NUZtQRgLSQ"]
});


问:
Is this common practice to avoid key not found in a dictionary
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary?</p>

```<code># default is 0
value = my_dic[100] if 100 in my_dic else 0
</code>```

答:
It is valid python syntax, however I would say that according to Python Coding Style Guidelines You should structure your if else statements like so,</p>

```<code>if <condition>:
    <statements>
else:
    <statements>
</code>```

Body:
I was wondering, whether the following style is a common practice to avoid key not found in a dictionary?

# default is 0
value = my_dic[100] if 100 in my_dic else 0

Body:
It is valid python syntax, however I would say that according to Python Coding Style Guidelines You should structure your if else statements like so,

if <condition>:
    <statements>
else:
    <statements>


问:
Is http_x_forwarded_for safe for check IP
is http_x_forwarded_for safe?

In requests, is it able to modify the http_x_forwarded_for with fake ip?

Can hackers do that?

答:
```<code>is http_x_forwarded_for safe?
</code>```

It depends on the proxy server you rely on. The proxy server has a complete control over this header and it can set whatever value in the header. So, if you are in control of the proxy, you can trust the attribute and can confirm its the correct information. I have used this successfully in the past to read the Client IP address with the trusted proxy server setup.

```<code>is it able to modify the http_x_forwarded_for with fake ip?
Can hackers do that?
</code>```

If you are talking about modifying the request at a particular hop in a network containing multiple proxy servers before it reaches the server, then yes its possible. So, its depends on your proxy setup on how you control it. If its about change the header over the network tunnel by intercepting the proxy request forwarded, IMO it may be possible but can be avoided using a proper handshake protocol.

Body:
is http_x_forwarded_for safe?

It depends on the proxy server you rely on. The proxy server has a complete control over this header and it can set whatever value in the header. So, if you are in control of the proxy, you can trust the attribute and can confirm its the correct information. I have used this successfully in the past to read the Client IP address with the trusted proxy server setup.

is it able to modify the http_x_forwarded_for with fake ip?
Can hackers do that?

If you are talking about modifying the request at a particular hop in a network containing multiple proxy servers before it reaches the server, then yes its possible. So, its depends on your proxy setup on how you control it. If its about change the header over the network tunnel by intercepting the proxy request forwarded, IMO it may be possible but can be avoided using a proper handshake protocol.


问:
Compare two version strings in Swift
I have two different app version Strings (i.e. "3.0.1" and "3.0.2").

How can compare these using Swift?

答:
You don't need to cast it as NSString. String object in Swift 3 is just powerful enough to compare versions like below.

```<code>let version = "1.0.0"
let targetVersion = "0.5.0"

version.compare(targetVersion, options: .numeric) == .orderedSame        // false
version.compare(targetVersion, options: .numeric) == .orderedAscending   // false
version.compare(targetVersion, options: .numeric) == .orderedDescending  // true
</code>```

But sample above does not cover versions with extra zeros.(Ex: "1.0.0" & "1.0")

So, I've made all kinds of these extension methods in String to handle version comparison using Swift. It does consider extra zeros I said, quite simple and will work as you expected.

```<code>XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "13.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: UIDevice.current.systemVersion))
XCTAssertTrue("0.1.1".isVersion(greaterThan: "0.1"))
XCTAssertTrue("0.1.0".isVersion(equalTo: "0.1"))
XCTAssertTrue("10.0.0".isVersion(equalTo: "10"))
XCTAssertTrue("10.0.1".isVersion(equalTo: "10.0.1"))
XCTAssertTrue("5.10.10".isVersion(lessThan: "5.11.5"))
XCTAssertTrue("1.0.0".isVersion(greaterThan: "0.99.100"))
XCTAssertTrue("0.5.3".isVersion(lessThanOrEqualTo: "1.0.0"))
XCTAssertTrue("0.5.29".isVersion(greaterThanOrEqualTo: "0.5.3"))
</code>```

Just take a look and take all you want in my sample extension repository with no license to care about.

https://github.com/DragonCherry/VersionCompare

Title: Compare two version strings in Swift

Body:
You don't need to cast it as NSString. String object in Swift 3 is just powerful enough to compare versions like below.

let version = "1.0.0"
let targetVersion = "0.5.0"

version.compare(targetVersion, options: .numeric) == .orderedSame        // false
version.compare(targetVersion, options: .numeric) == .orderedAscending   // false
version.compare(targetVersion, options: .numeric) == .orderedDescending  // true

But sample above does not cover versions with extra zeros.(Ex: "1.0.0" & "1.0")

So, I've made all kinds of these extension methods in String to handle version comparison using Swift. It does consider extra zeros I said, quite simple and will work as you expected.

XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThan: "99.0.0"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(equalTo: UIDevice.current.systemVersion))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThan: "3.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(lessThanOrEqualTo: "13.5.99"))
XCTAssertTrue(UIDevice.current.systemVersion.isVersion(greaterThanOrEqualTo: UIDevice.current.systemVersion))
XCTAssertTrue("0.1.1".isVersion(greaterThan: "0.1"))
XCTAssertTrue("0.1.0".isVersion(equalTo: "0.1"))
XCTAssertTrue("10.0.0".isVersion(equalTo: "10"))
XCTAssertTrue("10.0.1".isVersion(equalTo: "10.0.1"))
XCTAssertTrue("5.10.10".isVersion(lessThan: "5.11.5"))
XCTAssertTrue("1.0.0".isVersion(greaterThan: "0.99.100"))
XCTAssertTrue("0.5.3".isVersion(lessThanOrEqualTo: "1.0.0"))
XCTAssertTrue("0.5.29".isVersion(greaterThanOrEqualTo: "0.5.3"))

Just take a look and take all you want in my sample extension repository with no license to care about.

https://github.com/DragonCherry/VersionCompare


问:
removing duplicates from a bool list
I am trying to get a word in a list that is followed by a word with a ''.'' in it. for example, if this is a list

```<code>test_list = ["hello", "how", "are.", "you"]
</code>```

it would select the word ''you'' I have managed to pull this off but I am trying to ensure that I do not get duplicate words.
Here is what I have so far

```<code>list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list
</code>```

答:
Your whole code can be reduced to this example using zip() and list comprehension:

```<code>a = ['hello', 'how', 'are.', 'you']

def get_new_list(a):
    return [v for k,v in zip(a, a[1:]) if k.endswith('.')]
</code>```

Then, to remove the duplicates, if there is any, you can use set(), like this example:

```<code>final = set(get_new_list(a))
</code>```

output:

```<code>{'you'}
</code>```

Title: removing duplicates from a bool list

Body:
I am trying to get a word in a list that is followed by a word with a ''.'' in it. for example, if this is a list

test_list = ["hello", "how", "are.", "you"]

it would select the word ''you'' I have managed to pull this off but I am trying to ensure that I do not get duplicate words.
Here is what I have so far

list = []
i = 0
bool = False
words = sent.split()
for word in words:
    if bool:
        list.append(word)
        bool = False
   # the bellow if statment seems to make everything worse instead of fixing the duplicate problem
    if "." in word and word not in list:
        bool = True
return list

Body:
Your whole code can be reduced to this example using zip() and list comprehension:

a = ['hello', 'how', 'are.', 'you']

def get_new_list(a):
    return [v for k,v in zip(a, a[1:]) if k.endswith('.')]

Then, to remove the duplicates, if there is any, you can use set(), like this example:

final = set(get_new_list(a))

output:

{'you'}