问:
JPA & Hibernate: Eager loading performing subsequent queries to fetch all data, instead of doing it in just one query
I have the following doubt. I would like to know why when using JPA and Hibernate, when performing an Eager loading in a ManyToOne or OneToMany relationship, it calls the DB in order to obtain the Entity information but additionally, produces subsequent queries to fetch every child.

On the other side, when using a query with JOIN FETCH it performs the query as I would expect it to be, taking the information all at once, since the fetchType is denoted as "EAGER".

Here it is a simple example:

I have the Class Student which has ManyToOne relationship with the Class Classroom.

```<code>@Entity
@Table(name = "STUDENT")
public class Student {

@ManyToOne(optional = true, fetch = FetchType.EAGER)
        @JoinColumn(name = "ClassroomID")
        private Classroom mainClass;
</code>```

In the other side there is the class named Classroom as follows:

```<code>@Entity
public class Classroom {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "mainClass", fetch = FetchType.EAGER)
private List<Student> studentsList;
</code>```

When obtaining the Classroom object, it performs one query to obtain the information from itself and subsequent queries to obtain the information of each student contained in the studentsList for every classRoom object.

First query:

```<code>Hibernate:
/* SELECT
         r
     FROM
         Classroom r
     LEFT JOIN
         r.classStudents */

     select
         classroom0_.id as id1_0_,
         classroom0_.number as number2_0_
     from
         Classroom classroom0_
     left outer join
         STUDENT classstude1_
             on classroom0_.id=classstude1_.ClassroomID
</code>```

And then it performs the next query as many times as Students assigned to each classroom.

```<code>  Hibernate:
      /* load one-to-many com.hw.access.Classroom.classStudents */
      select
          classstude0_.ClassroomID as Classroo4_0_1_,
          classstude0_.id as id1_1_1_,
          classstude0_.id as id1_1_0_,
          classstude0_.FIRST_NAME as FIRST_NA2_1_0_,
          classstude0_.LAST_NAME as LAST_NAM3_1_0_,
          classstude0_.ClassroomID as Classroo4_1_0_
      from
          STUDENT classstude0_
      where
          classstude0_.ClassroomID=?
</code>```

The question is: Why doesn't it takes the Information all at once? Why doesn't it takes the information in just one query? As it is already performing the Join clause there.

Why just when adding Fetch explicitly in the query, it does what it is requested?

For example:

```<code>SELECT
         r
     FROM
         Classroom r
     LEFT JOIN FETCH
         r.classStudents */
</code>```

And then, the output query does takes all the information in just one query:

```<code>Hibernate:

        select
              classroom0_.id as id1_0_0_,
              classstude1_.id as id1_1_1_,
              classroom0_.number as number2_0_0_,
              classstude1_.FIRST_NAME as FIRST_NA2_1_1_,
              classstude1_.LAST_NAME as LAST_NAM3_1_1_,
              classstude1_.ClassroomID as Classroo4_1_1_,
              classstude1_.ClassroomID as Classroo4_0_0__,
              classstude1_.id as id1_1_0__
          from
              Classroom classroom0_
          left outer join
              STUDENT classstude1_
                  on classroom0_.id=classstude1_.ClassroomID
</code>```

答:
I found it described in https://vladmihalcea.com/eager-fetching-is-a-code-smell/
under EAGER fetching inconsistencies:

Both JPQL and Criteria queries default to select fetching, therefore issuing a secondary select for each individual EAGER association. The larger the associations’ number, the more additional individual SELECTS, the more it will affect our application performance.

Also, note that Hibernate similarly ignoreg fetching annotations for HQL queries:
https://developer.jboss.org/wiki/HibernateFAQ-AdvancedProblems#jive_content_id_Hibernate_ignores_my_outerjointrue_or_fetchjoin_setting_and_fetches_an_association_lazily_using_n1_selects

Hibernate ignores my outer-join="true" or fetch="join" setting and fetches an association lazily, using n+1 selects!

HQL queries always ignore the setting for outer-join or fetch="join" defined in mapping metadata. This setting applies only to associations fetched using get() or load(), Criteria queries, and graph navigation. If you need to enable eager fetching for a HQL query, use an explicit LEFT JOIN FETCH.

Body:
I have the following doubt. I would like to know why when using JPA and Hibernate, when performing an Eager loading in a ManyToOne or OneToMany relationship, it calls the DB in order to obtain the Entity information but additionally, produces subsequent queries to fetch every child.

On the other side, when using a query with JOIN FETCH it performs the query as I would expect it to be, taking the information all at once, since the fetchType is denoted as "EAGER".

Here it is a simple example:

I have the Class Student which has ManyToOne relationship with the Class Classroom.

@Entity
@Table(name = "STUDENT")
public class Student {

@ManyToOne(optional = true, fetch = FetchType.EAGER)
        @JoinColumn(name = "ClassroomID")
        private Classroom mainClass;

In the other side there is the class named Classroom as follows:

@Entity
public class Classroom {

@OneToMany(cascade = CascadeType.ALL, mappedBy = "mainClass", fetch = FetchType.EAGER)
private List<Student> studentsList;

When obtaining the Classroom object, it performs one query to obtain the information from itself and subsequent queries to obtain the information of each student contained in the studentsList for every classRoom object.

First query:

Hibernate:
/* SELECT
         r
     FROM
         Classroom r
     LEFT JOIN
         r.classStudents */

     select
         classroom0_.id as id1_0_,
         classroom0_.number as number2_0_
     from
         Classroom classroom0_
     left outer join
         STUDENT classstude1_
             on classroom0_.id=classstude1_.ClassroomID

And then it performs the next query as many times as Students assigned to each classroom.

  Hibernate:
      /* load one-to-many com.hw.access.Classroom.classStudents */
      select
          classstude0_.ClassroomID as Classroo4_0_1_,
          classstude0_.id as id1_1_1_,
          classstude0_.id as id1_1_0_,
          classstude0_.FIRST_NAME as FIRST_NA2_1_0_,
          classstude0_.LAST_NAME as LAST_NAM3_1_0_,
          classstude0_.ClassroomID as Classroo4_1_0_
      from
          STUDENT classstude0_
      where
          classstude0_.ClassroomID=?

The question is: Why doesn't it takes the Information all at once? Why doesn't it takes the information in just one query? As it is already performing the Join clause there.

Why just when adding Fetch explicitly in the query, it does what it is requested?

For example:

SELECT
         r
     FROM
         Classroom r
     LEFT JOIN FETCH
         r.classStudents */

And then, the output query does takes all the information in just one query:

Hibernate:

        select
              classroom0_.id as id1_0_0_,
              classstude1_.id as id1_1_1_,
              classroom0_.number as number2_0_0_,
              classstude1_.FIRST_NAME as FIRST_NA2_1_1_,
              classstude1_.LAST_NAME as LAST_NAM3_1_1_,
              classstude1_.ClassroomID as Classroo4_1_1_,
              classstude1_.ClassroomID as Classroo4_0_0__,
              classstude1_.id as id1_1_0__
          from
              Classroom classroom0_
          left outer join
              STUDENT classstude1_
                  on classroom0_.id=classstude1_.ClassroomID


来源: stackexchange

问:
What is the difference between input_shape and input_dim in keras?
Currently i am learning deep learning and stumbled upon these confusion:
when to use input_shape and input_dim parameter.

shape of my data is (798,9) and these has 8 input variable and 1 output variable so my question is when making a sequential model whats the difference between:

```<code>model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=12,input_shape=(6912,),activation='relu' ))
model.add(tf.keras.layers.Dense(32,activation='relu'))
</code>```

AND

```<code>model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=12,input_dim=8,activation='relu' ))
model.add(tf.keras.layers.Dense(32,activation='relu'))
</code>```

so can anyone explain in detail about how to choose input_size and input_dim and whats the difference between it?

答:
You need input_shape = (8,), which is exactly the same as input_dim = 8.

Your final Dense, naturally, needs to have 1 unit only. For regression you might want activation = 'linear' in the last layer and for classification you will want 'sigmoid'.

For higher dimension data, you will need input_shape = (dim_1, dim2, ...).

ContentLicense: CC BY-SA 4.0

Body:
Currently i am learning deep learning and stumbled upon these confusion:
when to use input_shape and input_dim parameter.

shape of my data is (798,9) and these has 8 input variable and 1 output variable so my question is when making a sequential model whats the difference between:

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=12,input_shape=(6912,),activation='relu' ))
model.add(tf.keras.layers.Dense(32,activation='relu'))

AND

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(units=12,input_dim=8,activation='relu' ))
model.add(tf.keras.layers.Dense(32,activation='relu'))

so can anyone explain in detail about how to choose input_size and input_dim and whats the difference between it?


问:
Can I change the appearance of an html image during hover without a second image?
Is there a way to change the appearance of an icon (ie. contrast / luminosity) when I hover the cursor, without requiring a second image file (or without requiring a hidden portion of the image)?</p>

答:
Here's some code to play with. Basic idea: put all possible states of the picture into one big image, set a "window size", that's smaller than the image; move the window around using background-position.

#test {
  display: block;
  width: 250px;  /* window */
  height: 337px; /*  size  */
  background: url(http://vi.sualize.us/thumbs/08/09/01/fashion,indie,inspiration,portrait-f825c152cc04c3dbbb6a38174a32a00f_h.jpg) no-repeat; /* put the image */
  border: 1px solid red; /* for debugging */
  text-indent: -1000px; /* hide the text */
}

#test:hover {
  background-position: -250px 0; /* on mouse over move the window to a different part of the image */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>a button</code>```

OwnerDisplayName: Brent Nesbitt

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brent Nesbitt

Body:
Here's some code to play with. Basic idea: put all possible states of the picture into one big image, set a "window size", that's smaller than the image; move the window around using background-position.

#test {
  display: block;
  width: 250px;  /* window */
  height: 337px; /*  size  */
  background: url(http://vi.sualize.us/thumbs/08/09/01/fashion,indie,inspiration,portrait-f825c152cc04c3dbbb6a38174a32a00f_h.jpg) no-repeat; /* put the image */
  border: 1px solid red; /* for debugging */
  text-indent: -1000px; /* hide the text */
}

#test:hover {
  background-position: -250px 0; /* on mouse over move the window to a different part of the image */
}

<a href="#" id="test">a button</a>

ContentLicense: CC BY-SA 3.0


问:
How do you fight design complexity?
I often find myself fighting overengineering -- the person in charge of designing the software comes up with an architecture that's, way, way overcomplicated.

It's all fine and dandy to have all the esoteric features that users will never know about and get that sense of achievement when you're doing something that all the magazine articles are telling you is the latest, cool thing, but we are going to spend half of our  engineering time on this monument to our cleverness, and not, you know, the actual product that our users need and upper management expects to be completed within a reasonable or at least a bounded time frame.

And you'll probably just have to revert back to the simpler solution anyway when you start running out of time, that is, if you get that chance.

We've all heard the refrain: Keep It Simple, Stupid™.

How do you fight with overcomplexity in your team?

One example I've had to work with repeatedly lately is when the decision has been made to go to a fully denormalized database design rather than an RDBMS. "because it's faster!" Fully denormalized databases are really hard to get right, and are only appropriate for really specialized data problems like Flickr or ebay, and which can be extremely expensive in terms of developer time relative to the rest of your development.

答: Don't try to do everything at a stretch. Break every problem/task into manageable chunks. Then prioritize, keeping KISS and YAGNI in mind. This will help you focus on building what you need. If you've done it right, you'll have a good core you can add to later, given time, money, resources and inspiration.

OwnerDisplayName: ʞɔıu

Title: How do you fight design complexity?

LastEditorDisplayName: philippe

OwnerDisplayName: Clayton


问:
UTF-8 only in Grails 1.1 database tables
When using Grails 1.1 together with a MySQL the charsets of the auto-generated database tables seem to default to ISO-8859-1. I'd rather have everything stored as pure UTF-8. Is that possible?

From the auto-generated database definitions:

```<code>ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
</code>```

Note the "latin1" part.

A work-around that works for Grails 1.0 is described here. This work-arounds does not appear to work when using Grails 1.1. The dataSource.dialect parameter seems to be ignored.

答:
Here is the solution to same problem on StackOverflow:
UTF-8 only in Grails database tables

It have worked for me, however it's not elegant...

Body:
When using Grails 1.1 together with a MySQL the charsets of the auto-generated database tables seem to default to ISO-8859-1. I'd rather have everything stored as pure UTF-8. Is that possible?

From the auto-generated database definitions:

ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

Note the "latin1" part.

A work-around that works for Grails 1.0 is described here. This work-arounds does not appear to work when using Grails 1.1. The dataSource.dialect parameter seems to be ignored.


问:
Why this code works well in MySQL but not in SQL Server?
This is a question in Leetcode: https://leetcode.com/problems/delete-duplicate-emails/solution/

Basically the question asks to delete duplicate emails and keep the one that has the minumal index.

My code is the following one, and I firstly ran it in SQL Server mode, and it shows "Internal Error". But it has passed in MySQL mode. Why does this happen? Are there any syntax differences between them shown in this case? Thanks.

```<code>delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);
</code>```

答:
Looks good to me. Perhaps

```<code>DELETE FROM Person
WHERE Id not in ( Select Id FROM
      (SELECT Email,
        MIN(Id) as Id, COUNT(*) as N
        FROM Person
        GROUP BY Email
        HAVING COUNT(*) > 1) as temp
);
</code>```

Make sure to run the inner SELECT by itself to see it's the same schema.

Body:
This is a question in Leetcode: https://leetcode.com/problems/delete-duplicate-emails/solution/

Basically the question asks to delete duplicate emails and keep the one that has the minumal index.

My code is the following one, and I firstly ran it in SQL Server mode, and it shows "Internal Error". But it has passed in MySQL mode. Why does this happen? Are there any syntax differences between them shown in this case? Thanks.

delete from Person
where Id not in (
select temp.minimum from
(select min(Id) as minimum from Person group by Email) as temp
);

Body:
Looks good to me. Perhaps

DELETE FROM Person
WHERE Id not in ( Select Id FROM
      (SELECT Email,
        MIN(Id) as Id, COUNT(*) as N
        FROM Person
        GROUP BY Email
        HAVING COUNT(*) > 1) as temp
);

Make sure to run the inner SELECT by itself to see it's the same schema.


问:
Daily Coding Problem 260 : Reconstruct a jumbled array - Intuition?
I'm going through the question below.

The sequence [0, 1, ..., N] has been jumbled, and the only clue you have for its order is an array representing whether each number is larger or smaller than the last. Given this information, reconstruct an array that is consistent with it.

For example, given [None, +, +, -, +], you could return [1, 2, 3, 0, 4].

I went through the solution on this post but still unable to understand it as to why this solution works. I don't think I would be able to come up with the solution if I had this in front of me during an interview. Can anyone explain the intuition behind it? Thanks in advance!

答:
The idea is to produce a permutation of [0,1...N] which will follow the pattern of [+,-...]. There are many permutations which will be applicable, it isn't a single one. For instance, look the the example provided:

[None, +, +, -, +], you could return [1, 2, 3, 0, 4].

But you also could have returned other solutions, just as valid: [2,3,4,0,1], [0,3,4,1,2] are also solutions. The only concern is that you need to have the first number having at least two numbers above it for positions [1],[2], and leave one number in the end which is lower then the one before and after it.

So the question isn't finding the one and only pattern which is scrambled, but to produce any permutation which will work with these rules.

This algorithm answers two questions for the next member of the list: get a number who’s both higher/lower from previous - and get a number who hasn’t been used yet. It takes a starting point number and essentially create two lists: an ascending list for the ‘+’ and a descending list for the ‘-‘. This way we guarantee that the next member is higher/lower than the previous one (because it’s in fact higher/lower than all previous members, a stricter condition than the one required) and for the same reason we know this number wasn’t used before.

So the intuition of the referenced algorithm is to start with a referenced number and work your way through. Let's assume we start from 0. The first place we put 0+1, which is 1. we keep 0 as our lowest, 1 as the highest.

```<code>l[0] h[1] list[1]
</code>```

the next symbol is '+' so we take the highest number and raise it by one to 2, and update both the list with a new member and the highest number.

```<code>l[0] h[2] list [1,2]
</code>```

The next symbol is '+' again, and so:

```<code>l[0] h[3] list [1,2,3]
</code>```

The next symbol is '-' and so we have to put in our 0. Note that if the next symbol will be - we will have to stop, since we have no lower to produce.

```<code>l[0] h[3] list [1,2,3,0]
</code>```

Luckily for us, we've chosen well and the last symbol is '+', so we can put our 4 and call is a day.

```<code>l[0] h[4] list [1,2,3,0,4]
</code>```

This is not necessarily the smartest solution, as it can never know if the original number will solve the sequence, and always progresses by 1. That means that for some patterns [+,-...] it will not be able to find a solution. But for the pattern provided it works well with 0 as the initial starting point. If we chose the number 1 is would also work and produce [2,3,4,0,1], but for 2 and above it will fail. It will never produce the solution [0,3,4,1,2].

I hope this helps understanding the approach.

Body:
The idea is to produce a permutation of [0,1...N] which will follow the pattern of [+,-...]. There are many permutations which will be applicable, it isn't a single one. For instance, look the the example provided:

[None, +, +, -, +], you could return [1, 2, 3, 0, 4].

But you also could have returned other solutions, just as valid: [2,3,4,0,1], [0,3,4,1,2] are also solutions. The only concern is that you need to have the first number having at least two numbers above it for positions [1],[2], and leave one number in the end which is lower then the one before and after it.

So the question isn't finding the one and only pattern which is scrambled, but to produce any permutation which will work with these rules.

This algorithm answers two questions for the next member of the list: get a number who’s both higher/lower from previous - and get a number who hasn’t been used yet. It takes a starting point number and essentially create two lists: an ascending list for the ‘+’ and a descending list for the ‘-‘. This way we guarantee that the next member is higher/lower than the previous one (because it’s in fact higher/lower than all previous members, a stricter condition than the one required) and for the same reason we know this number wasn’t used before.

So the intuition of the referenced algorithm is to start with a referenced number and work your way through. Let's assume we start from 0. The first place we put 0+1, which is 1. we keep 0 as our lowest, 1 as the highest.

l[0] h[1] list[1]

the next symbol is '+' so we take the highest number and raise it by one to 2, and update both the list with a new member and the highest number.

l[0] h[2] list [1,2]

The next symbol is '+' again, and so:

l[0] h[3] list [1,2,3]

The next symbol is '-' and so we have to put in our 0. Note that if the next symbol will be - we will have to stop, since we have no lower to produce.

l[0] h[3] list [1,2,3,0]

Luckily for us, we've chosen well and the last symbol is '+', so we can put our 4 and call is a day.

l[0] h[4] list [1,2,3,0,4]

This is not necessarily the smartest solution, as it can never know if the original number will solve the sequence, and always progresses by 1. That means that for some patterns [+,-...] it will not be able to find a solution. But for the pattern provided it works well with 0 as the initial starting point. If we chose the number 1 is would also work and produce [2,3,4,0,1], but for 2 and above it will fail. It will never produce the solution [0,3,4,1,2].

I hope this helps understanding the approach.


问:
Knit PDf file from RStudio
I am trying to Knit PDf file from RStudio, and I am getting the following error:

```<code>! LaTeX Error: File `framed.sty' not found.
</code>```

R version: 3.2.2 (2015-08-14)

Platform: x86_64-redhat-linux-gnu on AWS EC2

答:
After resolving the framed.sty issue, I was able to resolve the titling.sty error with:

sudo yum -y install texlive-titling

Title: Knit PDf file from RStudio

Body:
I am trying to Knit PDf file from RStudio, and I am getting the following error:

! LaTeX Error: File `framed.sty' not found.

R version: 3.2.2 (2015-08-14)

Platform: x86_64-redhat-linux-gnu on AWS EC2


问:
Save the current selection as HTML in Excel with Python
In Excel, when saving a workbook to an HTML file, one has the choice to save the entire workbook or the current selection only.

How can one programmatically perform the latter using Python win32com library?

答:
Here is the way I found:

import win32com.client
from win32com.client import constants

excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
selection = excel.Selection
worksheet = selection.Parent
workbook = worksheet.Parent
publish_object = workbook.PublishObjects.Add(
    constants.xlSourceRange,
    Filename=r'C:\absolute\path\to\file.html',
    Sheet=worksheet.Name,
    Source=selection.Address,
    HtmlType=constants.xlHtmlStatic
)
publish_object.Publish(True)
```

Not sure if it is the best way but it works. See Application.Selection,  PublishObjects.Add and PublishObject.Publish for additional options (saving Pivot Tables, Charts, etc).

Body:
Here is the way I found:

import win32com.client
from win32com.client import constants

excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
selection = excel.Selection
worksheet = selection.Parent
workbook = worksheet.Parent
publish_object = workbook.PublishObjects.Add(
    constants.xlSourceRange,
    Filename=r'C:\absolute\path\to\file.html',
    Sheet=worksheet.Name,
    Source=selection.Address,
    HtmlType=constants.xlHtmlStatic
)
publish_object.Publish(True)

Not sure if it is the best way but it works. See Application.Selection,  PublishObjects.Add and PublishObject.Publish for additional options (saving Pivot Tables, Charts, etc).


问:
Uninstall and re-install of Anaconda 2.7 won't fix kernel problem in Jupyter
I am in a VM environment (Win 7 VirtualBox) and had gotten the Anaconda 2.7 suite to work.

Being new to Python, I was working on some code that instructed me to install PythonWin to do some connection with Crystal Reports. Seemed to install OK but then started getting some errors about the kernel in Jupyter not starting.

Uninstalled everything and I think got rid of any bad links and such from the previous installs.

Did the fresh install of Anaconda 2.7 and did NOT install PythonWin. Now stuck with a broken/unable to load kernel in Jupyter. Here's the error below. All help much appreciated from this newbie. Thanks!

```<code>Traceback (most recent call last):
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\web.py", line 1592, in _execute
    result = yield result
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1141, in run
    yielded = self.gen.throw(*exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\sessions\handlers.py", line 73, in post
    type=mtype))
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1141, in run
    yielded = self.gen.throw(*exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 79, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1141, in run
    yielded = self.gen.throw(*exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 92, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 326, in wrapper
    yielded = next(result)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 160, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
    km.start_kernel(**kwargs)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\manager.py", line 259, in start_kernel
    **kw)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\manager.py", line 204, in _launch_kernel
    return launch_kernel(kernel_cmd, **kw)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\launcher.py", line 138, in launch_kernel
    proc = Popen(cmd, **kwargs)
  File "C:\Users\Victor\Anaconda2\lib\subprocess.py", line 394, in __init__
    errread, errwrite)
  File "C:\Users\Victor\Anaconda2\lib\subprocess.py", line 644, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
</code>```

答:
Figure I'll close the loop since I've found a solution - after uninstalling everything related to Anaconda and going through the file system and deleting all Anaconda related folders I re-installed Anaconda 2.7 as admin. Also during the setup I selected the choice to make the program available to all users.

Install finished and Anaconda 2.7 and all the modules worked as expected.

Body:
I am in a VM environment (Win 7 VirtualBox) and had gotten the Anaconda 2.7 suite to work.

Being new to Python, I was working on some code that instructed me to install PythonWin to do some connection with Crystal Reports. Seemed to install OK but then started getting some errors about the kernel in Jupyter not starting.

Uninstalled everything and I think got rid of any bad links and such from the previous installs.

Did the fresh install of Anaconda 2.7 and did NOT install PythonWin. Now stuck with a broken/unable to load kernel in Jupyter. Here's the error below. All help much appreciated from this newbie. Thanks!

Traceback (most recent call last):
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\web.py", line 1592, in _execute
    result = yield result
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1141, in run
    yielded = self.gen.throw(*exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\sessions\handlers.py", line 73, in post
    type=mtype))
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1141, in run
    yielded = self.gen.throw(*exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 79, in create_session
    kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1141, in run
    yielded = self.gen.throw(*exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 92, in start_kernel_for_session
    self.kernel_manager.start_kernel(path=kernel_path, kernel_name=kernel_name)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 1133, in run
    value = future.result()
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\concurrent.py", line 261, in result
    raise_exc_info(self._exc_info)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\tornado\gen.py", line 326, in wrapper
    yielded = next(result)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 160, in start_kernel
    super(MappingKernelManager, self).start_kernel(**kwargs)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\multikernelmanager.py", line 110, in start_kernel
    km.start_kernel(**kwargs)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\manager.py", line 259, in start_kernel
    **kw)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\manager.py", line 204, in _launch_kernel
    return launch_kernel(kernel_cmd, **kw)
  File "C:\Users\Victor\Anaconda2\lib\site-packages\jupyter_client\launcher.py", line 138, in launch_kernel
    proc = Popen(cmd, **kwargs)
  File "C:\Users\Victor\Anaconda2\lib\subprocess.py", line 394, in __init__
    errread, errwrite)
  File "C:\Users\Victor\Anaconda2\lib\subprocess.py", line 644, in _execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified


问:
How to map a 2D lookup table to array (python)?
I have three 2D-arrays of same shape, lets call them theta, phi and A.
Let theta and phi be angles to the normal vector seen from different distances on a surface:

```<code>size = 100 # this value is fixed
x = np.arange(-size, size)
y = np.arange(-size, size)
xx, yy = np.meshgrid(xx, yy)
theta = np.arctan((xx**2+yy**2)**0.5 / 100) # angle from distance 100
phi = np.arctan((xx**2+yy**2)**0.5 / 1000) # angle from distance 1000
</code>```

And let A be a 2D map of measured values where the x axis is theta and the y axis is phi in known and linear steps (which is actually not the same shape as theta and phi). What I need is the values of A(theta,phi) expressed as A(x,y).
It seems I can't figure out how to convert A(theta,phi) to A(x,y), even though I know both theta(x,y) and phi(x,y).

What I tried:
Via scipy.interpolate.interp2d I can map A to the same number of rows and columns as theta and phi. Now I can iterate over the indices and guess/round the best matching indices in my array

```<code>B = np.zeros(A.shape)
for i in range(0,A.shape[0]):
  for j in range(0,A.shape[1]):
    B[i,j] = A[int(f_theta*theta[i,j]),int(f_phi*phi[i,j])]
</code>```

Where f_theta and f_phi are prefactors determined by the measured step length of a index step.
This looks like very bad and inefficient coding to me, and like a crude approximation of what I actually want to do (which is an inverse interpolation mapping?). It reminds me of lookup-tables, coordinate transforms and interpolation, but with none of those keywords I found something appropriate to solve the problem.
My python experience shouts out that there will be a module/function for this which I do not know.

Edit about restrictions:
the range of the axis in A(theta, phi) is larger than the range of theta(x,y) and phi(x,y), such that a mapped value always exists.
I do not need to map B back to A, so there are no issues with missing values.
Many values in the map A(theta, phi) would never be used.

Edit about clarity:
I will give an example with small matrices, hoping to clarify things:

```<code># phi given in degrees
phi = np.array([
    [2,1,2],
    [1,0,1],
    [2,1,2],
])
# theta given in degrees
theta = np.array([
    [6,4,6],
    [4,0,5],
    [6,5,6],
])
# A[0,0] is the value at phi=0deg, theta=0deg
# A[0,1] is the value at phi=1deg, theta=0deg
# A[1,1] is the value at phi=1deg, theta=1deg etc
# this is a toy example, the actual A cannot be constructed by a simple rule
A = np.array([
    [0.0,0.1,0.2],
    [1.0,1.1,1.2],
    [2.0,2.1,2.2],
    [3.0,3.1,3.2],
    [4.0,4.1,4.2],
    [5.0,5.1,5.2],
    [6.0,6.1,6.2],
])
# what I want to reach:
B = [[6.2,4.1,6.2],
     [4.1,0.0,5.1],
     [6.2,5.1,6.2]]
</code>```

I need to clarify that I did some simplifications here:

1) For a given theta I can check the corresponding phi by looking in the table:
theta[i,j] corresponds to phi[i,j]. But the construction of the example is too simplified, they do not e.g. share the same origin, it is noisy data and I therefore cannot give an analytical expression theta(phi) or phi(theta)

2) The values in my actual theta and phi are floats, and my actual A measures in non-integer steps too (e.g. 0.45 deg per step in theta direction, 0.2 deg per step in phi direction)

3) in principle, as there is a strict relation between theta and phi, I only need a specific 1D "trace" of values A to find B, but I do not understand how to find this trace, nor how to create B out of the trace. This trace in the example would be [A[0,0],A[4,1],A[5,1],A[6,2]] = [0.0,4.1,5.1,6.2]

答:
You can do, e.g., a bilinear interpolation:

from scipy.interpolate import interpn

delta = [1.0, 1.0] # theta, phi
points = [np.arange(s)*d for s, d in zip(A.shape, delta)]
xi = np.stack((theta, phi), axis = -1)
B = interpn(points, A, xi)
```

<p>This gives:</p>

<pre class="lang-py prettyprint-override"><code>print(B)
[[6.2 4.1 6.2]
 [4.1 0.  5.1]
 [6.2 5.1 6.2]]
</code>```

Body:
I have three 2D-arrays of same shape, lets call them theta, phi and A.
Let theta and phi be angles to the normal vector seen from different distances on a surface:

size = 100 # this value is fixed
x = np.arange(-size, size)
y = np.arange(-size, size)
xx, yy = np.meshgrid(xx, yy)
theta = np.arctan((xx**2+yy**2)**0.5 / 100) # angle from distance 100
phi = np.arctan((xx**2+yy**2)**0.5 / 1000) # angle from distance 1000

And let A be a 2D map of measured values where the x axis is theta and the y axis is phi in known and linear steps (which is actually not the same shape as theta and phi). What I need is the values of A(theta,phi) expressed as A(x,y).
It seems I can't figure out how to convert A(theta,phi) to A(x,y), even though I know both theta(x,y) and phi(x,y).

What I tried:
Via scipy.interpolate.interp2d I can map A to the same number of rows and columns as theta and phi. Now I can iterate over the indices and guess/round the best matching indices in my array

B = np.zeros(A.shape)
for i in range(0,A.shape[0]):
  for j in range(0,A.shape[1]):
    B[i,j] = A[int(f_theta*theta[i,j]),int(f_phi*phi[i,j])]

Where f_theta and f_phi are prefactors determined by the measured step length of a index step.
This looks like very bad and inefficient coding to me, and like a crude approximation of what I actually want to do (which is an inverse interpolation mapping?). It reminds me of lookup-tables, coordinate transforms and interpolation, but with none of those keywords I found something appropriate to solve the problem.
My python experience shouts out that there will be a module/function for this which I do not know.

Edit about restrictions:
the range of the axis in A(theta, phi) is larger than the range of theta(x,y) and phi(x,y), such that a mapped value always exists.
I do not need to map B back to A, so there are no issues with missing values.
Many values in the map A(theta, phi) would never be used.

Edit about clarity:
I will give an example with small matrices, hoping to clarify things:

# phi given in degrees
phi = np.array([
    [2,1,2],
    [1,0,1],
    [2,1,2],
])
# theta given in degrees
theta = np.array([
    [6,4,6],
    [4,0,5],
    [6,5,6],
])
# A[0,0] is the value at phi=0deg, theta=0deg
# A[0,1] is the value at phi=1deg, theta=0deg
# A[1,1] is the value at phi=1deg, theta=1deg etc
# this is a toy example, the actual A cannot be constructed by a simple rule
A = np.array([
    [0.0,0.1,0.2],
    [1.0,1.1,1.2],
    [2.0,2.1,2.2],
    [3.0,3.1,3.2],
    [4.0,4.1,4.2],
    [5.0,5.1,5.2],
    [6.0,6.1,6.2],
])
# what I want to reach:
B = [[6.2,4.1,6.2],
     [4.1,0.0,5.1],
     [6.2,5.1,6.2]]

I need to clarify that I did some simplifications here:

1) For a given theta I can check the corresponding phi by looking in the table:
theta[i,j] corresponds to phi[i,j]. But the construction of the example is too simplified, they do not e.g. share the same origin, it is noisy data and I therefore cannot give an analytical expression theta(phi) or phi(theta)

2) The values in my actual theta and phi are floats, and my actual A measures in non-integer steps too (e.g. 0.45 deg per step in theta direction, 0.2 deg per step in phi direction)

3) in principle, as there is a strict relation between theta and phi, I only need a specific 1D "trace" of values A to find B, but I do not understand how to find this trace, nor how to create B out of the trace. This trace in the example would be [A[0,0],A[4,1],A[5,1],A[6,2]] = [0.0,4.1,5.1,6.2]

Body:
You can do, e.g., a bilinear interpolation:

from scipy.interpolate import interpn

delta = [1.0, 1.0] # theta, phi
points = [np.arange(s)*d for s, d in zip(A.shape, delta)]
xi = np.stack((theta, phi), axis = -1)
B = interpn(points, A, xi)

This gives:

print(B)
[[6.2 4.1 6.2]
 [4.1 0.  5.1]
 [6.2 5.1 6.2]]


问:
Get first day of week T-SQL
How get first day of week (Monday) where week = 6 and year = 2020 I need get 10.02.2020

eg. week 1 in 2020 is  date from 06.01.2020 - 12.01.2020
week 6 in 2020 is  date from 10.02.2020 - 16.02.2020

答:
```<code>DECLARE @YEAR int = 2020;
DECLARE @WEEKSTOADD int = 6;
SET DATEFIRST 1;

SELECT
        DATEADD(day,
                1 -  DATEPART(dw,DATEADD(week,@WEEKSTOADD,cast(cast(@YEAR as varchar(4)) + '0101' as date))),
                DATEADD(week,@WEEKSTOADD,cast(cast(@YEAR as varchar(4)) + '0101' as date)))
</code>```

Title: Get first day of week T-SQL


问:
Emulating GCC's __builtin_unreachable?
I get a whole lot of warnings about switches that only partially covers the range of an enumeration switched over. Therefor, I would like to have a "default" for all those switches and put __builtin_unreachable (GCC builtin) in that case, so that the compiler know that case is not reachable.

However, I came to know that GCC4.3 does not support that builtin yet. Is there any good way to emulate that functionality? I thought about dereferencing a null pointer instead, but that may have other undesirable effects/warnings and such. Do you have any better idea?

答:
keep it simple:

```<code>assert(false);
</code>```

or, better yet:

```<code>#define UNREACHABLE (!"Unreachable code executed!")

assert(UNREACHABLE);
</code>```

Title: Emulating GCC's __builtin_unreachable?

Body:
keep it simple:

assert(false);

or, better yet:

#define UNREACHABLE (!"Unreachable code executed!")

assert(UNREACHABLE);


问:
cbind with loop in R
I'm new with R and I've an issue
So my issue is :
I've multiples tables ex: 10 , also different list from kmeans results related to this tables (10). So I want use cbind in order to add each cluster  to its table :

Ex:

```<code>NEW_table1<- cbind(table1,kmeans_table1$cluster)
NEW_table2<- cbind(table2,kmeans_table2$cluster)
</code>```

...

I've tryd with this code but a get an error

```<code>for (i in 1:10)
{ assign(paste0("NEW_table", i)<-cbind(as.name(paste0("filter_table",i)),Class=(i$cluster) ))
}

> Error in i$cluster : $ operator is invalid for atomic vectors
</code>```

答:
I guess what you want might be something like below</p>

```<code>list2env(setNames(lapply(paste0("table",1:10), function(v) cbind(get(v),get(paste0("kmeans_",v))$cluster)),
                  paste0("NEW_table",1:10)),
         envir = .GlobalEnv)
</code>```

Title: cbind with loop in R

Body:
I'm new with R and I've an issue
So my issue is :
I've multiples tables ex: 10 , also different list from kmeans results related to this tables (10). So I want use cbind in order to add each cluster  to its table :

Ex:

NEW_table1<- cbind(table1,kmeans_table1$cluster)
NEW_table2<- cbind(table2,kmeans_table2$cluster)

...

I've tryd with this code but a get an error

for (i in 1:10)
{ assign(paste0("NEW_table", i)<-cbind(as.name(paste0("filter_table",i)),Class=(i$cluster) ))
}

> Error in i$cluster : $ operator is invalid for atomic vectors

Body:
I guess what you want might be something like below

list2env(setNames(lapply(paste0("table",1:10), function(v) cbind(get(v),get(paste0("kmeans_",v))$cluster)),
                  paste0("NEW_table",1:10)),
         envir = .GlobalEnv)


问:
How to return value from function which has Observable subscription inside?
I dont know how to extract value from Observable to be returned by function in which Observable is present. I need just a value from it to be returned, nothing else.

Current version which works

```<code>function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            console.log(data)
        }
    )
}
getValueFromObservable()
</code>```

I need this to work, function to return value, and then:

```<code>function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())
</code>```

What am I doing wrong here?

答:
In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

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

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

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

And in case store is a sequence of multiple values:

```<code>  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();
</code>```

Body:
I dont know how to extract value from Observable to be returned by function in which Observable is present. I need just a value from it to be returned, nothing else.

Current version which works

function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            console.log(data)
        }
    )
}
getValueFromObservable()

I need this to work, function to return value, and then:

function getValueFromObservable() {
    this.store.subscribe(
        (data:any) => {
            return data
        }
    )
}
console.log(getValueFromObservable())

What am I doing wrong here?

Body:
In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

(async()=>{

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

})();

And in case store is a sequence of multiple values:

  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();


问:
How to make img size constrained by cell size
I want to make sure that an image put inside of a table cell has its size constrained by the cell size, even if it distorts the image. I don´t want it to mantain the aspect ratio!

Can someone help me?

答:
Something like this, I guess:
JSFiddle

td {
  width: 250px;
  height: 450px;
  border: 1px solid black;
}
img {
  display: block;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td><img src="https://www.bigstockphoto.com/images/homepage/module-6.jpg"/></td>
  </tr>
</table></code>```

Body:
Something like this, I guess:
JSFiddle

td {
  width: 250px;
  height: 450px;
  border: 1px solid black;
}
img {
  display: block;
  width: 100%;
  height: 100%;
}

<table>
  <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td><img src="https://www.bigstockphoto.com/images/homepage/module-6.jpg"/></td>
  </tr>
</table>


答:
As per sample data you need substring() :

```<code>select t.*, substring(datnum, charindex(' ', datnum) + 1, 10) as dt
from table t
where t.week = 6;
</code>```

Title: Get first day of week T-SQL

Body:
How get first day of week (Monday) where week = 6 and year = 2020 I need get 10.02.2020

eg. week 1 in 2020 is  date from 06.01.2020 - 12.01.2020
week 6 in 2020 is  date from 10.02.2020 - 16.02.2020

Body:
As per sample data you need substring() :

select t.*, substring(datnum, charindex(' ', datnum) + 1, 10) as dt
from table t
where t.week = 6;


问:
Get ZXing to work
I followed every instructions, wiki, getting started, guides, help,
etc. I could find about ZXing project.
After many many debugging, I finally manged to compile using ant
core.jar, javame.jar, and javese.jar.
I would like to integrate ZXing into my code, i.e., I wish to scan
\read a barcode and handle its data.

I've imported as external jar each of the files mentioned above. Then
I turned to https://code.google.com/p/zxing/wiki/DeveloperNotes to use
the MultiFormatReader().
The BufferedImage class cannot be resolved. I tried whatever I know
and I even tried android's Bitmap for a workaround, but it didn't help
me either.

I know I can use an intent to read\scan the barcode, but I wish to
handle it myself and not to install a "3rd party" application.

Can anyone please help me understand how can I do so?
Few lines of code will be appreciated.

And again, I only want to scan\read a barcode and analyze its data.

答:
Jackson I too suggest you the way suggested by inazaruk.But if you are still having issues integrating that part of code (zxing-android).

Just download zxing-core

Import this core project to your eclipse

In your app's Eclipse build path add reference of zxing-core project so that it is not compiled by JVM but by Dalvik (just avoid using jar file because it is compiled with JVM) and simply use all the classes as suggested at https://code.google.com/p/zxing/wiki/DeveloperNotes

EDIT:
As stated by Sean Owen android doesn't posses BufferedImage class.You need to import these classes & satisfy their dependency.

com.google.zxing.BinaryBitmap,

com.google.zxing.LuminanceSource,

com.google.zxing.MultiFormatReader,

com.google.zxing.Reader

com.google.zxing.Result

com.google.zxing.common.HybridBinarizer

Then you may use it like this

```<code> Bitmap bMap = BitmapFactory.decodeStream(new FileInputStream(file));
 LuminanceSource source = new RGBLuminanceSource(bMap);
 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
                              source));
 Reader reader = new MultiFormatReader();

 Result result = reader.decode(bitmap);
</code>```

Title: Get ZXing to work

Body:
Jackson I too suggest you the way suggested by inazaruk.But if you are still having issues integrating that part of code (zxing-android).

Just download zxing-core

Import this core project to your eclipse

In your app's Eclipse build path add reference of zxing-core project so that it is not compiled by JVM but by Dalvik (just avoid using jar file because it is compiled with JVM) and simply use all the classes as suggested at https://code.google.com/p/zxing/wiki/DeveloperNotes

EDIT:
As stated by Sean Owen android doesn't posses BufferedImage class.You need to import these classes & satisfy their dependency.

com.google.zxing.BinaryBitmap,

com.google.zxing.LuminanceSource,

com.google.zxing.MultiFormatReader,

com.google.zxing.Reader

com.google.zxing.Result

com.google.zxing.common.HybridBinarizer

Then you may use it like this

 Bitmap bMap = BitmapFactory.decodeStream(new FileInputStream(file));
 LuminanceSource source = new RGBLuminanceSource(bMap);
 BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(
                              source));
 Reader reader = new MultiFormatReader();

 Result result = reader.decode(bitmap);


问:
macOS Catalina :repo error: Exited sync due to fetch errors
OS : macOS Catalina 10.15.2
it is failed with "error: Exited sync due to fetch errors"
why is that,anyone know why?</p>

```<code>repo version v1.13.8
       (from https://gerrit.googlesource.com/git-repo)
repo launcher version 1.26
       (from /Users/louiswong/bin/repo)
       (currently at 1.13.8)
repo User-Agent git-repo/1.13.8 (Darwin) git/2.23.0 Python/2.7.16
git 2.23.0
git User-Agent git/2.23.0 (Darwin) git-repo/1.13.8
Python 2.7.16 (default, Nov  9 2019, 05:55:08)
[GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s
</code>```

```<code>
louiswong@LouisWongs-MBP:/Volumes/SamsungT5/a6$ repo sync -j6 -f

....
....
....

Fetching projects: 100% (528/528), done.

error: Exited sync due to gc errors
</code>```

答: problem solved. change operating system to macOS Catalina 10.14.6</p>

Body:
OS : macOS Catalina 10.15.2
it is failed with "error: Exited sync due to fetch errors"
why is that,anyone know why?

repo version v1.13.8
       (from https://gerrit.googlesource.com/git-repo)
repo launcher version 1.26
       (from /Users/louiswong/bin/repo)
       (currently at 1.13.8)
repo User-Agent git-repo/1.13.8 (Darwin) git/2.23.0 Python/2.7.16
git 2.23.0
git User-Agent git/2.23.0 (Darwin) git-repo/1.13.8
Python 2.7.16 (default, Nov  9 2019, 05:55:08)
[GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s

louiswong@LouisWongs-MBP:/Volumes/SamsungT5/a6$ repo sync -j6 -f

....
....
....

Fetching projects: 100% (528/528), done.

error: Exited sync due to gc errors


问:
When python is referred to as single threaded why does in not have the same pitfalls in processing as something like node.js?
I've been doing Node programming for a while and one thing I'm just very tired of is having to worry about blocking the event loop with anything that requires lots of cpu time. I'd also like to expand my language skills to something more focused on machine learning, so python seemed like a good choice based on what I've read.

However, I keep seeing that python is also single threaded, but I get the feeling this wording is being used in a different way than how it's usually used in node. Python is the go to language for a lot of heavy data manipulation so I can't imagine it blocks the same way node does. Can someone with more familiarity with python (and some with node) explain how their processing of concurrent requests differs when 1 request is cpu intensive?

答:
First of all Python is not single-threaded, but its standard library contains everything required to manage threads. It works fine for IO bound tasks, but does not for CPU bound tasks because of the Global Interpretor Lock which prevents more than one thread to execute Python code at the same time.

For data processing tasks, several modules exist that add low level (C code level) processing and internally manage the GIL to be able to use multi-core processing. The most used modules here are scipy and numpy (scientific and numeric processing) and pandas which is an efficient data frame processing tools using numpy arrays for its underlying containers.

Long story short: For io bound tasks, Python is great. If your problem is vectorizable through numpy or pandas, Python is great. If your problem is CPU  intensive and neither numpy nor pandas will be used, Python is not at its best.


问:
How to mount folder with files in kubernetes
I am running a docker image that has certain configuration files within it. I need to persist/mount the same folder to the disk as new files will get added later on. When I use standard volume mount in kubernetes, it mounts an empty directory without the intial configuration files. How do I make sure my initial files are copied to the volume while mounting?</p>

```<code>        - mountPath: /tmp
          name: my-vol
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - name: my-vol
        persistentVolumeClaim:
          claimName: wso2-disk2```
</code>```

答:
A possible solution could be the use the node storage mounted on containers (easiest way) or using a DFS solution like NFS, GlusterFS, and so on.

Another and recommended way to achieve what you need is to use a persistent volumes to share the same files between your containers.

Assuming you have a kubernetes cluster that has only one Node, and you want to share the path /mtn/data of your node with your pods (Source):

Create a PersistentVolume:

A hostPath PersistentVolume uses a file or directory on the Node to emulate network-attached storage.

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: task-pv-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
</code>```

Create a PersistentVolumeClaim:

Pods use PersistentVolumeClaims to request physical storage

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: task-pv-claim
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 3Gi
</code>```

Look at the PersistentVolumeClaim:

kubectl get pvc task-pv-claim

The output shows that the PersistentVolumeClaim is bound to your PersistentVolume,  task-pv-volume.

```<code>NAME            STATUS    VOLUME           CAPACITY   ACCESSMODES   STORAGECLASS   AGE
task-pv-claim   Bound     task-pv-volume   10Gi       RWO           manual         30s
</code>```

Create a deployment with 2 replicas for example:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
            claimName: task-pv-claim
      containers:
        - name: task-pv-container
          image: nginx
          ports:
            - containerPort: 80
              name: "http-server"
          volumeMounts:
            - mountPath: "/mnt/data"
              name: task-pv-storage
</code>```

Now you can check inside both container the path /mnt/data has the same files.

If you have cluster with more than 1 node I recommend you to think about the other types of persistent volumes or using DFS.

References:
Configure persistent volumes
Persistent volumes
Volume Types

Body:
I am running a docker image that has certain configuration files within it. I need to persist/mount the same folder to the disk as new files will get added later on. When I use standard volume mount in kubernetes, it mounts an empty directory without the intial configuration files. How do I make sure my initial files are copied to the volume while mounting?

        - mountPath: /tmp
          name: my-vol
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
      volumes:
      - name: my-vol
        persistentVolumeClaim:
          claimName: wso2-disk2```

Body:
A possible solution could be the use the node storage mounted on containers (easiest way) or using a DFS solution like NFS, GlusterFS, and so on.

Another and recommended way to achieve what you need is to use a persistent volumes to share the same files between your containers.

Assuming you have a kubernetes cluster that has only one Node, and you want to share the path /mtn/data of your node with your pods (Source):

Create a PersistentVolume:

A hostPath PersistentVolume uses a file or directory on the Node to emulate network-attached storage.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: task-pv-volume
  labels:
    type: local
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"

Create a PersistentVolumeClaim:

Pods use PersistentVolumeClaims to request physical storage

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: task-pv-claim
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 3Gi

Look at the PersistentVolumeClaim:

kubectl get pvc task-pv-claim

The output shows that the PersistentVolumeClaim is bound to your PersistentVolume,  task-pv-volume.

NAME            STATUS    VOLUME           CAPACITY   ACCESSMODES   STORAGECLASS   AGE
task-pv-claim   Bound     task-pv-volume   10Gi       RWO           manual         30s

Create a deployment with 2 replicas for example:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx
spec:
  replicas: 2
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      volumes:
        - name: task-pv-storage
          persistentVolumeClaim:
            claimName: task-pv-claim
      containers:
        - name: task-pv-container
          image: nginx
          ports:
            - containerPort: 80
              name: "http-server"
          volumeMounts:
            - mountPath: "/mnt/data"
              name: task-pv-storage

Now you can check inside both container the path /mnt/data has the same files.

If you have cluster with more than 1 node I recommend you to think about the other types of persistent volumes or using DFS.

References:
Configure persistent volumes
Persistent volumes
Volume Types


问:
insert multipyle rows into sqlite database with PyQt5
So far I can insert the input from QLineEdit into a database with

```<code>self.add_to_db_button.clicked.connect(self.add_userinput)

 def add_userinput(self):
        self.query = qsql.QSqlQuery()
        self.query.prepare("INSERT INTO userinput(firstcolumns) VALUES(?)")
        self.query.addBindValue(self.user_input.text())
        self.query.exec()
        self.close

</code>```

with this code a can ad a row in my db

how can I  insert the input from multiple QLineEdit into my db, starting at a empty row in the columnn?
for example:

```<code> self.query.addBindValue(self.schale1_input.text())
        self.query.addBindValue(self.input_1.text())
        self.query.addBindValue(self.input_2.text())
        self.query.addBindValue(self.input_3.text())
        self.query.addBindValue(self.input_4.text())

</code>```

I know that I need to use next() from the QSqlQuery Class to switch to another row
But so far I dont know how to execute it

答:
I found the solution in the pyside2 docs

I needed to use BatchExecutionMode to insert multiple values

in the docs is an example too

PySide2 docs

Body:
So far I can insert the input from QLineEdit into a database with

self.add_to_db_button.clicked.connect(self.add_userinput)

 def add_userinput(self):
        self.query = qsql.QSqlQuery()
        self.query.prepare("INSERT INTO userinput(firstcolumns) VALUES(?)")
        self.query.addBindValue(self.user_input.text())
        self.query.exec()
        self.close

with this code a can ad a row in my db

how can I  insert the input from multiple QLineEdit into my db, starting at a empty row in the columnn?
for example:

 self.query.addBindValue(self.schale1_input.text())
        self.query.addBindValue(self.input_1.text())
        self.query.addBindValue(self.input_2.text())
        self.query.addBindValue(self.input_3.text())
        self.query.addBindValue(self.input_4.text())

I know that I need to use next() from the QSqlQuery Class to switch to another row
But so far I dont know how to execute it


问:
SharePoint Formula: [Created]+60 days = Extension Date (but need it to be a weekday)
I need help with a formula that will add [Extension], a choice field of 30, 45, or 60, to [Created], and return a date [Extension Weekday].

BUT, that future date must be a weekday.

Example: [Created] + [Extension] = [Extension Weekday], but if the result is a Saturday or Sunday, calculate it as the next Monday.

Thanks!

答:
You can use following formula:

```<code>=A2+B2+((WEEKDAY(A2+B2,2)=6)*2)+((WEEKDAY(A2+B2,2)=7)*1)
</code>```

First weekday = 1 = Monday, last = 7 = Sunday. Change WEEKDAY function second parameter if needed.

Body:
You can use following formula:

=A2+B2+((WEEKDAY(A2+B2,2)=6)*2)+((WEEKDAY(A2+B2,2)=7)*1)

First weekday = 1 = Monday, last = 7 = Sunday. Change WEEKDAY function second parameter if needed.


问:
How do I set the init state of a NSToolbar used for a multi panel preference window?
I'm trying to code a multiple panel preference window with an NSToolbar as seen in a lot of Mac applications.  There are a few tutorials that do this by programmatically populating the toolbar but that seems to require a lot of "mechanical" code that I thought to save by setting up the whole toolbar in IB.  Each NSToolbar item calls the action below and the tag is used to select the view (referenced from the same nib with an IBOutlet):

```<code>-(IBAction)changeViewController:(id) sender {
    NSToolbarItem *tbi = (NSToolbarItem*)sender;
    NSString* label = [tbi label];
    NSInteger tag = [tbi tag];
    [self displayViewController:tag];
    NSWindow* window = [self window];
    [window setTitle:label];
}
</code>```

Then I set Autovalidates on each NSToolbarItem which will give the selected/deselected look on the toolbar items.

Now here is my problem: I was not able to figure out a good way to set the initial state. The moment I open the Window none of the toolbar items is selected and I do not get any udpate to the code that would allow me to select this correctly either. What I came up with is this:

```<code>- (void) awakeFromNib {
    [self displayViewController:kGeneralPrefsTag];
    NSWindow* window = [self window];
    NSToolbar *toolbar = [window toolbar];
    [toolbar setSelectedItemIdentifier:@"generalPreferences"];
    [window setTitle:@"General"];
}
</code>```

This is all redundant information:
1) I need to declare the Item Identifiers for the toolbar item just for this
2) I manually duplicate the name of the 1st preference panel to be able to set the window title.

Is there a better way to initialize the toolbar ?  How could I call the first item of the toolbar so that it will invoke the changeViewControllerAction ?

thanks.

答:
I'm using the toolbar to select different tabs and used the following:

```<code>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [item1 setEnabled: YES];
    [toolbar setSelectedItemIdentifier: @"needItToolbarItem"];

    [item2 setEnabled: YES];
    [item3 setEnabled: YES];
    [item4 setEnabled: YES];
}
</code>```

This seemed to get me what I wanted without too much verbiage. I'm not sure if this is the answer you are looking for, but it seems like you were one the right track.

Body:
I'm trying to code a multiple panel preference window with an NSToolbar as seen in a lot of Mac applications.  There are a few tutorials that do this by programmatically populating the toolbar but that seems to require a lot of "mechanical" code that I thought to save by setting up the whole toolbar in IB.  Each NSToolbar item calls the action below and the tag is used to select the view (referenced from the same nib with an IBOutlet):

-(IBAction)changeViewController:(id) sender {
    NSToolbarItem *tbi = (NSToolbarItem*)sender;
    NSString* label = [tbi label];
    NSInteger tag = [tbi tag];
    [self displayViewController:tag];
    NSWindow* window = [self window];
    [window setTitle:label];
}

Then I set Autovalidates on each NSToolbarItem which will give the selected/deselected look on the toolbar items.

Now here is my problem: I was not able to figure out a good way to set the initial state. The moment I open the Window none of the toolbar items is selected and I do not get any udpate to the code that would allow me to select this correctly either. What I came up with is this:

- (void) awakeFromNib {
    [self displayViewController:kGeneralPrefsTag];
    NSWindow* window = [self window];
    NSToolbar *toolbar = [window toolbar];
    [toolbar setSelectedItemIdentifier:@"generalPreferences"];
    [window setTitle:@"General"];
}

This is all redundant information:
1) I need to declare the Item Identifiers for the toolbar item just for this
2) I manually duplicate the name of the 1st preference panel to be able to set the window title.

Is there a better way to initialize the toolbar ?  How could I call the first item of the toolbar so that it will invoke the changeViewControllerAction ?

thanks.

Body:
I'm using the toolbar to select different tabs and used the following:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [item1 setEnabled: YES];
    [toolbar setSelectedItemIdentifier: @"needItToolbarItem"];

    [item2 setEnabled: YES];
    [item3 setEnabled: YES];
    [item4 setEnabled: YES];
}

This seemed to get me what I wanted without too much verbiage. I'm not sure if this is the answer you are looking for, but it seems like you were one the right track.


问:
permission denied for window type 2038 - Android TV
I am attempting to develop floating "widgets" for an android TV (android 8) and every time I try to run the app I'm prompted with:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.floatingwidget2020, PID: 11548
java.lang.RuntimeException: Unable to create service com.example.floatingwidget2020.FloatingWindow: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@e7b96bd -- permission denied for window type 2038
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3414)
    at android.app.ActivityThread.-wrap4(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@e7b96bd -- permission denied for window type 2038
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:789)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
    at com.example.floatingwidget2020.FloatingWindow.onCreate(FloatingWindow.java:57)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3404)
    at android.app.ActivityThread.-wrap4(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

When I initially run the emulator the console prompts with:

```<code>E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
glUtilsParamSize: unknow param 0x000082da
</code>```

Snippet of what I believe to be resulting in the issue:

```<code>final WindowManager.LayoutParams parameters = new WindowManager.LayoutParams(400, 150, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
</code>```

and in AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
</code>```

When I change flag to WindowManager.LayoutParams.TYPE_PHONE it works fine on phone, but no go on android TV.

Any help is appreciated!

答:
On AndroidTV (Oreo) this is the correct configuration:

```<code>mFloatingView = LayoutInflater.from(this).inflate(R.layout.notification_item, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    500,
    WindowManager.LayoutParams.MATCH_PARENT,
    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT);
params.gravity = Gravity.END;
params.y = -354;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, params);
</code>```

This is what we use (production) to show some custom notifications. Actually you also make sure the user gave you the permission.

Body:
I am attempting to develop floating "widgets" for an android TV (android 8) and every time I try to run the app I'm prompted with:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.floatingwidget2020, PID: 11548
java.lang.RuntimeException: Unable to create service com.example.floatingwidget2020.FloatingWindow: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@e7b96bd -- permission denied for window type 2038
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3414)
    at android.app.ActivityThread.-wrap4(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@e7b96bd -- permission denied for window type 2038
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:789)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
    at com.example.floatingwidget2020.FloatingWindow.onCreate(FloatingWindow.java:57)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:3404)
    at android.app.ActivityThread.-wrap4(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1683)
    at android.os.Handler.dispatchMessage(Handler.java:105)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6541)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

When I initially run the emulator the console prompts with:

E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
glUtilsParamSize: unknow param 0x000082da

Snippet of what I believe to be resulting in the issue:

final WindowManager.LayoutParams parameters = new WindowManager.LayoutParams(400, 150, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);

and in AndroidManifest.xml:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

When I change flag to WindowManager.LayoutParams.TYPE_PHONE it works fine on phone, but no go on android TV.

Any help is appreciated!

Body:
On AndroidTV (Oreo) this is the correct configuration:

mFloatingView = LayoutInflater.from(this).inflate(R.layout.notification_item, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    500,
    WindowManager.LayoutParams.MATCH_PARENT,
    WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT);
params.gravity = Gravity.END;
params.y = -354;
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, params);

This is what we use (production) to show some custom notifications. Actually you also make sure the user gave you the permission.


问:
How do I concatenate two lists inside nested list Python?
How do I concatenate two lists inside the nested list Python?

I have this list

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
</code>```

And my expected output is

```<code>lists_of_lists =[[1,2],[3,5],[6,6]]
</code>```

I tried this way

```<code>new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)
</code>```

But I got

```<code>[1, 2, 3, 5, 6, 6]
</code>```

Thank you for any suggestions

答:
I hope this is readable </p>

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

def concat_inner(arr):
    return arr[0]+ arr[1]

final_list = list(map(concat_inner, lists_of_lists))

print(final_list)
</code>```

Body:
How do I concatenate two lists inside the nested list Python?

I have this list

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

And my expected output is

lists_of_lists =[[1,2],[3,5],[6,6]]

I tried this way

new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)

But I got

[1, 2, 3, 5, 6, 6]

Thank you for any suggestions

Body:
I hope this is readable

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

def concat_inner(arr):
    return arr[0]+ arr[1]

final_list = list(map(concat_inner, lists_of_lists))

print(final_list)


问:
in laravel if condition not working in controller
i am trying to use if condition in controller ( IF IMAGE NOT UPLOADED it go to ELSE condition Or else go to IF    )  but it was not working , it just redirecting  registration from page when submitting a form

code

```<code>public function Enrollment(Request $request)

{

  $this->validate($request, [

      'name' => 'required|string|max:255',
      'father_name' => 'required|string|max:225',
      'address' => 'required|string|max:255',
      'card_id' => 'required|string|max:255',
      'image' => 'required|image|mimes:jpeg,png,jpg',

    ]);

    if ($request->image != '')

  {

    $input['name'] = strtoupper ($request['name']);
    $input['father_name'] = strtoupper ($request['father_name']);
    $input['address'] = strtoupper ($request['address']);
    $input['card_id'] = strtoupper ($request['card_id']);

    $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
    $folder1 = public_path('IMAGE/');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']); // image saved in first folder
    $path2 = public_path('IMAGE/BACKUP_IMAGE/') . $input['image']; // path 2
    \File::copy($path1, $path2);

}else{

    $input['name'] = strtoupper ($request['name']);
    $input['father_name'] = strtoupper ($request['father_name']);
    $input['address'] = strtoupper ($request['address']);
    $input['card_id'] = strtoupper ($request['card_id']);

   }

    Card::create($input);

   return back()->with('success','Enrolled Successfully.');
}
</code>```

答:
try this</p>

```<code>if($request->hasfile('user_image'))
</code>```

Body:
i am trying to use if condition in controller ( IF IMAGE NOT UPLOADED it go to ELSE condition Or else go to IF    )  but it was not working , it just redirecting  registration from page when submitting a form

code

public function Enrollment(Request $request)

{

  $this->validate($request, [

      'name' => 'required|string|max:255',
      'father_name' => 'required|string|max:225',
      'address' => 'required|string|max:255',
      'card_id' => 'required|string|max:255',
      'image' => 'required|image|mimes:jpeg,png,jpg',

    ]);

    if ($request->image != '')

  {

    $input['name'] = strtoupper ($request['name']);
    $input['father_name'] = strtoupper ($request['father_name']);
    $input['address'] = strtoupper ($request['address']);
    $input['card_id'] = strtoupper ($request['card_id']);

    $input['image'] = time().'.'.$request->image->getClientOriginalExtension();
    $folder1 = public_path('IMAGE/');
    $path1 = $folder1 . $input['image']; // path 1
    $request->image->move($folder1, $input['image']); // image saved in first folder
    $path2 = public_path('IMAGE/BACKUP_IMAGE/') . $input['image']; // path 2
    \File::copy($path1, $path2);

}else{

    $input['name'] = strtoupper ($request['name']);
    $input['father_name'] = strtoupper ($request['father_name']);
    $input['address'] = strtoupper ($request['address']);
    $input['card_id'] = strtoupper ($request['card_id']);

   }

    Card::create($input);

   return back()->with('success','Enrolled Successfully.');
}

Body:
try this

if($request->hasfile('user_image'))


问:
How do I force powershell to reload a custom module?
I have created a module 'ActiveDirectory.psm1' which contains a class in powershellv5. I am importing that module in another file called 'test.ps1' and then calling a method from the class.

test.ps1 contains the following:

```<code>using module '\\ser01\Shared\Scripts\Windows Powershell\modules\ActiveDirectory\ActiveDirectory.psm1'

Set-StrictMode -version Latest;

$AD = [ActiveDirectory]::New('CS');
$AD.SyncGroupMembership($True);
</code>```

It all works as expected BUT when I make a change to ActiveDirectory.psm1 & save the changes they aren't reflected immediately. i.e. if ActiveDirectory.psm1 contains:

```<code>write-verbose 'do something';
</code>```

If I change that to

```<code>write-verbose 'now the script does something else';
</code>```

the output remains 'do something'

I'm guessing it has stored the module in memory and doesn't reload it therefore missing the changes I have made. What command do I need to run to load the most recent saved version of the module?

答:
From what I've gathered. Import-Module does not import classes. You have to use the "using module " and it has to be in the first line of your script. On top of that problem, the classes appear to be "cached" in some esoteric way that precludes any uninstall-module or remove-module options. I've found I basically need to restart my powershell terminal to clear it.

If classes are not involved use import-module OR install-module. In both cases you can do a get-modules -all or get-installedmodule and then remove-module or uninstall-module. You want to make sure you look for all versions and pipe that to remove/uninstall to ensure you wipe everything out.

Body:
I have created a module 'ActiveDirectory.psm1' which contains a class in powershellv5. I am importing that module in another file called 'test.ps1' and then calling a method from the class.

test.ps1 contains the following:

using module '\\ser01\Shared\Scripts\Windows Powershell\modules\ActiveDirectory\ActiveDirectory.psm1'

Set-StrictMode -version Latest;

$AD = [ActiveDirectory]::New('CS');
$AD.SyncGroupMembership($True);

It all works as expected BUT when I make a change to ActiveDirectory.psm1 & save the changes they aren't reflected immediately. i.e. if ActiveDirectory.psm1 contains:

write-verbose 'do something';

If I change that to

write-verbose 'now the script does something else';

the output remains 'do something'

I'm guessing it has stored the module in memory and doesn't reload it therefore missing the changes I have made. What command do I need to run to load the most recent saved version of the module?


问:
How to load a small placeholder image before loading the actual content
I have a question regarding the image loading style as shown on http://www.e-flux.com. This website first loads an image of a certain pattern (randomly) before proceeding to display the actual image. My guess is that this is to have visually pleasing content before even having loaded the total website.

I have looked at the source code and I saw that it had a class of "lazy is-loading". I think it has to do something with that.

I'd like to replicate this effect and did some research, about progressive images and such. Also, this website: 'css-tricks.com the-blur-up-technique-for-loading-background-images/' explains about loading a small image first and blur it to keep loading times low until the actual image has been downloaded.

But I can't seem to find how they did this trick at http://www.e-flux.com.

All info is appreciated!

答:
Sometimes the CSS background-image is not desired. You could also use a simple inline javascript for this purpose, a disadvantage is that the placeholder image has to load first and correctly. However, this is usually not an issue, as the placeholder image will be faster to load in the first place, and may already be in cache.

For example:

```

This works because the browser will typically leave the currently displayed image in view until the new image has loaded.

It might not be a perfect solution, but it is simple, fairly readable, and easy to implement.

Body:
Sometimes the CSS background-image is not desired. You could also use a simple inline javascript for this purpose, a disadvantage is that the placeholder image has to load first and correctly. However, this is usually not an issue, as the placeholder image will be faster to load in the first place, and may already be in cache.

For example:

<img src="placeholder.jpg" data-src="my-image.jpg" onload="if(this.src !== this.getAttribute('data-src')) this.src=this.getAttribute('data-src');">

This works because the browser will typically leave the currently displayed image in view until the new image has loaded.

It might not be a perfect solution, but it is simple, fairly readable, and easy to implement.


问:
Home-brew installation fails on High Sierra
I am trying to install Homebrew on a Mac mini with High Sierra v10.13. I run the following command as instructed:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

The terminal informs me that it will install brew and asks password, but it eventually fails and shows the following message:

```<code>The operation couldn’t be completed. (NSURLErrorDomain error -1012.)
==> Installing
==> /usr/bin/sudo /usr/sbin/softwareupdate -i
Software Update Tool
: No such update
No updates are available.
==> /usr/bin/sudo /bin/rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
==> /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools
xcode-select: error: invalid developer directory '/Library/Developer/CommandLineTools'
Failed during: /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools
</code>```

Please help me solve this issue. Thanks.

答:
I had a similar problem, so I am posting this here to help anyone in pain !

The command brew doctor tells me that some installed formulae are missing dependencies.

After doing the command brew upgrade, I get the error for some dependencies (below is the example for openjdk) :

```<code>configure: error: No xcodebuild tool and no system framework headers found, use --with-sysroot or --with-sdk-name to provide a path to a valid SDK
/private/tmp/openjdk-20200219-89506-1wim844/jdk13u-jdk-13.0.2+8/build/.configure-support/generated-configure.sh: line 82: 5: Bad file descriptor
configure exiting with result code 1

These open issues may also help:
Migrate formulae to depend on `openjdk`.
</code>```

Here is how I solved this :

sudo xcode-select -r

Edit and set the date of your Mac as October 1st, 2019

sudo xcodebuild -runFirstLaunch

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

brew upgrade

And it worked ! (i am using a iMac mid2011 with MacOS Sierra)

Body:
I am trying to install Homebrew on a Mac mini with High Sierra v10.13. I run the following command as instructed:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

The terminal informs me that it will install brew and asks password, but it eventually fails and shows the following message:

The operation couldn’t be completed. (NSURLErrorDomain error -1012.)
==> Installing
==> /usr/bin/sudo /usr/sbin/softwareupdate -i
Software Update Tool
: No such update
No updates are available.
==> /usr/bin/sudo /bin/rm -f /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
==> /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools
xcode-select: error: invalid developer directory '/Library/Developer/CommandLineTools'
Failed during: /usr/bin/sudo /usr/bin/xcode-select --switch /Library/Developer/CommandLineTools

Please help me solve this issue. Thanks.

Body:
I had a similar problem, so I am posting this here to help anyone in pain !

The command brew doctor tells me that some installed formulae are missing dependencies.

After doing the command brew upgrade, I get the error for some dependencies (below is the example for openjdk) :

configure: error: No xcodebuild tool and no system framework headers found, use --with-sysroot or --with-sdk-name to provide a path to a valid SDK
/private/tmp/openjdk-20200219-89506-1wim844/jdk13u-jdk-13.0.2+8/build/.configure-support/generated-configure.sh: line 82: 5: Bad file descriptor
configure exiting with result code 1

These open issues may also help:
Migrate formulae to depend on `openjdk`.

Here is how I solved this :

sudo xcode-select -r

Edit and set the date of your Mac as October 1st, 2019

sudo xcodebuild -runFirstLaunch

sudo xcode-select -s /Applications/Xcode.app/Contents/Developer

brew upgrade

And it worked ! (i am using a iMac mid2011 with MacOS Sierra)


问:
Get users from an AD group
I have this code to work with users from a group

```<code>DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}
</code>```

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?

答: It might be an option to use the System.DirectoryServices.AccountManagement classes instead of the DirectorySearcher. There is a GroupPrincipal class which has a Members property that contains the UserPrincipal objects.

Title: Get users from an AD group

Body:
I have this code to work with users from a group

DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");

SearchResult myGroupSearchResult = myGroupSearcher.FindOne();

if (myGroupSearchResult != null)
{
    ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];

    int intMemberCount = myUsersInGroup.Count;

    for (int i = 0; i < intMemberCount; i++)
    {
        //Split the current result
        string[] strProperites = myUsersInGroup[i].ToString().Split(',');

        //Get the CN
        string strUsername = strProperites[0].Substring(3);

        DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
        myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
        myUserSearcher.PropertiesToLoad.Add("memberOf");

        SearchResult myUserSearchResult = myUserSearcher.FindOne();

        //Do some work
    }
}

This works for most users, but for some, the strUsername gets turncated depending on how the customers AD looks like (if the user have a CN containing ,). So this solution isnt the most optimal to use. Is there a way to get the samaccount name when searching for members in a group? Or is there a better way?


问:
How to recover original data after detrending?
I have a vector y which contains the original data I have collected. I am using the MATLAB function detrend(..) in order to shift the data around zero and be able to compare them with another vector x which contains data which exist around zero. Now, what I want to do is to shift the data of vector y back to their original scale and also if possible shift the data of vector x as well in order to compare them around the area of the original data of y. The reason for that is because I want to compute the relative error between the data which is given by the formula:

It is obvious that x can't be around zero because it will cause division problems. I have tried to recover the data by adding to the detrending data the mean of the original data but it doesn;t give me back the original data. Is there any way I can do so ?

答:
Detrending removes both offsets and linear trends from the data, so adding back the mean is not sufficient. You also have to add points from a line of the form d = a*t + b.

The two-output version of the detrend command returns the portion of the data, T_r that was removed from the original data:

```<code>[data_d,T_r] = detrend(___)
</code>```

So unless you have access to T_r mentioned above or the equation of the line that was removed from the original data, you cannot recover it back.

You can see in MATLAB's documentation that a trend line is removed with the detrend command: https://www.mathworks.com/help/ident/ref/detrend.html

Body:
Detrending removes both offsets and linear trends from the data, so adding back the mean is not sufficient. You also have to add points from a line of the form d = a*t + b.

The two-output version of the detrend command returns the portion of the data, T_r that was removed from the original data:

[data_d,T_r] = detrend(___)

So unless you have access to T_r mentioned above or the equation of the line that was removed from the original data, you cannot recover it back.

You can see in MATLAB's documentation that a trend line is removed with the detrend command: https://www.mathworks.com/help/ident/ref/detrend.html


问:
NameError: name 'cap' is not defined
I have defined cap in

```<code>def fingerCursor(device):
    global cap
    global cap_height
    global cap_width
    cap = cv2.VideoCapture(device)
        #cap.set(cv2.cap_PROP_FRAME_HEIGHT,720)
        #cap.set(cv2.cap_PROP_FRAME_WIDTH,1280)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
        #print(cap_height,cap_width)
</code>```

But still whenever I am running this part of my code, it says cap not defined. It also has the same problem with cap_height and cap_width.

```<code>while(cap.isOpened()):
        ## capture frame-by-frame
        ret, frame_raw = cap.read()
        while not ret:
            ret,frame_raw = cap.read()
        frame_raw = cv2.flip(frame_raw, 1)
        frame = frame_raw[:round(cap_height),:round(cap_width)] # ROI of the image
        cv2.imshow("raw_frame",frame)
</code>```

答: Your variables have to be defined outside of your function. And you have to keep your lines starting with global to declare you want to modify those variables outside of your function as well.

Title: NameError: name 'cap' is not defined

Body:
I have defined cap in

def fingerCursor(device):
    global cap
    global cap_height
    global cap_width
    cap = cv2.VideoCapture(device)
        #cap.set(cv2.cap_PROP_FRAME_HEIGHT,720)
        #cap.set(cv2.cap_PROP_FRAME_WIDTH,1280)
    cap_height = cap.get(cv2.cap_PROP_FRAME_HEIGHT)
    cap_width = cap.get(cv2.cap_PROP_FRAME_WIDTH)
        #print(cap_height,cap_width)

But still whenever I am running this part of my code, it says cap not defined. It also has the same problem with cap_height and cap_width.

while(cap.isOpened()):
        ## capture frame-by-frame
        ret, frame_raw = cap.read()
        while not ret:
            ret,frame_raw = cap.read()
        frame_raw = cv2.flip(frame_raw, 1)
        frame = frame_raw[:round(cap_height),:round(cap_width)] # ROI of the image
        cv2.imshow("raw_frame",frame)


问:
Logout all tabs and if you logout in one tab it needs to be logged out automatically in all other tabs
We are opening Gmail in two tabs and if you logout in one tab it needs to be logged out automatically in all other tabs</p>

答: It gets automatically logged out from the other tabs as well if you logout in one tab. If you're NOT getting logged out, try refreshing the page.</p>