问:
How to refactor complicated SQL query which is broken
Here is the simplified model of the domain

In a nutshell, unit grants documents to to a customer. There are two types of units: main units and their child units. Both belong to the same province, and to one province may belong multiple cities. Document has numerous events (processing history). Customer belongs to one city and province.

I have to write query, which returns random set of documents, given a target main unit code. Here is the criteria:

Return 10 documents where the newest event_code = 10

Each document must belong to a different customer living in any city of the unit's region (prefer different cities)

Return the Customers newest Document which meets the criteria

There must be both document types present in the result

Result (customers chosen) should be random with each query

But...

If there's not enough customers, try to use multiple documents of the same customer as a last resort

If there aren't enough documents either, return as much as possible

If there's not a single instance of another document type, then return all the same

There may be million of rows, and the query must be as fast as possible, it is executed frequently.

I'm not sure how to structure this kind of complex query in a sane manner. I'm using Oracle and PL/SQL. Here is something I tried, but it isn't working as expected (returns wrong data). How should I refactor this query and get the random result, and also honor all those borderline rules? I'm also worried about the performance regarding the joins and wheres.

```<code>CURSOR c_documents IS
WITH documents_cte AS
    SELECT d.document_id AS document_id, d.create_dt AS create_dt,
      c.customer_id
    FROM documents d
    JOIN customers c ON (c.customer_id = d.customer_id AND
      c.province_id = (SELECT region_id FROM unit WHERE unit_code = 1234))
    WHERE exists (
       SELECT 1
       FROM event
       where document_id = d.document_id AND
         event_code = 10
         AND create_dt =
            SELECT MAX(create_dt)
            FROM event
            WHERE document_id = d.document_id)
SELECT * FROM documents_cte d
WHERE create_dt = (SELECT MAX(create_dt)
                   from documents_cte
                   WHERE customer_id = d.customer_id)
</code>```

How to correctly make this query with efficiency, randomness in mind? I'm not asking for exact solution, but guidelines at least.

答:
I'd avoid hierarchic tables whenever possible. In your case you are using a hierarchic table to allow for an unlimited depth, but at last it's just two levels you store: provinces and their cities. That should better be just two tables: one for provinces and one for cities. Not a big deal, but that would make your data model simpler and easier to query.

Below I am starting with a WITH clause to get a city table, as such doesn't exist. Then I go step by step: get the customers belonging to the unit, then get their documents and rank them. At last I select the ranked documents and randomly take 10 of the best ranked ones.

```<code>with cities as
(
  select
    c.region_id as city_id,
    o.region_id as province_id
  from region c
  join region p on p.region_id = c.parent_region_id
)
, unit_customers as
(
  select customer_id
  from customer
  where city_id in
  (
    select city_id
    from cities
    where
    (
      select region_id
      from unit
      where unit_code = 1234
    ) in (city_id, province_id)
  )
)
, ranked_documents as
(
  select
    document.*,
    row_number(partition by customer_id order by create_dt desc) as rn
  from document
  where customer_id in -- customers belonging to the unit
  (
    select customer_id
    from unit_customers
  )
  and document_id in -- documents with latest event code = 10
  (
    select document_id
    from event
    group by document_id
    having max(event_code) keep (dense_rank last order by create_dt) = 10
  )
)
select *
from ranked_documents
order by rn, dbms_random.value
fetch first 10 rows only;
</code>```

This doesn't take into account to get both document types, as this contradicts the rule to get the latest documents per customer.

FETCH FIRST is availavle as of Oracle 12c. In earlier versions you would use one more subquery and another ROW_NUMBER instead.

As to speed, I'd recommend these indexes for the query:

```<code>create index idx_r1 on region(region_id); -- already exists for region_id = primary key
create index idx_r2 on region(parent_region_id, region_id);
create index idx_u1 on unit(unit_code, region_id);
create index idx_c1 on customer(city_id, customer_id);
create index idx_e1 on event(document_id, create_dt, event_code);
create index idx_d1 on document(document_id, customer_id, create_dt);
create index idx_d2 on document(customer_id, document_id, create_dt);
</code>```

One of the last two will be used, the other not. Check which with EXPLAIN PLAN and drop the unused one.

Body:
Here is the simplified model of the domain

In a nutshell, unit grants documents to to a customer. There are two types of units: main units and their child units. Both belong to the same province, and to one province may belong multiple cities. Document has numerous events (processing history). Customer belongs to one city and province.

I have to write query, which returns random set of documents, given a target main unit code. Here is the criteria:

Return 10 documents where the newest event_code = 10

Each document must belong to a different customer living in any city of the unit's region (prefer different cities)

Return the Customers newest Document which meets the criteria

There must be both document types present in the result

Result (customers chosen) should be random with each query

But...

If there's not enough customers, try to use multiple documents of the same customer as a last resort

If there aren't enough documents either, return as much as possible

If there's not a single instance of another document type, then return all the same

There may be million of rows, and the query must be as fast as possible, it is executed frequently.

I'm not sure how to structure this kind of complex query in a sane manner. I'm using Oracle and PL/SQL. Here is something I tried, but it isn't working as expected (returns wrong data). How should I refactor this query and get the random result, and also honor all those borderline rules? I'm also worried about the performance regarding the joins and wheres.

CURSOR c_documents IS
WITH documents_cte AS
    SELECT d.document_id AS document_id, d.create_dt AS create_dt,
      c.customer_id
    FROM documents d
    JOIN customers c ON (c.customer_id = d.customer_id AND
      c.province_id = (SELECT region_id FROM unit WHERE unit_code = 1234))
    WHERE exists (
       SELECT 1
       FROM event
       where document_id = d.document_id AND
         event_code = 10
         AND create_dt =
            SELECT MAX(create_dt)
            FROM event
            WHERE document_id = d.document_id)
SELECT * FROM documents_cte d
WHERE create_dt = (SELECT MAX(create_dt)
                   from documents_cte
                   WHERE customer_id = d.customer_id)

How to correctly make this query with efficiency, randomness in mind? I'm not asking for exact solution, but guidelines at least.

Body:
I'd avoid hierarchic tables whenever possible. In your case you are using a hierarchic table to allow for an unlimited depth, but at last it's just two levels you store: provinces and their cities. That should better be just two tables: one for provinces and one for cities. Not a big deal, but that would make your data model simpler and easier to query.

Below I am starting with a WITH clause to get a city table, as such doesn't exist. Then I go step by step: get the customers belonging to the unit, then get their documents and rank them. At last I select the ranked documents and randomly take 10 of the best ranked ones.

with cities as
(
  select
    c.region_id as city_id,
    o.region_id as province_id
  from region c
  join region p on p.region_id = c.parent_region_id
)
, unit_customers as
(
  select customer_id
  from customer
  where city_id in
  (
    select city_id
    from cities
    where
    (
      select region_id
      from unit
      where unit_code = 1234
    ) in (city_id, province_id)
  )
)
, ranked_documents as
(
  select
    document.*,
    row_number(partition by customer_id order by create_dt desc) as rn
  from document
  where customer_id in -- customers belonging to the unit
  (
    select customer_id
    from unit_customers
  )
  and document_id in -- documents with latest event code = 10
  (
    select document_id
    from event
    group by document_id
    having max(event_code) keep (dense_rank last order by create_dt) = 10
  )
)
select *
from ranked_documents
order by rn, dbms_random.value
fetch first 10 rows only;

This doesn't take into account to get both document types, as this contradicts the rule to get the latest documents per customer.

FETCH FIRST is availavle as of Oracle 12c. In earlier versions you would use one more subquery and another ROW_NUMBER instead.

As to speed, I'd recommend these indexes for the query:

create index idx_r1 on region(region_id); -- already exists for region_id = primary key
create index idx_r2 on region(parent_region_id, region_id);
create index idx_u1 on unit(unit_code, region_id);
create index idx_c1 on customer(city_id, customer_id);
create index idx_e1 on event(document_id, create_dt, event_code);
create index idx_d1 on document(document_id, customer_id, create_dt);
create index idx_d2 on document(customer_id, document_id, create_dt);

One of the last two will be used, the other not. Check which with EXPLAIN PLAN and drop the unused one.


来源: stackexchange

问:
node to traverse cannot be null?
i already saw the possible fixes to this problem, but i don't know what can i change in  my code.</p>

```<code>package br.com.caelum.livraria.dao;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import br.com.caelum.livraria.modelo.Usuario;

@Stateless
public class UsuarioDao {

    @PersistenceContext
    private EntityManager manager;

    public Usuario buscaPeloLogin(String login) {
        TypedQuery<Usuario> usuarioQuery = manager.createQuery("select u from Usuario u where u.login = :username",Usuario.class);
        usuarioQuery.setParameter("username", login);
        return usuarioQuery.getSingleResult();
    }
}
</code>```

答:
problem solved!

I Just put "LIKE" operator instead "=".

ContentLicense: CC BY-SA 3.0

Title: node to traverse cannot be null?

Body:
i already saw the possible fixes to this problem, but i don't know what can i change in  my code.

package br.com.caelum.livraria.dao;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import br.com.caelum.livraria.modelo.Usuario;

@Stateless
public class UsuarioDao {

    @PersistenceContext
    private EntityManager manager;

    public Usuario buscaPeloLogin(String login) {
        TypedQuery<Usuario> usuarioQuery = manager.createQuery("select u from Usuario u where u.login = :username",Usuario.class);
        usuarioQuery.setParameter("username", login);
        return usuarioQuery.getSingleResult();
    }
}


问:
expand div on hover, with bootstrap
I have a littre problem.

Curently, I have a struture like this (run in full page)

.color{
    background : red;
}

.color-green{
    background : green;
}

.vertical-align {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

<body>
  <div class="container-fluid color-green vertical-align">
    <div class="row">
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
    </div>
  </div>
</body></code>```

I would like to expand div on hover independently like this

But i use bootstrap, and I don't know how to make that with bootstrap..

if you have an idea or track to follow

thanks

答:
on :hover, you can use transform: scale() to make the element bigger, change the background, and add position: relative; z-index: 1; to keep that element on top of it's siblings. And use transition to create a smooth transition, if you want that.

.color{
    background : red;
}

.color-green{
    background : green;
}

.vertical-align {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}
.color-green > .row > .text-center {
  transition: transform .25s, background .25s;
}
.color-green > .row > .text-center:hover {
  transform: scale(1.2);
  background: #8dc63f;
  position: relative;
  z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

<body>
  <div class="container-fluid color-green vertical-align">
    <div class="row">
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
    </div>
  </div>
</body></code>```

Title: expand div on hover, with bootstrap

Body:
I have a littre problem.

Curently, I have a struture like this (run in full page)

.color{
    background : red;
}

.color-green{
    background : green;
}

.vertical-align {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

Titre

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.

Titre

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.

Titre

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.

I would like to expand div on hover independently like this

But i use bootstrap, and I don't know how to make that with bootstrap..

if you have an idea or track to follow

thanks

Body:
on :hover, you can use transform: scale() to make the element bigger, change the background, and add position: relative; z-index: 1; to keep that element on top of it's siblings. And use transition to create a smooth transition, if you want that.

.color{
    background : red;
}

.color-green{
    background : green;
}

.vertical-align {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: center;
}
.color-green > .row > .text-center {
  transition: transform .25s, background .25s;
}
.color-green > .row > .text-center:hover {
  transform: scale(1.2);
  background: #8dc63f;
  position: relative;
  z-index: 1;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >

<body>
  <div class="container-fluid color-green vertical-align">
    <div class="row">
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
      <div class="col-lg-4 text-center">
        <h1>Titre</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Amet animi aspernatur assumenda atque, commodi corporis deserunt eius enim laborum natus obcaecati optio, quidem quos repudiandae saepe tempora tempore unde veritatis.</p>
      </div>
    </div>
  </div>
</body>


问:
How to add root Project as classpath in Gradle
In JAVA eclipse, the main class of the java project is defined as one of the class in the JAR of the 'lib' folder, and the root project (fooBar) is added as a dependency in the classpath.

This can be acheived in eclipse by simply adding the root project in the classpath. However, how do we add the dependency of the root project in gradle?

```<code>dependencies {
    compile project(':fooBar');
}

> Project with path ':fooBar' could not be found in root project 'fooBar'.
</code>```

The following is the project structure:

```<code>fooBar
-src/main/java
-src/test/java
-JRE System Library
-gradle
--wrapper
--launch.gradle
-lib
-build.gradle
-settings.gradle
-gradle-apps.settings
-gradle.properties
-gradlew
-gradlew.bat
</code>```

答:
As far as the project method is concerned, the root project has no name. So this is the syntax in the subproject's build.gradle:

dependencies {
  compile project(':')
}

However, it is rarely a good idea to do this. It is too easy to end up with circular dependencies. Most multi-module projects have a separate "main" projects (called something like "main", "core" or "base"), and other modules can easily depend on that using compile project(':core') or whatever.

(Originally answered over here.)

Body:
In JAVA eclipse, the main class of the java project is defined as one of the class in the JAR of the 'lib' folder, and the root project (fooBar) is added as a dependency in the classpath.

This can be acheived in eclipse by simply adding the root project in the classpath. However, how do we add the dependency of the root project in gradle?

dependencies {
    compile project(':fooBar');
}

> Project with path ':fooBar' could not be found in root project 'fooBar'.

The following is the project structure:

fooBar
-src/main/java
-src/test/java
-JRE System Library
-gradle
--wrapper
--launch.gradle
-lib
-build.gradle
-settings.gradle
-gradle-apps.settings
-gradle.properties
-gradlew
-gradlew.bat


问:
Remove horizontal scroll bar in mobile
I am finding it difficult to remove the horizontal scroll bar on mobile devices and i really need some one that can help me remove it please would really appreciate it .

```<code>    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=no">
</code>```

CSS

```<code>{
    margin:0;
    padding:0;
}

body
{

  overflow-x:hidden;
  overflow-y:scroll;
  width:100%;
}
.header
{
    background-image:linear-gradient(rgba(0,0,0,0.7),rgba(0,0,0,0.7)),url(../img/website-startups.jpg);
    height:100vh;
    background-position: center;
    background-size: cover;
}
</code>```

答:
You can hide your scrollbar with the css below..
Add this to the page where you don't want people to see your scrollbar</p>

```<code>::-webkit-scrollbar-track
{
    -webkit-box-shadow: inset 0 0 6px transparent;
    background-color: transparent;
}

::-webkit-scrollbar
{
    width: 6px;
    background-color: transparent;
}

::-webkit-scrollbar-thumb
{
    background-color: transparent;
}
</code>```

Title: Remove horizontal scroll bar in mobile

Body:
I am finding it difficult to remove the horizontal scroll bar on mobile devices and i really need some one that can help me remove it please would really appreciate it .

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=no">

CSS

{
    margin:0;
    padding:0;
}

body
{

  overflow-x:hidden;
  overflow-y:scroll;
  width:100%;
}
.header
{
    background-image:linear-gradient(rgba(0,0,0,0.7),rgba(0,0,0,0.7)),url(../img/website-startups.jpg);
    height:100vh;
    background-position: center;
    background-size: cover;
}

Body:
You can hide your scrollbar with the css below..
Add this to the page where you don't want people to see your scrollbar

::-webkit-scrollbar-track
{
    -webkit-box-shadow: inset 0 0 6px transparent;
    background-color: transparent;
}

::-webkit-scrollbar
{
    width: 6px;
    background-color: transparent;
}

::-webkit-scrollbar-thumb
{
    background-color: transparent;
}


问:
Python extract numbers after a specific string has appeared
I'm new to python and would like to write a script to extract some numbers from a bunch of files. This is a representative example of what I'm trying to do:

```<code>File_name_1: Bob-01
File content:
...(Lots of text)
Tea cups: 3
Tea cups: 4
Tea cups: 6
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 7
Termination
</code>```

Let's say we also have another file:

```<code>File_name_2: Bob-02
File content:
...(Lots of text)
Tea cups: 2
Tea cups: 7
Tea cups: 3
Tea cups: 8
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 1
Termination.
</code>```

At the moment I have written codes to extract the file name (eg. Bob-01), number after each Bob (eg. 01), and the file content (eg. every line in the first file) and store in a variable called list_of_file

```<code>print list_of_file

[["Bob-01"],
  01,
 [".......", "Tea Cups: 3", "Tea Cups: 4", "Tea cups: 6", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 7", "Termination"],
 ["Bob-02"],
  02,
 [".......", "Tea Cups: 2", "Tea Cups: 7", "Tea cups: 3", "Tea cups: 8", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 1", "Termination]]
</code>```

What I wanted to do is to extract the number of tea cups after the line "Complete first task, proceed to the next task." in each file. So I've written the following code:

```<code>def get_tea_cups (list_of_files):
   list_of_cup = []
   for line in file[2]:
      if "Completed the first task" in line:
         for line in file[2]:
            if "Tea cups:" in line:
              tea_cups_line = line.split()
              cup_num = tea_cups_line [2]
              list_of_cup.append(file[0], file[1], cup_num)
   return list_of_cup
</code>```

My though process: if I can find "Complete first task" in list_of_file, then hopefully I can extract the number of tea cups (eg. 7 for Bob-01 and 1 for Bob-02) after the string containing "Complete first task" has appeared. However, when I executed my code, I seems to have extracted all number of tea cups, which is not what I want.

I think the reason why this has happened is because the if statement will always be true so I ended up extracting all numbers of tea cups.

Is there a way I can get around this problem?? I know if I only do the extraction for one file I can store all the tea cup numbers found as a list and take the last value (by slicing backward). Can I do something similar when I perform extraction for multiple files?

I tried to look around but haven't found anything helpful yet. If you have come across anything which is related to this question please post the link below.

Thank you!!

答:
UPDATED CODE:
What I would do:

```<code>.....

for i, line in enumerate(file[2]):
    if "Completed the first task" in line:
         for j in xrange(i+1, len(file[2]):
            if "Tea cups:" in file[2][j]:
              tea_cups_line = file[2][j].split()
              cup_num = tea_cups_line [2]
              list_of_cup.append(file[0], file[1], cup_num)
              break
return list_of_cup
</code>```

It just like your thought but My code count the variant in file[2]. When get 'Completed the first task' start the next one from the text is and go through for loop again until find 'Tea cups'. Take the number and break.

Apologize on my english and hope this help

Body:
I'm new to python and would like to write a script to extract some numbers from a bunch of files. This is a representative example of what I'm trying to do:

File_name_1: Bob-01
File content:
...(Lots of text)
Tea cups: 3
Tea cups: 4
Tea cups: 6
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 7
Termination

Let's say we also have another file:

File_name_2: Bob-02
File content:
...(Lots of text)
Tea cups: 2
Tea cups: 7
Tea cups: 3
Tea cups: 8
...(Lots of text)
Completed the first task, proceed to the next task.
...(Lots of text)
Tea cups: 1
Termination.

At the moment I have written codes to extract the file name (eg. Bob-01), number after each Bob (eg. 01), and the file content (eg. every line in the first file) and store in a variable called list_of_file

print list_of_file

[["Bob-01"],
  01,
 [".......", "Tea Cups: 3", "Tea Cups: 4", "Tea cups: 6", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 7", "Termination"],
 ["Bob-02"],
  02,
 [".......", "Tea Cups: 2", "Tea Cups: 7", "Tea cups: 3", "Tea cups: 8", "....", "Completed the first task, proceed to the next task.", "....", "Tea cups: 1", "Termination]]

What I wanted to do is to extract the number of tea cups after the line "Complete first task, proceed to the next task." in each file. So I've written the following code:

def get_tea_cups (list_of_files):
   list_of_cup = []
   for line in file[2]:
      if "Completed the first task" in line:
         for line in file[2]:
            if "Tea cups:" in line:
              tea_cups_line = line.split()
              cup_num = tea_cups_line [2]
              list_of_cup.append(file[0], file[1], cup_num)
   return list_of_cup

My though process: if I can find "Complete first task" in list_of_file, then hopefully I can extract the number of tea cups (eg. 7 for Bob-01 and 1 for Bob-02) after the string containing "Complete first task" has appeared. However, when I executed my code, I seems to have extracted all number of tea cups, which is not what I want.

I think the reason why this has happened is because the if statement will always be true so I ended up extracting all numbers of tea cups.

Is there a way I can get around this problem?? I know if I only do the extraction for one file I can store all the tea cup numbers found as a list and take the last value (by slicing backward). Can I do something similar when I perform extraction for multiple files?

I tried to look around but haven't found anything helpful yet. If you have come across anything which is related to this question please post the link below.

Thank you!!

Body:
UPDATED CODE:
What I would do:

.....

for i, line in enumerate(file[2]):
    if "Completed the first task" in line:
         for j in xrange(i+1, len(file[2]):
            if "Tea cups:" in file[2][j]:
              tea_cups_line = file[2][j].split()
              cup_num = tea_cups_line [2]
              list_of_cup.append(file[0], file[1], cup_num)
              break
return list_of_cup

It just like your thought but My code count the variant in file[2]. When get 'Completed the first task' start the next one from the text is and go through for loop again until find 'Tea cups'. Take the number and break.

Apologize on my english and hope this help


问:
Linux batch rename files, with string manipulation
I have a series of folders that having this naming convention:

DD / MM / YYYY - Name

eg:

01 / 05 / 2015 - test folder

I want to convert the format for easier reading as the name is more important than the date.

I would like the output to be

Name DD-MM-YYY

for i in *; do mv "$i" ...

So how do I in the terminal, or through a .sh (bash):

replace / (\s\/\s) with -?

move the DD-MM-YYYY to the back?

remove the - (\s\-\s)?

答:
Okay hopefuly here you have a way to do it.
Probably it can be done better but it's a start point.

First, set the file name in a variable

```<code>file='01 / 05 / 2015 - test folder'
</code>```

Then I used the - as a delimiter to grab the first part (the date) and then I changed / with -:

```<code>file_name=`echo $file | cut -f2 -d-`
file_date=`echo $file | cut -f1 -d- | sed 's/\//-/g'`
</code>```

Then just set the final name:

```<code>mv "$file" "$file_name $file_date"
</code>```

Also, if you want to delete the first space of $file_name try with

```<code>file_name=`echo $file | cut -f2 -d- | cut -c 2-`
</code>```

which cut the first character of the string.

Body:
Okay hopefuly here you have a way to do it.
Probably it can be done better but it's a start point.

First, set the file name in a variable

file='01 / 05 / 2015 - test folder'

Then I used the - as a delimiter to grab the first part (the date) and then I changed / with -:

file_name=`echo $file | cut -f2 -d-`
file_date=`echo $file | cut -f1 -d- | sed 's/\//-/g'`

Then just set the final name:

mv "$file" "$file_name $file_date"

Also, if you want to delete the first space of $file_name try with

file_name=`echo $file | cut -f2 -d- | cut -c 2-`

which cut the first character of the string.


问:
Efficient way to produce facetted bar plots
Is there a way to produce facetted bar plots as rapidly as you can produce facetted box plots?

For instance this code will produce box plots facetted by a grouping variable:

```<code>library(tidyverse)

mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_boxplot() +
  facet_grid(~ cyl)
</code>```

But the "same" code for a bar plot fails because geom_col() expects to have means provided, which would take considerably more time to calculate:

```<code>mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_col() +
  facet_grid(~ cyl)
</code>```

If there is a way to produce facetted bar plots at the speed of facetted box plots, I'd love to hear your methods.

答:
There seems to be no notable difference between those two plots

```<code>library(tidyverse)

box_plot <- function() mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_boxplot() +
  facet_grid(~ cyl)

bar_plot <- function() mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_col() +
  facet_grid(~ cyl)

library(microbenchmark)

mb <- microbenchmark(box_plot(), bar_plot())

mb
# Unit: milliseconds
#        expr      min       lq     mean   median       uq      max neval cld
#  box_plot() 2.412589 2.431660 2.538586 2.475522 2.534515 9.966422  1000   a
#  bar_plot() 2.543288 2.566173 2.670544 2.609146 2.671571 5.254653  1000   b

autoplot(mb)
</code>```

A similar test with the full diamonds dataset yields the same result. I think the bottleneck is the graphical device that needs a lot of time to display a ggplot object.

```<code>box_p <- box_plot()
bar_p <- bar_plot()

# !!! this will need about 2 minutes to execute !!!
mb2 <- microbenchmark(plot(box_p), plot(bar_p), times = 100)

mb2
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval cld
#  plot(box_p) 405.0375 513.7360 532.1827 524.1259 536.8206 740.7494   100   b
#  plot(bar_p) 454.6047 469.3411 489.3676 479.3709 497.9246 717.7909   100  a

autoplot(mb2)
</code>```

Body:
Is there a way to produce facetted bar plots as rapidly as you can produce facetted box plots?

For instance this code will produce box plots facetted by a grouping variable:

library(tidyverse)

mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_boxplot() +
  facet_grid(~ cyl)

But the "same" code for a bar plot fails because geom_col() expects to have means provided, which would take considerably more time to calculate:

mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_col() +
  facet_grid(~ cyl)

If there is a way to produce facetted bar plots at the speed of facetted box plots, I'd love to hear your methods.

Body:
There seems to be no notable difference between those two plots

library(tidyverse)

box_plot <- function() mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_boxplot() +
  facet_grid(~ cyl)

bar_plot <- function() mtcars %>%
  ggplot(aes(x = am, y = mpg)) +
  geom_col() +
  facet_grid(~ cyl)

library(microbenchmark)

mb <- microbenchmark(box_plot(), bar_plot())

mb
# Unit: milliseconds
#        expr      min       lq     mean   median       uq      max neval cld
#  box_plot() 2.412589 2.431660 2.538586 2.475522 2.534515 9.966422  1000   a
#  bar_plot() 2.543288 2.566173 2.670544 2.609146 2.671571 5.254653  1000   b

autoplot(mb)

A similar test with the full diamonds dataset yields the same result. I think the bottleneck is the graphical device that needs a lot of time to display a ggplot object.

box_p <- box_plot()
bar_p <- bar_plot()

# !!! this will need about 2 minutes to execute !!!
mb2 <- microbenchmark(plot(box_p), plot(bar_p), times = 100)

mb2
# Unit: milliseconds
#         expr      min       lq     mean   median       uq      max neval cld
#  plot(box_p) 405.0375 513.7360 532.1827 524.1259 536.8206 740.7494   100   b
#  plot(bar_p) 454.6047 469.3411 489.3676 479.3709 497.9246 717.7909   100  a

autoplot(mb2)


问:
How would I implement this fold function?
Given are the two datatypes Color and Plant.

```<code>data Color = Red | Pink | White | Blue | Purple | Green | Yellow
   deriving (Show, Eq)

data Plant =
     Leaf
   | Blossom Color
   | Stalk Plant Plant
   deriving (Show, Eq)
</code>```

Now I'm supposed to implement a function fold_plant of following type:

```<code>(x -> x -> x) -> (Color -> x) -> x -> Plant -> x
</code>```

The way I understand a fold function is that it takes a list and for each iteration it removes the first element from the list and does something with that element.

Apparently fold_plant Stalk Blossom Leaf is the identity on plants.

Now I know that in Haskell you make functions like this:

```<code>fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
fold_plant = do something
</code>```

But from here on I don't know how a fold function would work an a plant.

答:
If we look at the function signature:

```<code>fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
--            \_____ _____/    \____ _____/    |      |      |
--                  v               v          v      v      v
--                stalk           blossom     leaf  tree  output
</code>```

We see that there is stalk part as well as a blossom part and a leaf part. We will name the stalk function s and the blossom function b here and the leaf part l. In order to simplify (and optimize) the function, we will unpack these three parameters, and then call a recursive method:

```<code>fold_plant s b l = fold_plant'
    where fold_plant' = ...
</code>```

Now the question is of course what to do with fold_plant'. Given we see a Leaf, we do not need to  perform any operation on the values, we simply return our leaf result l:

```<code>fold_plant' Leaf = l
</code>```

In case we find a (Blossom c) with c a color, we have to perform a mapping from the c :: Color to an x with the b part to obtain the new value:

```<code>fold_plant' (Blossom c) = b c
</code>```

Finally in case we have a Stalk we will have to perform recursion: we first call fold_plant' on the left stalk, and then we call the fold_plant' and construct an s with the two results:

```<code>fold_plant' (Stalk lef rig) = s (fold_plant' lef) (fold_plant' rig)
</code>```

So we can put it all together into the following function:

```<code>fold_plant s b l = fold_plant'
    where fold_plant' Leaf = l
          fold_plant' (Blossom c) = b c
          fold_plant' (Stalk lef rig) = s (fold_plant' lef) (fold_plant' rig)
</code>```

Body:
Given are the two datatypes Color and Plant.

data Color = Red | Pink | White | Blue | Purple | Green | Yellow
   deriving (Show, Eq)

data Plant =
     Leaf
   | Blossom Color
   | Stalk Plant Plant
   deriving (Show, Eq)

Now I'm supposed to implement a function fold_plant of following type:

(x -> x -> x) -> (Color -> x) -> x -> Plant -> x

The way I understand a fold function is that it takes a list and for each iteration it removes the first element from the list and does something with that element.

Apparently fold_plant Stalk Blossom Leaf is the identity on plants.

Now I know that in Haskell you make functions like this:

fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
fold_plant = do something

But from here on I don't know how a fold function would work an a plant.

Body:
If we look at the function signature:

fold_plant :: (x -> x -> x) -> (Color -> x) -> x -> Plant -> x
--            \_____ _____/    \____ _____/    |      |      |
--                  v               v          v      v      v
--                stalk           blossom     leaf  tree  output

We see that there is stalk part as well as a blossom part and a leaf part. We will name the stalk function s and the blossom function b here and the leaf part l. In order to simplify (and optimize) the function, we will unpack these three parameters, and then call a recursive method:

fold_plant s b l = fold_plant'
    where fold_plant' = ...

Now the question is of course what to do with fold_plant'. Given we see a Leaf, we do not need to  perform any operation on the values, we simply return our leaf result l:

fold_plant' Leaf = l

In case we find a (Blossom c) with c a color, we have to perform a mapping from the c :: Color to an x with the b part to obtain the new value:

fold_plant' (Blossom c) = b c

Finally in case we have a Stalk we will have to perform recursion: we first call fold_plant' on the left stalk, and then we call the fold_plant' and construct an s with the two results:

fold_plant' (Stalk lef rig) = s (fold_plant' lef) (fold_plant' rig)

So we can put it all together into the following function:

fold_plant s b l = fold_plant'
    where fold_plant' Leaf = l
          fold_plant' (Blossom c) = b c
          fold_plant' (Stalk lef rig) = s (fold_plant' lef) (fold_plant' rig)


问:
Warning: No xauth data; using fake authentication data for X11 forwarding
I have an unfortunate problem when making ssh connections from Fedora 23 to Centos 7. The commands ssh -X user@centos7 and ssh -Y user@centos7 both print Warning: No xauth data; using fake authentication data for X11 forwarding.

Googling shows to add the following lines to /etc/ssh/ssh_config:

```<code>Host *
    ForwardX11Trusted yes
    ForwardAgend yes
    ForwardX11 yes
</code>```

But this didn't make the warning message go away.

答:
See https://serverfault.com/a/859370/423488

You might have to add a line like this to /etc/ssh/ssh_config of the client system:

```<code>XAuthLocation /opt/X11/bin/xauth
</code>```

But use the actual path to the xauth program on your client system (where your client system is the one you are running ssh from).  You can find the path to xauth with this command:

```<code>which xauth
</code>```

Body:
I have an unfortunate problem when making ssh connections from Fedora 23 to Centos 7. The commands ssh -X user@centos7 and ssh -Y user@centos7 both print Warning: No xauth data; using fake authentication data for X11 forwarding.

Googling shows to add the following lines to /etc/ssh/ssh_config:

Host *
    ForwardX11Trusted yes
    ForwardAgend yes
    ForwardX11 yes

But this didn't make the warning message go away.

Body:
See https://serverfault.com/a/859370/423488

You might have to add a line like this to /etc/ssh/ssh_config of the client system:

XAuthLocation /opt/X11/bin/xauth

But use the actual path to the xauth program on your client system (where your client system is the one you are running ssh from).  You can find the path to xauth with this command:

which xauth


问:
Reflection of other objects in a scene in OpenGL
I'm trying to implement a OpenGL program to generate an animation of a scene composed of a central sphere, where each object in the scene (minus the central sphere) performs rotational movement around its center of mass and around the central sphere . The ball is made of polished stainless steel and features on its surface, like a mirror, the reflection of the other objects of the scene. For each object in the scene (minus the sphere) I need to do texture mapping with a different texture. Use the "environment map" approach to produce the mirror effect on the central sphere. I researched issues related to this procedure, and what I definitely can not understand is how to get the other objects on the scene reflected in that animation. A topic that I see here (which was the closest thing I have to do) and that could help me but is not answered is in the link OpenGL Environment mapping Reflection.

If anyone can give me any idea, I will be extremely grateful. It is a university work, where the part of object construction and rotation have been done previously. The very cruel question is how to realize the reflection of these moving objects in this central sphere.

答:
The usual solution is to create a dynamic cube map. At each frame, render the scene from the viewpoint of the central sphere (with frustum: fov=90, aspect ratio=1, near plane=radius+epsilon) 6 times (once in each direction), and put the result into a cubemap.

Then write a pixel shader for the central sphere, which samples from this cube map.

It won't be perfect, but close.

There are other solutions for this problem, but I think this is the most easiest to develop in OpenGL.

If a more correct solution is needed, then you have to resort to other techniques, I'm afraid. Like ray tracing. If you only have simple geometries (plane, sphere), then you could write a little ray tracing engine in pixel shader or compute shader.


问:
tensorflow : How to compute L1 difference between the batch (matrix of size B X DIM) and vocabulary (matrix of size V X DIM)?
I have two tensorflow objects as follows

```<code>batch = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3,2], name='batch')
vocab = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0,1.0,2.0,3.0,4.0,5.0,6.0], shape=[6,2], name='vocab')
</code>```

batch has 3 vectors, each of 2 dimensions. vocab has 6 vectors, each of 2 dimensions.
I want to compute L1 difference between the every possible pair of vectors (generating 18 values).
e.g. L1 differences of [1,2] would be

```<code>|1-1|+|2-2|, |1-3|+|2-4|, |1-5|+|2-6|, |1-1|+|2-2|, |1-3|+|2-4|, |1-5|+|2-6|,
</code>```

How can I do this with tensorflow functions ? The resulting matrix could be 6 X 3 (batch X vocab). Matrix multiplication seems to be the computation that will generate the expected order of the matrix. But is there a way to override the underlying operation of matrix multiplication ? (i.e. overriding the component-wise multiplication with absolute value of difference) ?

答:
May be this response is not useful to you anymore, but I recently came across to this example of k-nearest neighbors with L1 and L2 distance.
So, I guess, your problem can be solved as:

```<code>batch = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3,2], name='batch')
vocab = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0,1.0,2.0,3.0,4.0,5.0,6.0], shape=[6,2], name='vocab')
distance_L1 = tf.reduce_sum(tf.abs(tf.subtract(vocab, tf.expand_dims(batch,1))), axis=2)
</code>```

Good luck!

Body:
I have two tensorflow objects as follows

batch = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3,2], name='batch')
vocab = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0,1.0,2.0,3.0,4.0,5.0,6.0], shape=[6,2], name='vocab')

batch has 3 vectors, each of 2 dimensions. vocab has 6 vectors, each of 2 dimensions.
I want to compute L1 difference between the every possible pair of vectors (generating 18 values).
e.g. L1 differences of [1,2] would be

|1-1|+|2-2|, |1-3|+|2-4|, |1-5|+|2-6|, |1-1|+|2-2|, |1-3|+|2-4|, |1-5|+|2-6|,

How can I do this with tensorflow functions ? The resulting matrix could be 6 X 3 (batch X vocab). Matrix multiplication seems to be the computation that will generate the expected order of the matrix. But is there a way to override the underlying operation of matrix multiplication ? (i.e. overriding the component-wise multiplication with absolute value of difference) ?

Body:
May be this response is not useful to you anymore, but I recently came across to this example of k-nearest neighbors with L1 and L2 distance.
So, I guess, your problem can be solved as:

batch = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3,2], name='batch')
vocab = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0,1.0,2.0,3.0,4.0,5.0,6.0], shape=[6,2], name='vocab')
distance_L1 = tf.reduce_sum(tf.abs(tf.subtract(vocab, tf.expand_dims(batch,1))), axis=2)

Good luck!


问:
Inserting into Access database
How do I resolve the error in inserting memo in Access from a Java program?

4159 the size of the string

the error

```<code>java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect
</code>```

The source code that executes the insert statement:

```<code>statement.executeUpdate("INSERT INTO webData VALUES ("+"'" + list.get(y)+"','"+data+ "')");
</code>```

4159 the size of data

my schma is :

table name webData with 2 coulmun the

first ID of type text

the second Field1 of type memo

i have update the statment but i have get the same error:

statement.executeUpdate("INSERT INTO webData (ID,Field1) VALUES ("+"'" + list.get(y)+"','"+data+ "')");

Thank you

答:
Please post your schema.

Rather than doing:

```<code>INSERT INTO webData VALUES (...)
</code>```

You should be doing:

```<code>INSERT INTO webData (MyColumn1, MyColumn2) VALUES (...)
</code>```

Do not rely on the physical column order in the table, you should state it explicitly to avoid errors.

ContentLicense: CC BY-SA 2.5

Title: Inserting into Access database

Body:
How do I resolve the error in inserting memo in Access from a Java program?

4159 the size of the string

the error

java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]COUNT field incorrect

The source code that executes the insert statement:

statement.executeUpdate("INSERT INTO webData VALUES ("+"'" + list.get(y)+"','"+data+ "')");

4159 the size of data

my schma is :

table name webData with 2 coulmun the

first ID of type text

the second Field1 of type memo

i have update the statment but i have get the same error:

statement.executeUpdate("INSERT INTO webData (ID,Field1) VALUES ("+"'" + list.get(y)+"','"+data+ "')");

Thank you

Body:
Please post your schema.

Rather than doing:

INSERT INTO webData VALUES (...)

You should be doing:

INSERT INTO webData (MyColumn1, MyColumn2) VALUES (...)

Do not rely on the physical column order in the table, you should state it explicitly to avoid errors.


问:
Laravel sql server on mac
So i installed SQL serve with docker on mac and i can actually manage to access my local sql server database with datagrip, but when i want to do a php artisan migrate i get this error:

```<code>[Illuminate\Database\QueryException] could not find driver (SQL: select * from sysobjects where type = 'U' and name = migrations)
</code>```

and this error

```<code>[PDOException]could not find driver
</code>```

i search for some answer but they where mostly for linux.

答:
You need a module called "pdo_mysql". Try php_info()to see if it's installed - I doubt it's there.

In your php.ini file (you can find it via php --ini) uncomment the line which has extension=pdo_mysql.so on it and restart the server.

edit: also make sure that the default key is set in your config/database.php file. Something like 'default' => env('DB_CONNECTION', 'mysql'),

Title: Laravel sql server on mac

Body:
So i installed SQL serve with docker on mac and i can actually manage to access my local sql server database with datagrip, but when i want to do a php artisan migrate i get this error:

[Illuminate\Database\QueryException] could not find driver (SQL: select * from sysobjects where type = 'U' and name = migrations)

and this error

[PDOException]could not find driver

i search for some answer but they where mostly for linux.


问:
prepared statement
how  can i write prepared statement instead of this: please help me</p>

```<code>String qry= "INSERT INTO
Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES('"+regno+"','"+dt+"','"+nm+"','"+place+"','"+kul+"','"+gotra+"','"+kswami+"','"+raddr+"','"+pincode+"','"+stdcd+"','"+tele+"','"+mno+"','"+email+"','"+website+"','"+education+"','"+branch+"','"+bdt+"','"+bloodgrp+"')";
stmt.executeUpdate(qry);
</code>```

答:
```<code>    `enter code here`you can use prepared statement of insertion like..

         Connection MyCon=null;
         PreparedStatement Ps=null;
try{
          myCon=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/demo","student","student");
       // these are string from where we can take inputs .
         String Fname;
         String Lname;
         String email;
         String department;
         String Salary;

         Fname=JOptionPane.showInputDialog(null,"Enter First Name");
         Lname=JOptionPane.showInputDialog(null,"Enter Last Name");
         email=JOptionPane.showInputDialog(null,"Enter Your Email");
         department=JOptionPane.showInputDialog(null,"Enter Department Name");
         Salary=JOptionPane.showInputDialog(null,"Enter Salary Name");

            **String insertion="insert into employees"
                   + "(first_name, last_name, email, department ,salary )"+"values "
                    + "(?,?,?,?,?)";**

             **Ps=(PreparedStatement) MyCon.prepareStatement(insertion);
               Ps.setString(1,Fname);
                 Ps.setString(2,Lname);
                 Ps.setString(3,email);
                 Ps.setString(4,department);
                 Ps.setString(5,Salary);

        Ps.executeUpdate();**
}catch(Exception e)
{
e.printtrace();
}
</code>```

Title: prepared statement

Body:
how  can i write prepared statement instead of this: please help me

String qry= "INSERT INTO
Registration1(RegistrationNo,Date,SeniorPerson,NativePlace,Kul,Gotra,KulSwami,ResidensialAddress,PinCode,STDcode,TelephoneNo,MobileNo,Email,Website,Education,Branch,BirthDate,BloodGroup) VALUES('"+regno+"','"+dt+"','"+nm+"','"+place+"','"+kul+"','"+gotra+"','"+kswami+"','"+raddr+"','"+pincode+"','"+stdcd+"','"+tele+"','"+mno+"','"+email+"','"+website+"','"+education+"','"+branch+"','"+bdt+"','"+bloodgrp+"')";
stmt.executeUpdate(qry);


问:
Python: Check if list of named tuples contains particular attribute value
I have a list of named tuples:

```<code>from collections import namedtuple

T = namedtuple('T', ['attr1', 'attr2', 'attr3', 'attr4'])
t1 = T('T1', 1, '1234', 'XYZ')
t2 = T('T2', 2, '1254', 'ABC')
t3 = T('T2', 2, '1264', 'DEF')
l = [t1, t2, t3]
</code>```

I want to check if an element exists in the list T where attr1 = 'T2'.

Checking if the list contains such an element by doing:

```<code>any(x for x in l if x.attr1 == 'T2')
</code>```

only returns the information whether such a namedtuple is in the list or not.

I would like to also pop this namedtuple from the list.

One way of doing it is:

```<code>if any(x for x in l if x.attr1 == 'T2'):
   result = [x for x in l if x.attr1 == 'T2'].pop()
</code>```

However, I don't like this solution, since I'm looping over the list l twice.

Is there any better/more-elegant way of doing this?

答:
If it is allowed to get the result as an array:

```<code>result = filter(lambda x: x.attr1 == 'T2', l)
</code>```

Or if you just want to get one then:

```<code>result = filter(lambda x: x.attr1 == 'T2', l).pop()
</code>```

Body:
I have a list of named tuples:

from collections import namedtuple

T = namedtuple('T', ['attr1', 'attr2', 'attr3', 'attr4'])
t1 = T('T1', 1, '1234', 'XYZ')
t2 = T('T2', 2, '1254', 'ABC')
t3 = T('T2', 2, '1264', 'DEF')
l = [t1, t2, t3]

I want to check if an element exists in the list T where attr1 = 'T2'.

Checking if the list contains such an element by doing:

any(x for x in l if x.attr1 == 'T2')

only returns the information whether such a namedtuple is in the list or not.

I would like to also pop this namedtuple from the list.

One way of doing it is:

if any(x for x in l if x.attr1 == 'T2'):
   result = [x for x in l if x.attr1 == 'T2'].pop()

However, I don't like this solution, since I'm looping over the list l twice.

Is there any better/more-elegant way of doing this?

Body:
If it is allowed to get the result as an array:

result = filter(lambda x: x.attr1 == 'T2', l)

Or if you just want to get one then:

result = filter(lambda x: x.attr1 == 'T2', l).pop()


问:
Passing 'this' into a cached click handler
I have a function in some uneditable file that binds a click handler to some items, as such:

```<code>$("#container").on("click", ".editThis", function(e) {
    var elemID = this.id;
    // etc...
});
</code>```

In another file, I attempt to wrap a check around it before executing the function:

```<code>// Get event info
var clickEvent = $("#container").data('events').click[0];
var clickEvent_func = clickEvent.handler;
var clickEvent_selector = clickEvent.selector;

// Remove previous event and attach new one
$("#container").off("click", clickEvent_selector);
$("#container").on( "click", clickEvent_selector, function(e) {
    if (someValue) {
        clickEvent_func(e);
    } else {
        // Do something else
    }
});
</code>```

Due to the fact that there's no longer any context for the original function (I guess), I get an error on the first line when I try to run it. How do I get around this? Or is there a better way of accomplishing the check?

答:
As of jQuery 1.8 events were moved to $._data(element, 'events') and no longer stored on individual elements.

In order to pass in a new this you need to use function.call(thisArg, arg1, arg2, ...)

$('#container').on('click', '.editThis', function(e) {
  console.log('Original handler');
  console.log('event type:', e.type);
  console.log('button id:', this.id);
});

// store reference to original event handler before using `off()`
var clickEvt = $._data($("#container")[0], "events").click[0],
  selector = clickEvt.selector,
  originalHandler = clickEvt.handler;

var clickCount = 0;

$('#container')
  .off('click', selector, originalHandler)
  .on('click', selector, newHandler);

function newHandler(e) {
  if (clickCount) {
    // call original handler with current `this` and event object
    originalHandler.call(this, e);
  } else {
    console.log('First click')
    clickCount++;
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
  <button class="editThis" id="btn">
    Click me twice
  </button>
</div></code>```

Body:
I have a function in some uneditable file that binds a click handler to some items, as such:

$("#container").on("click", ".editThis", function(e) {
    var elemID = this.id;
    // etc...
});

In another file, I attempt to wrap a check around it before executing the function:

// Get event info
var clickEvent = $("#container").data('events').click[0];
var clickEvent_func = clickEvent.handler;
var clickEvent_selector = clickEvent.selector;

// Remove previous event and attach new one
$("#container").off("click", clickEvent_selector);
$("#container").on( "click", clickEvent_selector, function(e) {
    if (someValue) {
        clickEvent_func(e);
    } else {
        // Do something else
    }
});

Due to the fact that there's no longer any context for the original function (I guess), I get an error on the first line when I try to run it. How do I get around this? Or is there a better way of accomplishing the check?

Body:
As of jQuery 1.8 events were moved to $._data(element, 'events') and no longer stored on individual elements.

In order to pass in a new this you need to use function.call(thisArg, arg1, arg2, ...)

$('#container').on('click', '.editThis', function(e) {
  console.log('Original handler');
  console.log('event type:', e.type);
  console.log('button id:', this.id);
});

// store reference to original event handler before using `off()`
var clickEvt = $._data($("#container")[0], "events").click[0],
  selector = clickEvt.selector,
  originalHandler = clickEvt.handler;

var clickCount = 0;

$('#container')
  .off('click', selector, originalHandler)
  .on('click', selector, newHandler);

function newHandler(e) {
  if (clickCount) {
    // call original handler with current `this` and event object
    originalHandler.call(this, e);
  } else {
    console.log('First click')
    clickCount++;
  }

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="container">
  <button class="editThis" id="btn">
    Click me twice
  </button>
</div>


问:
How to get bearer token passed through header in rails?
In my rails application I'm able to get the Token Authorization: Token token='aUthEnTicAtIonTokeN' passed in header of request with

```<code>authenticate_with_http_token do |token, options|
 @auth_token = token
end
</code>```

but when I pass token as Authorization: Bearer token='aUthEnTicAtIonTokeN' getting token as nil above method.

how can i get bearer token passed through header in rails application?

答:
Your method will work correctly as it is, you just need to use the correct quotes in the request.

Using single quotes ' doesn't work, where as double quotes " does.

For reference, rails handles tokens from the Authorization: header in any of the following formats with the authenticate_with_http_token method:

```<code>Bearer "token_goes_here"
Bearer token_goes_here
Bearer token="token_goes_here"
Bearer token=token_goes_here
Token token="token_goes_here"
Token token=token_goes_here
Token "token_goes_here"
Token token_goes_here
</code>```

I'm sure this list is not exhaustive, but hopefully gives an idea of what is possible.

Body:
In my rails application I'm able to get the Token Authorization: Token token='aUthEnTicAtIonTokeN' passed in header of request with

authenticate_with_http_token do |token, options|
 @auth_token = token
end

but when I pass token as Authorization: Bearer token='aUthEnTicAtIonTokeN' getting token as nil above method.

how can i get bearer token passed through header in rails application?

Body:
Your method will work correctly as it is, you just need to use the correct quotes in the request.

Using single quotes ' doesn't work, where as double quotes " does.

For reference, rails handles tokens from the Authorization: header in any of the following formats with the authenticate_with_http_token method:

Bearer "token_goes_here"
Bearer token_goes_here
Bearer token="token_goes_here"
Bearer token=token_goes_here
Token token="token_goes_here"
Token token=token_goes_here
Token "token_goes_here"
Token token_goes_here

I'm sure this list is not exhaustive, but hopefully gives an idea of what is possible.


问:
find string with regular expression in load runner 12.5 extractor
I use load runner 12.5 to record script . I want to extract a value in response script and pass it to other so I want to find 17821107849674 in script with regular expression. what should I do?</p>

```<code>.
.
.
 AdfLoopbackUtils.runLoopback(
     9,
     '_afrLoop',
     '17821107849674',
     '_afrWindowMode',
     'Adf-Window-Id',
     '_afrPage',
     '',
     'w0',
     ';EBOXPORTALID=3fUCuSHtu2lAMvjhIqj5GMCRNrUTXZ_E0w-nQGzQxolJ4T38oItW!-939378123',
     '!',
     false,
</code>```

答:
Tell us more about the pattern?   Is it always the third element in the set?  Is it always preceded by "'_afrLoop'," or followed by ",'_afrWindowMode'?"

You potentially have several paths to collect the value, but understanding the patterns involved helps

Body:
I use load runner 12.5 to record script . I want to extract a value in response script and pass it to other so I want to find 17821107849674 in script with regular expression. what should I do?

.
.
.
 AdfLoopbackUtils.runLoopback(
     9,
     '_afrLoop',
     '17821107849674',
     '_afrWindowMode',
     'Adf-Window-Id',
     '_afrPage',
     '',
     'w0',
     ';EBOXPORTALID=3fUCuSHtu2lAMvjhIqj5GMCRNrUTXZ_E0w-nQGzQxolJ4T38oItW!-939378123',
     '!',
     false,


问:
NLog Writing a GUID to database
I am having trouble inserting a guid Id each time a log is written in the database. It throws these errors:

```<code>Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in NLog.dll
</code>```

What I have so far:

```<code>    @"INSERT INTO [dbo].[Nlogs]
            (Id,Message)
            values
            (@Id,@Message)";

    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Id", Guid.NewGuid().ToString()));
    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));
</code>```

Thanks.

答:
How would I get it to create a new Guid for each entry?

Use ${guid} or event properties

for example:

<target name="db"
        xsi:type="Database"
        connectionStringName="NLogConn"
        commandText="NSERT INTO [dbo].[Nlogs]
            (Id,Message)
            values
            (@Id,@Message)" >
  <parameter name="@Id"      layout="${guid}" dbType="Guid" />
  <parameter name="@Message" layout="${message}" />
</target>
```

Update: added dbType attribute to the example above, that would fix any conversion issues! You need NLog 4.6+ for that.

From the docs:

dbType - One of the values of DbType (e.g. "Int32", "Decimal", "DateTime"), or a value of DBType like prefixed with the property name, e.g. "SqlDbType.NChar" will set the property "SqlDbType" on "NChar". Another example: "NpgsqlDbType.Json" with NpgsqlParameter. Introduced in NLog 4.6

Title: NLog Writing a GUID to database

Body:
I am having trouble inserting a guid Id each time a log is written in the database. It throws these errors:

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll
Exception thrown: 'System.Data.SqlClient.SqlException' in NLog.dll

What I have so far:

    @"INSERT INTO [dbo].[Nlogs]
            (Id,Message)
            values
            (@Id,@Message)";

    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Id", Guid.NewGuid().ToString()));
    databaseTarget.Parameters.Add(new DatabaseParameterInfo("@Message", "${message}"));

Thanks.

Body:
How would I get it to create a new Guid for each entry?

Use ${guid} or event properties

for example:

<target name="db"
        xsi:type="Database"
        connectionStringName="NLogConn"
        commandText="NSERT INTO [dbo].[Nlogs]
            (Id,Message)
            values
            (@Id,@Message)" >
  <parameter name="@Id"      layout="${guid}" dbType="Guid" />
  <parameter name="@Message" layout="${message}" />
</target>

Update: added dbType attribute to the example above, that would fix any conversion issues! You need NLog 4.6+ for that.

From the docs:

dbType - One of the values of DbType (e.g. "Int32", "Decimal", "DateTime"), or a value of DBType like prefixed with the property name, e.g. "SqlDbType.NChar" will set the property "SqlDbType" on "NChar". Another example: "NpgsqlDbType.Json" with NpgsqlParameter. Introduced in NLog 4.6

ContentLicense: CC BY-SA 4.0


问:
Do x86 Android AVD's work on Linux on AMD?
I know that you cannot run the x86 images on Windows on AMD.  I am trying to see if I can run them on Linux though as the documentation implies.  I installed Ubuntu 1704.  I installed the latest Android Studio 2.3.3.  I created a default AVD for API 25 on x86.

I have also installed the following packages:

```<code>cpu-checker
lib32ncurses5
lib32z1
gcc-multilib
nvidia-current
</code>```

I have an AMD Phenom II 1045T:

```<code>vendor_id   : AuthenticAMD
cpu family  : 16
model       : 10
model name  : AMD Phenom(tm) II X6 1045T Processor
stepping    : 0
microcode   : 0x10000bf
cpu MHz     : 2000.000
cache size  : 512 KB
physical id : 0
siblings    : 6
core id     : 5
cpu cores   : 6
apicid      : 5
initial apicid  : 5
fpu     : yes
fpu_exception   : yes
cpuid level : 6
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt nodeid_msr cpb hw_pstate vmmcall npt lbrv svm_lock nrip_save pausefilter
</code>```

I have SVM turned on in my BIOS too.

I verified that KVM is ready:

```<code>my-linux:~$ emulator -accel-check
accel:
0
KVM (version 12) is installed and usable.
accel
</code>```

If I try to run it, I see the following:

```<code>my-linux:~$ emulator -avd Nexus_5X_API_25
[140469584095040]:ERROR:./android/qt/qt_setup.cpp:28:Qt library not found at ../emulator/lib64/qt/lib
Could not launch '../emulator/qemu/linux-x86_64/qemu-system-i386': No such file or directory
my-linux:~$ which emulator
/home/me/Android/Sdk/tools/emulator
</code>```

If I instead try the other emulator binary:

```<code>my-linux:~$ /home/me/Android/Sdk/emulator/emulator -avd Nexus_5X_API_25
emulator: WARNING: Host CPU is missing the following feature(s) required for x86 emulation: SSSE3
Hardware-accelerated emulation may not work properly!
emulator: ERROR: GPU emulation is disabled.
Only screen size of 800 X 1280 or smaller is supported when GPU emulation is disabled.
emulator: ERROR: GPU emulation is disabled: software gpu and screen too large
warning: host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]
warning: host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]
warning: host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]
</code>```

A black screen emulator appears that never seems to actually start.

Do either the x86 or x86-64 images run in accelerated mode on AMD under Ubuntu 17.04 for anyone?  Did you have to perform any additional steps or install any additional software?

Oh, here is my env setup:

```<code>export ANDROID_HOME=/home/me/Android/Sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
</code>```

I've googled around a ton on this and most posts I can find deal with trying to run the x86 emulator on Windows on AMD which is not supported and not what I am trying to do.

答:
It's a bug.  x86 API 22 image works just fine and seems accelerated, but not 23+. Others have seen it too:

https://issuetracker.google.com/issues/37076174

Body:
I know that you cannot run the x86 images on Windows on AMD.  I am trying to see if I can run them on Linux though as the documentation implies.  I installed Ubuntu 1704.  I installed the latest Android Studio 2.3.3.  I created a default AVD for API 25 on x86.

I have also installed the following packages:

cpu-checker
lib32ncurses5
lib32z1
gcc-multilib
nvidia-current

I have an AMD Phenom II 1045T:

vendor_id   : AuthenticAMD
cpu family  : 16
model       : 10
model name  : AMD Phenom(tm) II X6 1045T Processor
stepping    : 0
microcode   : 0x10000bf
cpu MHz     : 2000.000
cache size  : 512 KB
physical id : 0
siblings    : 6
core id     : 5
cpu cores   : 6
apicid      : 5
initial apicid  : 5
fpu     : yes
fpu_exception   : yes
cpuid level : 6
wp      : yes
flags       : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt nodeid_msr cpb hw_pstate vmmcall npt lbrv svm_lock nrip_save pausefilter

I have SVM turned on in my BIOS too.

I verified that KVM is ready:

my-linux:~$ emulator -accel-check
accel:
0
KVM (version 12) is installed and usable.
accel

If I try to run it, I see the following:

my-linux:~$ emulator -avd Nexus_5X_API_25
[140469584095040]:ERROR:./android/qt/qt_setup.cpp:28:Qt library not found at ../emulator/lib64/qt/lib
Could not launch '../emulator/qemu/linux-x86_64/qemu-system-i386': No such file or directory
my-linux:~$ which emulator
/home/me/Android/Sdk/tools/emulator

If I instead try the other emulator binary:

my-linux:~$ /home/me/Android/Sdk/emulator/emulator -avd Nexus_5X_API_25
emulator: WARNING: Host CPU is missing the following feature(s) required for x86 emulation: SSSE3
Hardware-accelerated emulation may not work properly!
emulator: ERROR: GPU emulation is disabled.
Only screen size of 800 X 1280 or smaller is supported when GPU emulation is disabled.
emulator: ERROR: GPU emulation is disabled: software gpu and screen too large
warning: host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]
warning: host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]
warning: host doesn't support requested feature: CPUID.01H:ECX.ssse3 [bit 9]

A black screen emulator appears that never seems to actually start.

Do either the x86 or x86-64 images run in accelerated mode on AMD under Ubuntu 17.04 for anyone?  Did you have to perform any additional steps or install any additional software?

Oh, here is my env setup:

export ANDROID_HOME=/home/me/Android/Sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

I've googled around a ton on this and most posts I can find deal with trying to run the x86 emulator on Windows on AMD which is not supported and not what I am trying to do.


问:
Can't send the correct value to the Database in C#
I have C# (WindowsForm) Application and I want to insert values into a database.

The information I insert into the database is the name of a product, his category and his cost, which is decimal(5,2).

However, when I try to insert a value like 1,90 , it only inserts 1,00. By that I want to say it only inserts the numbers before the comma, and then just add two zeros after the comma.

I already tried with this code:

```<code>decimal varcost = costprod.Value;
MySqlCommand command_addprod = new MySqlCommand("INSERT INTO products (name, cost, id_category) VALUES ('" + nameprod.Text + "','" + varcost + "'," + getidcat + ")");
</code>```

And this code:

```<code>decimal varcost = costprod.Value;
MySqlCommand command_addprod = new MySqlCommand("INSERT INTO products (name, cost, id_category) VALUES ('" + nameprod.Text + "'," + varcost + "," + getidcat + ")");
</code>```

The difference between this two codes is that the first one have quotation marks and the second one doesn't.

With the first code, it gives me the error I said. With the second code, it gives me an error like: "Column count doesn't match value count at row 1".

Every help is welcome!

Edit:

Now I tried with a different code:

```<code>string getidcat = catprod.SelectedItem.ToString();
        try
        {
            decimal varpreco = precoprod.Value;
            string varnome = nomeprod.Text;
            MySqlConnection mConn = new MySqlConnection("Persist Security Info=False;server = localhost; port=3307; database = startselling; user = root; password ='usbw';");
            var sqlCommand = "INSERT INTO produtos (designacao, preco_unitario, id_categoria) VALUES ('@nome', @preco, (select id_categoria FROM categorias WHERE designacao = @categoria)";

            //Create mysql command and pass sql query
            using (var command = new MySqlCommand(sqlCommand, mConn))
            {
                command.Parameters.AddWithValue("@nome", varnome);
                command.Parameters.AddWithValue("@preco", varpreco);
                command.Parameters.AddWithValue("@categoria", getidcat);
                mConn.Open();
                command.ExecuteNonQuery();
                mConn.Close();
            }

            MessageBox.Show("Succeeded");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
</code>```

(Some variables are different but don't bother with that)

I think I know where is the error, but I don't know how to solve it.

I think the error is on the variable "varpreco" because it contains values with a comma, and as this makes confusion with the commas of sql code, it gives an error.

Now maybe if I changed the comma from the variable to a dot, it should work. The problem is that I don't know how to use it.

If someone could help me, I would be grateful.

答:
The code below is how you would add parameters for your command</p>

```<code>MySqlCommand command_addprod = new MySqlCommand("INSERT INTO products (name, cost, id_category) VALUES (@nameprod, @varcost, @getidcat)";

command_addprod.Parameters.AddWithValue("@nameprod", nameprod.text);
command_addprod.Parameters.AddWithValue("@varcost", varcost);
command_addprod.Parameters.AddWithValue("@getidcat", getidcat);
</code>```

Body:
I have C# (WindowsForm) Application and I want to insert values into a database.

The information I insert into the database is the name of a product, his category and his cost, which is decimal(5,2).

However, when I try to insert a value like 1,90 , it only inserts 1,00. By that I want to say it only inserts the numbers before the comma, and then just add two zeros after the comma.

I already tried with this code:

decimal varcost = costprod.Value;
MySqlCommand command_addprod = new MySqlCommand("INSERT INTO products (name, cost, id_category) VALUES ('" + nameprod.Text + "','" + varcost + "'," + getidcat + ")");

And this code:

decimal varcost = costprod.Value;
MySqlCommand command_addprod = new MySqlCommand("INSERT INTO products (name, cost, id_category) VALUES ('" + nameprod.Text + "'," + varcost + "," + getidcat + ")");

The difference between this two codes is that the first one have quotation marks and the second one doesn't.

With the first code, it gives me the error I said. With the second code, it gives me an error like: "Column count doesn't match value count at row 1".

Every help is welcome!

Edit:

Now I tried with a different code:

string getidcat = catprod.SelectedItem.ToString();
        try
        {
            decimal varpreco = precoprod.Value;
            string varnome = nomeprod.Text;
            MySqlConnection mConn = new MySqlConnection("Persist Security Info=False;server = localhost; port=3307; database = startselling; user = root; password ='usbw';");
            var sqlCommand = "INSERT INTO produtos (designacao, preco_unitario, id_categoria) VALUES ('@nome', @preco, (select id_categoria FROM categorias WHERE designacao = @categoria)";

            //Create mysql command and pass sql query
            using (var command = new MySqlCommand(sqlCommand, mConn))
            {
                command.Parameters.AddWithValue("@nome", varnome);
                command.Parameters.AddWithValue("@preco", varpreco);
                command.Parameters.AddWithValue("@categoria", getidcat);
                mConn.Open();
                command.ExecuteNonQuery();
                mConn.Close();
            }

            MessageBox.Show("Succeeded");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

(Some variables are different but don't bother with that)

I think I know where is the error, but I don't know how to solve it.

I think the error is on the variable "varpreco" because it contains values with a comma, and as this makes confusion with the commas of sql code, it gives an error.

Now maybe if I changed the comma from the variable to a dot, it should work. The problem is that I don't know how to use it.

If someone could help me, I would be grateful.

Body:
The code below is how you would add parameters for your command

MySqlCommand command_addprod = new MySqlCommand("INSERT INTO products (name, cost, id_category) VALUES (@nameprod, @varcost, @getidcat)";

command_addprod.Parameters.AddWithValue("@nameprod", nameprod.text);
command_addprod.Parameters.AddWithValue("@varcost", varcost);
command_addprod.Parameters.AddWithValue("@getidcat", getidcat);


问:
Scala: Requiring members on companion objects of abstract classes
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

```<code>abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false
</code>```

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

答:
It is not possible to do what you are asking.

You are asking about overriding members of object. objects in scala are equivalent of static classes in Java with all members being static.
Companion object with its class would be a class with both static and none static members in Java.
You can't override them. You can't do it in Java and you can't do it in Scala.

Alternative solution:

Just define tastyCultivars in class.

```<code>abstract class Fruit(cultivar: String) {
  val tastyCultivars: Set[String]
  def isTastyCultivar(): Boolean = tastyCultivars.contains(cultivar)
}

class Apple(cultivar: String) extends Fruit(cultivar) {

    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

println("Should return true, is " + a1.isTastyCultivar())
println("Should return false, is " +a2.isTastyCultivar())

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

println("Should return true, is " +t1.isTastyCultivar())
println("Should return false, is " +t2.isTastyCultivar())
</code>```

Output:

```<code>$ scala fruit.scala
Should return true, is true
Should return false, is false
Should return true, is true
Should return false, is false
</code>```

Body:
I'd like to create an abstract class, and be able to add members to it that reference attributes of the implementing class's companion object.  Something like this (Scala pseudocode):

abstract class Fruit(cultivar: String) {
    // How do I reference the implementing class's companion object here?
    def isTastyCultivar(): Boolean = Fruit.tastyCultivars.contains(cultivar)
}

// how do I implement what I am thinking of as "the abstract companion object"
abstract object Fruit {
    val tastyCultivars: Set[String]  // must be implemented
                                     // by the concrete object
}

class Apple(cultivar: String) extends Fruit(cultivar) {

}

object Apple extends Fruit{ // presumably this is not correct;
                            // it needs to extend the FruitObject
                            // or whatever it is
    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

}

object Tomato extends Fruit{
    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

a1.isTastyCultivar()  // should return true
a2.isTastyCultivar()  // should return false

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

t1.isTastyCultivar() // should return true
t2.isTastyCultivar() // should return false

Sorry if this is a dumb question, or if asked previously (I'm not confident in how to word this question so I couldn't easily search for it).  Thanks in advance!

Body:
It is not possible to do what you are asking.

You are asking about overriding members of object. objects in scala are equivalent of static classes in Java with all members being static.
Companion object with its class would be a class with both static and none static members in Java.
You can't override them. You can't do it in Java and you can't do it in Scala.

Alternative solution:

Just define tastyCultivars in class.

abstract class Fruit(cultivar: String) {
  val tastyCultivars: Set[String]
  def isTastyCultivar(): Boolean = tastyCultivars.contains(cultivar)
}

class Apple(cultivar: String) extends Fruit(cultivar) {

    val tastyCultivars: Set[String] = Set("Red Delicious", "Granny Smith")
}

class Tomato(cultivar: String) extends Fruit(cultivar) {

    val tastyCultivars = Set("Roma")
}

val a1 = new Apple("Red Delicious")
val a2 = new Apple("Honeycrisp")

println("Should return true, is " + a1.isTastyCultivar())
println("Should return false, is " +a2.isTastyCultivar())

val t1 = new Tomato("Roma")
val t2 = new Tomato("San Marzano")

println("Should return true, is " +t1.isTastyCultivar())
println("Should return false, is " +t2.isTastyCultivar())

Output:

$ scala fruit.scala
Should return true, is true
Should return false, is false
Should return true, is true
Should return false, is false


问:
How to set specific row to one and rest all others to zero?
How to set a specific row to one and all other entries of a matrix to zero?

For example let us consider the matrix below

```<code>Matrix M = 0 0 0
           1 0 5
           2 0 4
           5 6 8
           0 3 10
</code>```

I want to set for example row number 4 to ones like in the Result and the rest to zero.

```<code>Result = 0 0 0
         0 0 0
         0 0 0
         1 1 1
         0 0 0
</code>```

How can this be done?

答:
Given the simplicity of the task, I would rather recommend creating a new matrix. Just use the size of the original matrix. Assume you have matrix A.

```<code>B = zeros(size(A));
</code>```

This will create a matrix B of all 0s of the same size as A. Then, if you need to change the value of one of the rows (e.g. row 4 in your example)

```<code>B(4,:)=1;
</code>```

Will assign 1s to all the values in that row. I would recommend reading this page on matrix indexing in matlab before asking any further questions ;)

Body:
How to set a specific row to one and all other entries of a matrix to zero?

For example let us consider the matrix below

Matrix M = 0 0 0
           1 0 5
           2 0 4
           5 6 8
           0 3 10

I want to set for example row number 4 to ones like in the Result and the rest to zero.

Result = 0 0 0
         0 0 0
         0 0 0
         1 1 1
         0 0 0

How can this be done?

Body:
Given the simplicity of the task, I would rather recommend creating a new matrix. Just use the size of the original matrix. Assume you have matrix A.

B = zeros(size(A));

This will create a matrix B of all 0s of the same size as A. Then, if you need to change the value of one of the rows (e.g. row 4 in your example)

B(4,:)=1;

Will assign 1s to all the values in that row. I would recommend reading this page on matrix indexing in matlab before asking any further questions ;)


问:
Mock Ajax (Reactjs + Mobx)
I want to make some fake my ajax calls so when on localhost I can bring back dummy data from a fake method instead of doing real calls to my server(where the structure might not exist).

What is the best way to do this in reactjs + mobx?

I was thinking of making a fake store as this is where all my actions are with my ajax calls but that would involve always making the entire store with all functions.

I then though of maybe extracting out the ajax calls from the store and then mockup those calls but I am not sure the best way to do that.

答:
Another alternative to the already proposed is to implement rapidly a node server that runs locally (in development mode) and that responds with some dummy JSON data for each endpoint.

That way you keep your frontend code clean, regardless the tech stack used, and delegate the implementation details on your server. The only thing required in your frontend (assuming you are using a build tool like webpack or alike to bundle up your JavaScript) is to use environmental variables to use your local or prod server endpoints.

This is typically done using this webpack plugin: https://webpack.js.org/plugins/environment-plugin/

```<code>let apiEndpoint;
if (process.env.NODE_ENV === 'production') {
  apiEndpoint = 'https://yourProdServer/api'
} else {
  apiEndpoint = 'https://localhost:8080/api'
}
</code>```

Then in your npm scripts configure something like:

```<code>"dev": "webpack",
"prod": "NODE_ENV=production webpack"
</code>```

Title: Mock Ajax (Reactjs + Mobx)

Body:
Another alternative to the already proposed is to implement rapidly a node server that runs locally (in development mode) and that responds with some dummy JSON data for each endpoint.

That way you keep your frontend code clean, regardless the tech stack used, and delegate the implementation details on your server. The only thing required in your frontend (assuming you are using a build tool like webpack or alike to bundle up your JavaScript) is to use environmental variables to use your local or prod server endpoints.

This is typically done using this webpack plugin: https://webpack.js.org/plugins/environment-plugin/

let apiEndpoint;
if (process.env.NODE_ENV === 'production') {
  apiEndpoint = 'https://yourProdServer/api'
} else {
  apiEndpoint = 'https://localhost:8080/api'
}

Then in your npm scripts configure something like:

"dev": "webpack",
"prod": "NODE_ENV=production webpack"


问:
Searching through nested list
```<code>from nltk import word_tokenize

list_1 = [a, b, c, d, e, f]
list_2 = [[aa, bb, cc], [dd, ee], [ff], [gg, hh, ii, jj], [kk, ll], [mm, nn, oo]]
text = 'The lazy aa moves along the hh'
text_token = word_tokenize(text)

for word in text:
     if word in [j for i in list_2 for j in i]:
        print(list_2.index(word))
     else:
        print(word)

ValueError: 'hh' is not in list
</code>```

I'm attempting textual analysis on large bodies of French text. I have already tried using the NLTK Stemmer and it doesn't stem a significant amount of words that I'm analyzing.

I'm not very familiar with python or any of the other coding languages (I'm coming from the Humanities) so I'm also not entirely sure as to how to search for the issue that I'm looking for, and I apologize in  if this question is either redundant or easily solved.

I've attempted to approach this by finding a list of French words with their various grammatical forms. I already complied the list into two separate lists: the first list contains the root of the word that I would like the others to take on, while the second list is the variant forms that the item in the first list can take on. I've made it so that both lists correspond to each other. For example, list_1[0] would correspond to the words in list_2[0]. As a result, there are a lot of nested lists of different lengths within list_2.

My issue seems to arise when I'm searching through nested lists. I have to iterate through text_token to check if any of the words in text_token exist in list_2. If text_token exists in list_2 then find misc = list_2.index(word) . After finding misc, I want to replace word with search list_1[misc]. However, after confirming that word exists in list_2, I try to print(list_2.index(word)) to see if it works, but i keep receiving ValueError: 'hh' is not in list I'm not entirely sure how to cycle through nested lists after already having done so in order to avoid this error, because I'm assuming that when I search through the definitions a second time, it doesn't see the nested list as multiple items. I've tried to circumvent this by trying another list comprehension after checking it in the original one, but it ends up returning individual letters. I've also tried making these two lists into a dictionary, but I can't seem to figure out how to yield .keys() from .values().

答:
If you want to obtain the index of the sublist in the main list, you can do:

```<code>for word in text:
     for index, sublist in enumerate(list_2):
         if word in sublist:
             print(index)
             break
     else:
        print(word)
</code>```

enumerate(list_2) iterates on the elements of list_2, which are your sublists, and yields at each step the index of the sublist and the sublist itself.

Then, we check if the word is in one of the sublists.

If this is the case, we print the index and break out of the inner for loop.

If we didn't find the word in any of the sublists, we execute the else part of the for loop and print the word.

Title: Searching through nested list

Body:
from nltk import word_tokenize

list_1 = [a, b, c, d, e, f]
list_2 = [[aa, bb, cc], [dd, ee], [ff], [gg, hh, ii, jj], [kk, ll], [mm, nn, oo]]
text = 'The lazy aa moves along the hh'
text_token = word_tokenize(text)

for word in text:
     if word in [j for i in list_2 for j in i]:
        print(list_2.index(word))
     else:
        print(word)

ValueError: 'hh' is not in list

I'm attempting textual analysis on large bodies of French text. I have already tried using the NLTK Stemmer and it doesn't stem a significant amount of words that I'm analyzing.

I'm not very familiar with python or any of the other coding languages (I'm coming from the Humanities) so I'm also not entirely sure as to how to search for the issue that I'm looking for, and I apologize in  if this question is either redundant or easily solved.

I've attempted to approach this by finding a list of French words with their various grammatical forms. I already complied the list into two separate lists: the first list contains the root of the word that I would like the others to take on, while the second list is the variant forms that the item in the first list can take on. I've made it so that both lists correspond to each other. For example, list_1[0] would correspond to the words in list_2[0]. As a result, there are a lot of nested lists of different lengths within list_2.

My issue seems to arise when I'm searching through nested lists. I have to iterate through text_token to check if any of the words in text_token exist in list_2. If text_token exists in list_2 then find misc = list_2.index(word) . After finding misc, I want to replace word with search list_1[misc]. However, after confirming that word exists in list_2, I try to print(list_2.index(word)) to see if it works, but i keep receiving ValueError: 'hh' is not in list I'm not entirely sure how to cycle through nested lists after already having done so in order to avoid this error, because I'm assuming that when I search through the definitions a second time, it doesn't see the nested list as multiple items. I've tried to circumvent this by trying another list comprehension after checking it in the original one, but it ends up returning individual letters. I've also tried making these two lists into a dictionary, but I can't seem to figure out how to yield .keys() from .values().

Body:
If you want to obtain the index of the sublist in the main list, you can do:

for word in text:
     for index, sublist in enumerate(list_2):
         if word in sublist:
             print(index)
             break
     else:
        print(word)

enumerate(list_2) iterates on the elements of list_2, which are your sublists, and yields at each step the index of the sublist and the sublist itself.

Then, we check if the word is in one of the sublists.

If this is the case, we print the index and break out of the inner for loop.

If we didn't find the word in any of the sublists, we execute the else part of the for loop and print the word.


问:
Google maps, cannot place marker
I have been unable to play down even a basic marker at the LatLng position and I am unsure on how to fix it. Whenever I try to place a marker, the whole div tag and map goes away.</p>

```<code><div id="googleMap" style="width:100%;height:400px;"></div>

<script>
function myMap() {
var mapProp= {
    center:new google.maps.LatLng(-36.934601, 174.915836),
    zoom:15,
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Hello World!'
        });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDRqDMSVnEAKKE7vPz3cWiJ9Ge6lLLBtQ4&callback=myMap"></script>
</div>
</code>```

答:
You have to define myLatLng

```<code>var myLatLng = {lat:-36.934601, lng: 174.915836};
</code>```

The complete code becomes:

```<code><div id="googleMap" style="width:100%;height:400px;"></div>

<script>
function myMap() {
var mapProp= {
    center:new google.maps.LatLng(-36.934601, 174.915836),
    zoom:15,
};
var myLatLng = {lat:-36.934601, lng: 174.915836};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Hello World!'
        });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDRqDMSVnEAKKE7vPz3cWiJ9Ge6lLLBtQ4&callback=myMap"></script>
</div>
</code>```

Title: Google maps, cannot place marker

Body:
You have to define myLatLng

var myLatLng = {lat:-36.934601, lng: 174.915836};

The complete code becomes:

<div id="googleMap" style="width:100%;height:400px;"></div>

<script>
function myMap() {
var mapProp= {
    center:new google.maps.LatLng(-36.934601, 174.915836),
    zoom:15,
};
var myLatLng = {lat:-36.934601, lng: 174.915836};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({
          position: myLatLng,
          map: map,
          title: 'Hello World!'
        });
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDRqDMSVnEAKKE7vPz3cWiJ9Ge6lLLBtQ4&callback=myMap"></script>
</div>