问:
Best way to make PostgreSQL backups
I have a site that uses PostgreSQL. All content that I provide in my site is created at a development environment (this happens because it's webcrawler content). The only information created at the production environment is information about the users.

I need to find a good way to update data stored at production. May I restore to production only the tables updated at development environment and PostgreSQL will update this records at production or the best way would be to backup the users information at production, insert them at development and restore the whole database at production?

Thank you

答:
There are many tips arounds this subject here and here.
I'd suggest you to take a look on these links before everything.

If your data is discarded at each update process then a plain dump will be enough. You can redirect pg_dump output directly to psql connected on production to avoid pg_restore step, something like below:

```<code>#Of course you must drop tables to load it again
#so it'll be reasonable to make a full backup before this
pg_dump -Fp -U user -h host_to_dev -T=user your_db | psql -U user -h host_to_production your_db
</code>```

You might asking yourself "Why he's saying to drop my tables"?

Bulk loading data on a fresh table is faster than deleting old data and inserting again. A quote from the docs:

Creating an index on pre-existing data is quicker than updating it incrementally as each row is loaded.

Ps¹: If you can't connect on both environment at same time then you need to do pg_restore manually.

Ps²: I don't recommend it but you can append --clean option on pg_dump to generate DROP statements automatically. Be extreme careful with this option to avoid dropping unnexpected objects.

Title: Best way to make PostgreSQL backups

Body:
There are many tips arounds this subject here and here.
I'd suggest you to take a look on these links before everything.

If your data is discarded at each update process then a plain dump will be enough. You can redirect pg_dump output directly to psql connected on production to avoid pg_restore step, something like below:

#Of course you must drop tables to load it again
#so it'll be reasonable to make a full backup before this
pg_dump -Fp -U user -h host_to_dev -T=user your_db | psql -U user -h host_to_production your_db

You might asking yourself "Why he's saying to drop my tables"?

Bulk loading data on a fresh table is faster than deleting old data and inserting again. A quote from the docs:

Creating an index on pre-existing data is quicker than updating it incrementally as each row is loaded.

Ps¹: If you can't connect on both environment at same time then you need to do pg_restore manually.

Ps²: I don't recommend it but you can append --clean option on pg_dump to generate DROP statements automatically. Be extreme careful with this option to avoid dropping unnexpected objects.


来源: stackexchange

问:
UL suffix vs uint32_t cast
I have to define constants like this :

```<code>#define MY_CONSTANT   0xBEEF
</code>```

I want to be sure that my constant will be considered 32 bits.

I have can use a (uint32_t) cast like this :

```<code>#define MY_CONSTANT   (uint32_t)0xBEEF
</code>```

Or a UL suffix like this :

```<code>#define MY_CONSTANT   0xBEEFUL
</code>```

Are these two versions fully equivalent?

I would say no, as UL is the equivalent of unsigned long and unsigned long length may depend on CPU.

The C99 standard ensures that an uint32_t integer is 32 bits, but I don't think it ensures that a UL suffix does the same.

答:
The suffix corresponding to uint32_t is not necessarily UL (it's usually U on 32 bit and 64 bit architectures).

Apart from that, a cast might possibly truncate an integer constant that's wider, but its corresponding suffix wouldn't ever cast down, only up.

(See this table for how suffixes work with integer constants in different bases.)

ContentLicense: CC BY-SA 3.0

Title: UL suffix vs uint32_t cast

Body:
I have to define constants like this :

#define MY_CONSTANT   0xBEEF

I want to be sure that my constant will be considered 32 bits.

I have can use a (uint32_t) cast like this :

#define MY_CONSTANT   (uint32_t)0xBEEF

Or a UL suffix like this :

#define MY_CONSTANT   0xBEEFUL

Are these two versions fully equivalent?

I would say no, as UL is the equivalent of unsigned long and unsigned long length may depend on CPU.

The C99 standard ensures that an uint32_t integer is 32 bits, but I don't think it ensures that a UL suffix does the same.


问:
pandas: fill a column by applying a class method to another column (which contains classes)
i have a pandas dataframe where one of the column is filled with class objects, like the code below:

```<code>import pandas as pd
class rec:
    def test(self, a):
        return a
class rec1:
    def test(self, a):
        return a*3
x= rec()
y = rec1()
list = [x,y]
df=pd.DataFrame(list, columns=['first'])
df['second']=['a1','b1']

print(df)
                                          first second
0   <__main__.rec object at 0x000000180AAE9208>     a1
1  <__main__.rec1 object at 0x000000180AACBEB8>     b1
</code>```

now, i wish to create a new column by applying the method "test" to column 'first', by reading input for "test" from column 'second'.
this loop works:

```<code>df['third']=0
for i in (0,1):
 df['third'][i] = df['first'][i].test(df['second'][i])
</code>```

but i wonder if i can avoid the loop and use something more similar to the following code (which does not work):

```<code>df['third'] = df['first'].test(df['second'])
</code>```

any advice? thank you

答:
This isn't that hard to do actually. You can use np.vectorize.

```<code>f = lambda x, y: x.test(y)
v = np.vectorize(f)

df['third'] = v(df['first'], df['second'])

df
                                   first second   third
0   <__main__.rec object at 0x1038b1ef0>     a1      a1
1  <__main__.rec1 object at 0x1038b1c18>     b1  b1b1b1
</code>```

Body:
i have a pandas dataframe where one of the column is filled with class objects, like the code below:

import pandas as pd
class rec:
    def test(self, a):
        return a
class rec1:
    def test(self, a):
        return a*3
x= rec()
y = rec1()
list = [x,y]
df=pd.DataFrame(list, columns=['first'])
df['second']=['a1','b1']

print(df)
                                          first second
0   <__main__.rec object at 0x000000180AAE9208>     a1
1  <__main__.rec1 object at 0x000000180AACBEB8>     b1

now, i wish to create a new column by applying the method "test" to column 'first', by reading input for "test" from column 'second'.
this loop works:

df['third']=0
for i in (0,1):
 df['third'][i] = df['first'][i].test(df['second'][i])

but i wonder if i can avoid the loop and use something more similar to the following code (which does not work):

df['third'] = df['first'].test(df['second'])

any advice? thank you

Body:
This isn't that hard to do actually. You can use np.vectorize.

f = lambda x, y: x.test(y)
v = np.vectorize(f)

df['third'] = v(df['first'], df['second'])

df
                                   first second   third
0   <__main__.rec object at 0x1038b1ef0>     a1      a1
1  <__main__.rec1 object at 0x1038b1c18>     b1  b1b1b1


问:
In TensorFlow is there any way to just initialize uninitialised variables?
The standard way of initializing variables in TensorFlow is

```<code>init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
</code>```

After running some learning for a while I create a new set of variables but once I initialize them it resets all my existing variables. At the moment my way around this is to save all the variable I need and then reapply them after the tf.initalize_all_variables call. This works but is a bit ugly and clunky. I cannot find anything like this in the docs...

Does anyone know of any good way to just initialize the uninitialized variables?

答:
Btw, if you want to initialize only a single tensor (for e.g.  tf.Variable) that hasn't been initialized using tf.global_variables_initializer(), then you can use your_tensor.initializer in the sess.run() as in the following example:

```<code>In [196]: weights = tf.Variable(tf.zeros(shape=(3, 4)), name='weights')

In [197]: with tf.Session() as sess:
     ...:     sess.run(weights.initializer)
     ...:     print(weights.eval())
     ...:

# the result
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]
</code>```

Body:
The standard way of initializing variables in TensorFlow is

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

After running some learning for a while I create a new set of variables but once I initialize them it resets all my existing variables. At the moment my way around this is to save all the variable I need and then reapply them after the tf.initalize_all_variables call. This works but is a bit ugly and clunky. I cannot find anything like this in the docs...

Does anyone know of any good way to just initialize the uninitialized variables?

Body:
Btw, if you want to initialize only a single tensor (for e.g.  tf.Variable) that hasn't been initialized using tf.global_variables_initializer(), then you can use your_tensor.initializer in the sess.run() as in the following example:

In [196]: weights = tf.Variable(tf.zeros(shape=(3, 4)), name='weights')

In [197]: with tf.Session() as sess:
     ...:     sess.run(weights.initializer)
     ...:     print(weights.eval())
     ...:

# the result
[[ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]
 [ 0.  0.  0.  0.]]


问:
How to use lxml version 3.7.3 on app engine?
On their Built-in Third-party Libraries page, it says that lxml 3.7.3 is supported but I can't seem to find a way to use that.

If I write in app.yaml:

```<code>- name: lxml
  version: latest
</code>```

When I log etree.LXML_VERSION inside the app, I get (2, 3, 0, 0).

Setting the version specifically to "3.7.3" (instead of latest) doesn't seem to work. When I try to deploy, gcloud says:

```<code>ERROR: (gcloud.app.deploy) An error occurred while parsing file: [... /app.yaml]
lxml version "3.7.3" is not supported, use one of: "2.3", "2.3.5"
  in "... app.yaml", line 17, column 1
</code>```

I have installed lxml locally inside the ./lib folder, but the folder is ignored on deploy.

Am I doing something wrong?

答:
The problems seemed to happen because of an old google cloud sdk.

The sdk was installed using apt-get and somehow it was not getting updated. This also included an older Python SDK

At this moment the latest Python SDK is 1.9.62, I was using 1.9.52.

Updating the sdk seemed to fix the problem

sudo apt-get update && sudo apt-get install google-cloud-sdk

Body:
On their Built-in Third-party Libraries page, it says that lxml 3.7.3 is supported but I can't seem to find a way to use that.

If I write in app.yaml:

- name: lxml
  version: latest

When I log etree.LXML_VERSION inside the app, I get (2, 3, 0, 0).

Setting the version specifically to "3.7.3" (instead of latest) doesn't seem to work. When I try to deploy, gcloud says:

ERROR: (gcloud.app.deploy) An error occurred while parsing file: [... /app.yaml]
lxml version "3.7.3" is not supported, use one of: "2.3", "2.3.5"
  in "... app.yaml", line 17, column 1

I have installed lxml locally inside the ./lib folder, but the folder is ignored on deploy.

Am I doing something wrong?


问:
How to track untracked content?
See below the solid line for my original question.

I have a folder in my local directory that is untracked. When I run git status, I get:

```<code>Changed but not updated:
modified:   vendor/plugins/open_flash_chart_2 (modified content, untracked content)
</code>```

When I type git add vendor/plugins/open_flash_chart_2 then try git status again, it still says untracked. What's going on?

Here is a simple summary of my latest half hour:

Discovered that my Github repo is not tracking my vendor/plugins/open_flash_chart_2 plugin. Specifically, there's no content and it's showing a green arrow on the folder icon.

Tried git submodule init

```<code>No submodule mapping found in .gitmodules for path 'vendor/plugins/open_flash_chart_2'
</code>```

Tried git submodule add git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2

```<code>vendor/plugins/open_flash_chart_2 already exists in the index
</code>```

git status

```<code>modified: vendor/plugins/open_flash_chart_2 (untracked content)
</code>```

Hunted for any file named .gitmodules in my repository/local directory but couldn't find one.

What do I have to do to get my submodules working so git can start tracking properly?

This may be unrelated (I include it in case it helps), but every time I type git commit -a rather than my usual git commit -m "my comments", it throws up an error:

```<code>E325: ATTENTION
Found a swap file by the name ".git\.COMMIT-EDITMSG.swp"
         dated: Thu Nov 11 19:45:05 2010
     file name: c:/san/project/.git/COMMIT_EDITMSG
      modified: YES
     user name: San   host name: San-PC
    process ID: 4268
While opening file ".git\COMMIT_EDITMSG"
         dated: Thu Nov 11 20:56:09 2010
  NEWER than swap file!
Swap file ".git\.COMMIT_EDITMSG.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:
Swap file ".git\.COMMIT_EDITMSG.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:
</code>```

I am a complete newbie at Github and despite trying to go through the documentation, I'm a bit stumped by these particular problems. Thank you.

答:
This question has been answered already, but thought I'd add to the mix what I found out when I got these messages.

I have a repo called playground that contains a number of sandbox apps. I added two new apps from a tutorial to the playground directory by cloning the tutorial's repo. The result was that the new apps' git stuff pointed to the tutorial's repo and not to my repo. The solution was to delete the .git directory from each of those apps' directories, mv the apps' directories outside the playground directory, and then mv them back and run git add .. After that it worked.

Title: How to track untracked content?

Body:
See below the solid line for my original question.

I have a folder in my local directory that is untracked. When I run git status, I get:

Changed but not updated:
modified:   vendor/plugins/open_flash_chart_2 (modified content, untracked content)

When I type git add vendor/plugins/open_flash_chart_2 then try git status again, it still says untracked. What's going on?

Here is a simple summary of my latest half hour:

Discovered that my Github repo is not tracking my vendor/plugins/open_flash_chart_2 plugin. Specifically, there's no content and it's showing a green arrow on the folder icon.

Tried git submodule init

No submodule mapping found in .gitmodules for path 'vendor/plugins/open_flash_chart_2'

Tried git submodule add git://github.com/korin/open_flash_chart_2_plugin.git vendor/plugins/open_flash_chart_2

vendor/plugins/open_flash_chart_2 already exists in the index

git status

modified: vendor/plugins/open_flash_chart_2 (untracked content)

Hunted for any file named .gitmodules in my repository/local directory but couldn't find one.

What do I have to do to get my submodules working so git can start tracking properly?

This may be unrelated (I include it in case it helps), but every time I type git commit -a rather than my usual git commit -m "my comments", it throws up an error:

E325: ATTENTION
Found a swap file by the name ".git\.COMMIT-EDITMSG.swp"
         dated: Thu Nov 11 19:45:05 2010
     file name: c:/san/project/.git/COMMIT_EDITMSG
      modified: YES
     user name: San   host name: San-PC
    process ID: 4268
While opening file ".git\COMMIT_EDITMSG"
         dated: Thu Nov 11 20:56:09 2010
  NEWER than swap file!
Swap file ".git\.COMMIT_EDITMSG.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:
Swap file ".git\.COMMIT_EDITMSG.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:

I am a complete newbie at Github and despite trying to go through the documentation, I'm a bit stumped by these particular problems. Thank you.


问:
Navbar items sitting on top of each other instead of next to
Navbar items are sitting on top of each other when creating a  while they are meant to sit next to each other. I have followed the instructions on W3 Schools As far as I'm concerned my code is right.

```<code><div class="container-fluid">
    <nav class="navbar navbar-default">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#">BRAND</a>
            </div>

            <ul class="nav navbar-nav">
                <li><a href="#">about</a></li>
                <li><a href="#">portfolio</a></li>
                <li><a href="#">contact</a></li>
            </ul>
        </div>
    </nav>
</div>
</code>```

Here is my Codepen

答:
Pasting your example into bootply seems to work fine.  I'd check that your script & stylesheet files are correctly included in your page.

--Edit--

I actually do see the issue after reducing the browser width match one of the smaller media queries (responsive mode).  The code you're using is working correctly, but is based on an incomplete example which wouldn't collapse down to the hamburger/triple-bar icon, as Bootstrap navbar's typically do.

You might be better served to review the code example from the Bootstrap website directly:  https://getbootstrap.com/docs/3.3/components/#navbar

Body:
Navbar items are sitting on top of each other when creating a  while they are meant to sit next to each other. I have followed the instructions on W3 Schools As far as I'm concerned my code is right.

                BRAND

about

portfolio

contact

Here is my Codepen


问:
Where do Workers and Parameter Servers reside in Distributed TensorFlow?
In this post, it was mentioned that:

Also, there's no built-in distinction between worker and ps devices --
  it's just a convention that variables get assigned to ps devices, and
  ops are assigned to worker devices.

In this post, it was mentioned that:

TL;DR: TensorFlow doesn't know anything about "parameter servers", but
  instead it supports running graphs across multiple devices in
  different processes. Some of these processes have devices whose names
  start with "/job:ps", and these hold the variables. The workers drive
  the training process, and when they run the train_op they will cause
  work to happen on the "/job:ps" devices, which will update the shared
  variables.

Questions:

Do variables in ps reside on the CPU or GPU? Also, are there any performance gains if "/job:ps" resides on CPU or GPU?

Do the lower level libraries decide where to place a variable or operation?

答:
Do variables in ps reside on the CPU or GPU? Also, are there any performance gains if "/job:ps" resides on CPU or GPU?

You can pin ps job to either on of those (with exceptions, see below), but pinning it to GPU is not practical. ps is really a storage of parameters and ops to update it. A CPU device can have a lot more memory (i.e., main RAM) than a GPU and is fast enough to update the parameters as the gradients are coming in. In most cases, matrix multiplications, convolutions and other expensive ops are done by the workers, hence a placement of a worker on a GPU makes sense. A placement of a ps to a GPU is a waste of resources, unless a ps job is doing something very specific and expensive.

But: Tensorflow does not currently have a GPU kernel for integer variables, so the following code will fail when Tensorflow tries to place the variable i on GPU #0:

with tf.device("/gpu:0"):
  i = tf.Variable(3)

with tf.Session() as sess:
  sess.run(i.initializer)   # Fails!
```

<p>with the following message:</p>

```Could not satisfy explicit device specification '/device:GPU:0'
because no supported kernel for GPU devices is available.
```

This is the case when there's no choice of device for a parameter, and thus for a parameter server: only CPU.

Do the lower level libraries decide where to place a variable or operation?

If I get this question right, node placement rules are pretty simple:

If a node was already placed on a device in a previous run of the graph, it is left on that device.

Else, if the user pinned a node to a device via tf.device, the placer places it on that device.

Else, it defaults to GPU #0, or the CPU if there is no GPU.

Tensorflow whitepaper describes also a dynamic placer, which is more sophisticated, but it's not part of the open source version of tensorflow right now.

Body:
Do variables in ps reside on the CPU or GPU? Also, are there any performance gains if "/job:ps" resides on CPU or GPU?

You can pin ps job to either on of those (with exceptions, see below), but pinning it to GPU is not practical. ps is really a storage of parameters and ops to update it. A CPU device can have a lot more memory (i.e., main RAM) than a GPU and is fast enough to update the parameters as the gradients are coming in. In most cases, matrix multiplications, convolutions and other expensive ops are done by the workers, hence a placement of a worker on a GPU makes sense. A placement of a ps to a GPU is a waste of resources, unless a ps job is doing something very specific and expensive.

But: Tensorflow does not currently have a GPU kernel for integer variables, so the following code will fail when Tensorflow tries to place the variable i on GPU #0:

with tf.device("/gpu:0"):
  i = tf.Variable(3)

with tf.Session() as sess:
  sess.run(i.initializer)   # Fails!

with the following message:

Could not satisfy explicit device specification '/device:GPU:0'
because no supported kernel for GPU devices is available.

This is the case when there's no choice of device for a parameter, and thus for a parameter server: only CPU.

Do the lower level libraries decide where to place a variable or operation?

If I get this question right, node placement rules are pretty simple:

If a node was already placed on a device in a previous run of the graph, it is left on that device.

Else, if the user pinned a node to a device via tf.device, the placer places it on that device.

Else, it defaults to GPU #0, or the CPU if there is no GPU.

Tensorflow whitepaper describes also a dynamic placer, which is more sophisticated, but it's not part of the open source version of tensorflow right now.


问:
Using reflection to distinguish generic methods with generic arguments
In EntityFrameworkQueryableExtensions there are two methods, both called ThenInclude, with the following signatures:

```<code>public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)where TEntity : class
</code>```

and

```<code>public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(this IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)where TEntity : class
</code>```

The difference is that the second signature has IEnumerable<TPreviousProperty> in the type of the 'this' argument, while the first signature has just TPreviousProperty.

The question is, how can I get one the MethodInfo for the second one (or the first one for that matter) using reflection and MakeGenericMethod?

So far all I've been able to come up with is to add an extra layer like this:

```<code>class Whatever<TEntity> where TEntity: class {
    private static MethodInfo ThenIncludeEnumerableMethod<TPreviousProperty,TProperty>()
    {
        Func<IIncludableQueryable<TEntity,IEnumerable<TPreviousProperty>>, Expression<Func<TPreviousProperty, TProperty>>, IIncludableQueryable<TEntity, TProperty>> thenIncludeLambda = (source, lambda) => source.ThenInclude(lambda);
        return thenIncludeLambda.Method;
    }
}
</code>```

There should be a more direct way to do it.

Note Reflection: How to get a generic method? is not an answer to this question.

答:
You would like to call

```<code>typeof(EntityFrameworkQueryableExtensions).GetMethod("ThenInclude", new [] { type1, type2 })
</code>```

But you cannot do so because the type arguments type1 and type2 are constructed from the open generic types returned by MethodInfo.GetGenericArguments() for the two methods named "ThenInclude".

What you can do is to loop through all methods named "ThenInclude" that have the required number of generic arguments and parameters, map the open generic arguments to the required parameter type(s), and check if the actual parameters types match the required types:

```<code>class Whatever<TEntity> where TEntity : class
{
    public static MethodInfo ThenIncludeMethod<TPreviousProperty, TProperty>()
    {
        var query = from m in typeof(EntityFrameworkQueryableExtensions).GetMethods()
                    where m.Name == "ThenInclude" && m.IsGenericMethodDefinition
                    let args = m.GetGenericArguments()
                    where args.Length == 3
                    let tEntityType = args[0]
                    let tPreviousPropertyType = args[1]
                    let tPropertyType = args[2]
                    let parameters = m.GetParameters()
                    where parameters.Length == 2
                    where parameters[0].ParameterType == typeof(IIncludableQueryable<,>).MakeGenericType(new Type[] { tEntityType, tPreviousPropertyType })
                    where parameters[1].ParameterType == typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(new[] { tPreviousPropertyType, tPropertyType }))
                    select m.MakeGenericMethod(new[] { typeof(TEntity), typeof(TPreviousProperty), typeof(TProperty) });
        return query.SingleOrDefault();
    }

    public static MethodInfo ThenIncludeEnumerableMethod<TPreviousProperty, TProperty>()
    {
        var query = from m in typeof(EntityFrameworkQueryableExtensions).GetMethods()
                    where m.Name == "ThenInclude" && m.IsGenericMethodDefinition
                    let args = m.GetGenericArguments()
                    where args.Length == 3
                    let tEntityType = args[0]
                    let tPreviousPropertyType = args[1]
                    let tPropertyType = args[2]
                    let parameters = m.GetParameters()
                    where parameters.Length == 2
                    where parameters[0].ParameterType == typeof(IIncludableQueryable<,>).MakeGenericType(new Type[] { tEntityType, typeof(IEnumerable<>).MakeGenericType(new[] { tPreviousPropertyType }) })
                    where parameters[1].ParameterType == typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(new[] { tPreviousPropertyType, tPropertyType }))
                    select m.MakeGenericMethod(new[] { typeof(TEntity), typeof(TPreviousProperty), typeof(TProperty) });
        return query.SingleOrDefault();
    }
}
</code>```

Honestly your current method is much simpler, however it does return the MethodInfo of an anonymous method declared by Whatever<T> that calls EntityFrameworkQueryableExtensions.ThenInclude() while the above return a MethodInfo of a concrete method of EntityFrameworkQueryableExtensionsThenInclude<,,>() directly.

Note I wrote this using full .Net.  If you are using .Net Core you may need to nuget System.Reflection.TypeExtensions as described here and then I believe it should work.

Body:
In EntityFrameworkQueryableExtensions there are two methods, both called ThenInclude, with the following signatures:

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(this IIncludableQueryable<TEntity, TPreviousProperty> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)where TEntity : class

and

public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(this IIncludableQueryable<TEntity, IEnumerable<TPreviousProperty>> source, Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath)where TEntity : class

The difference is that the second signature has IEnumerable<TPreviousProperty> in the type of the 'this' argument, while the first signature has just TPreviousProperty.

The question is, how can I get one the MethodInfo for the second one (or the first one for that matter) using reflection and MakeGenericMethod?

So far all I've been able to come up with is to add an extra layer like this:

class Whatever<TEntity> where TEntity: class {
    private static MethodInfo ThenIncludeEnumerableMethod<TPreviousProperty,TProperty>()
    {
        Func<IIncludableQueryable<TEntity,IEnumerable<TPreviousProperty>>, Expression<Func<TPreviousProperty, TProperty>>, IIncludableQueryable<TEntity, TProperty>> thenIncludeLambda = (source, lambda) => source.ThenInclude(lambda);
        return thenIncludeLambda.Method;
    }
}

There should be a more direct way to do it.

Note Reflection: How to get a generic method? is not an answer to this question.

Body:
You would like to call

typeof(EntityFrameworkQueryableExtensions).GetMethod("ThenInclude", new [] { type1, type2 })

But you cannot do so because the type arguments type1 and type2 are constructed from the open generic types returned by MethodInfo.GetGenericArguments() for the two methods named "ThenInclude".

What you can do is to loop through all methods named "ThenInclude" that have the required number of generic arguments and parameters, map the open generic arguments to the required parameter type(s), and check if the actual parameters types match the required types:

class Whatever<TEntity> where TEntity : class
{
    public static MethodInfo ThenIncludeMethod<TPreviousProperty, TProperty>()
    {
        var query = from m in typeof(EntityFrameworkQueryableExtensions).GetMethods()
                    where m.Name == "ThenInclude" && m.IsGenericMethodDefinition
                    let args = m.GetGenericArguments()
                    where args.Length == 3
                    let tEntityType = args[0]
                    let tPreviousPropertyType = args[1]
                    let tPropertyType = args[2]
                    let parameters = m.GetParameters()
                    where parameters.Length == 2
                    where parameters[0].ParameterType == typeof(IIncludableQueryable<,>).MakeGenericType(new Type[] { tEntityType, tPreviousPropertyType })
                    where parameters[1].ParameterType == typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(new[] { tPreviousPropertyType, tPropertyType }))
                    select m.MakeGenericMethod(new[] { typeof(TEntity), typeof(TPreviousProperty), typeof(TProperty) });
        return query.SingleOrDefault();
    }

    public static MethodInfo ThenIncludeEnumerableMethod<TPreviousProperty, TProperty>()
    {
        var query = from m in typeof(EntityFrameworkQueryableExtensions).GetMethods()
                    where m.Name == "ThenInclude" && m.IsGenericMethodDefinition
                    let args = m.GetGenericArguments()
                    where args.Length == 3
                    let tEntityType = args[0]
                    let tPreviousPropertyType = args[1]
                    let tPropertyType = args[2]
                    let parameters = m.GetParameters()
                    where parameters.Length == 2
                    where parameters[0].ParameterType == typeof(IIncludableQueryable<,>).MakeGenericType(new Type[] { tEntityType, typeof(IEnumerable<>).MakeGenericType(new[] { tPreviousPropertyType }) })
                    where parameters[1].ParameterType == typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(new[] { tPreviousPropertyType, tPropertyType }))
                    select m.MakeGenericMethod(new[] { typeof(TEntity), typeof(TPreviousProperty), typeof(TProperty) });
        return query.SingleOrDefault();
    }
}

Honestly your current method is much simpler, however it does return the MethodInfo of an anonymous method declared by Whatever<T> that calls EntityFrameworkQueryableExtensions.ThenInclude() while the above return a MethodInfo of a concrete method of EntityFrameworkQueryableExtensionsThenInclude<,,>() directly.

Note I wrote this using full .Net.  If you are using .Net Core you may need to nuget System.Reflection.TypeExtensions as described here and then I believe it should work.


问:
Table in IE7 with 100% width overflowing containing div
I have a table of results inside an area div. Because I am using a fluid layout, the area div doesn't have a  set width. The width of the table is set to 100%, but in IE7 it overflows beyond the containing div. Any ideas?

HTML:

```<code><div id="area">
    <table id="results">
    </table>
</div>
</code>```

CSS:

```<code>#results{
    width: 100%;
}
</code>```

答: Got it! I needed to set white-space:normal for all the TDs and THs within the table.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a table of results inside an area div. Because I am using a fluid layout, the area div doesn't have a  set width. The width of the table is set to 100%, but in IE7 it overflows beyond the containing div. Any ideas?

HTML:

CSS:

#results{
    width: 100%;
}


问:
Linking against a local `extern` variable
I reckon this has been probably answered before. Please mark as a duplicate if it has!

I'm having trouble understanding what extern means for local variables (or local functions!). I can't seem to see how it is functionally different from a static local variable... For instance:

```<code>int foo(void) {
   extern int i;
   return i++;
}

int bar(void) {
   static int i;
   return i++;
}
</code>```

AFAICT, foo and bar are the same. The difference according to the C99 spec is that i in foo should have external linkage compared to the i in bar. That said, I can't think of any way to exploit that external linkage - since it is a local variable, it isn't accessible outside of foo, let alone outside of the file.

I'm sure I'm missing something here - what is it?

EDIT

Thank you to everyone who pointed out that I'm missing a type on extern and static. You are quite correct. As a frequent answerer on SO, I now understand the frustration of the barrage of down votes that follow this sort of oversight.

答:
Extern : extern variable are having external linkage ,main usage of extern varaible to link variable in other file so you are saying "since it is a local variable, it isn't accessible outside of foo" which is wrong, check the below code.

```<code>    xyz@xyz-PC:~/s_flow/alec$ vi one.c
    #include<stdio.h>
    int foo() {
            extern i;//this is just declaration, not definition
            return i++;
    }
    main()
    {
            int ret = foo();
            printf("ret = %d \n",ret);
    }
</code>```

Now linker will try to find definition of "i" in other file or below functions  , if not found linker will throw error. when you compile above code you will get linker error. So provide the definition in other file as

```<code>xyz@xyz-PC:~/s_flow/alec$ vi two.c
i=100;//this is definition of i
</code>```

Now compile like gcc one.c two.c & check

static : static storage class having internal linkage it means you can't use  static variable outside that file(in which it is declared).

```<code>     xyz@xyz-PC:~/s_flow/alec$ vi one.c
     main()
     {
          printf("i = %d \n",i);
     }
</code>```

Now if I am trying to access static variable which is defined in two.c to one.c , it will throw error.

```<code>xyz@xyz-PC:~/s_flow/alec$ vi two.c
void bar() {
   static i = 10;
}
</code>```

Body:
I reckon this has been probably answered before. Please mark as a duplicate if it has!

I'm having trouble understanding what extern means for local variables (or local functions!). I can't seem to see how it is functionally different from a static local variable... For instance:

int foo(void) {
   extern int i;
   return i++;
}

int bar(void) {
   static int i;
   return i++;
}

AFAICT, foo and bar are the same. The difference according to the C99 spec is that i in foo should have external linkage compared to the i in bar. That said, I can't think of any way to exploit that external linkage - since it is a local variable, it isn't accessible outside of foo, let alone outside of the file.

I'm sure I'm missing something here - what is it?

EDIT

Thank you to everyone who pointed out that I'm missing a type on extern and static. You are quite correct. As a frequent answerer on SO, I now understand the frustration of the barrage of down votes that follow this sort of oversight.

Body:
Extern : extern variable are having external linkage ,main usage of extern varaible to link variable in other file so you are saying "since it is a local variable, it isn't accessible outside of foo" which is wrong, check the below code.

    xyz@xyz-PC:~/s_flow/alec$ vi one.c
    #include<stdio.h>
    int foo() {
            extern i;//this is just declaration, not definition
            return i++;
    }
    main()
    {
            int ret = foo();
            printf("ret = %d \n",ret);
    }

Now linker will try to find definition of "i" in other file or below functions  , if not found linker will throw error. when you compile above code you will get linker error. So provide the definition in other file as

xyz@xyz-PC:~/s_flow/alec$ vi two.c
i=100;//this is definition of i

Now compile like gcc one.c two.c & check

static : static storage class having internal linkage it means you can't use  static variable outside that file(in which it is declared).

     xyz@xyz-PC:~/s_flow/alec$ vi one.c
     main()
     {
          printf("i = %d \n",i);
     }

Now if I am trying to access static variable which is defined in two.c to one.c , it will throw error.

xyz@xyz-PC:~/s_flow/alec$ vi two.c
void bar() {
   static i = 10;
}


问:
using template literal to assign value to title attribute using javascript
i need to assign the title attribute of a div which is creating using java-script
the issue i am facing is when the title includes multiple words separated by space the example code is

```<code>let value = "example value to display";
$("#parentDiv").append(`<div title=${value}> ${value}</div>`);
</code>```

the result i am getting is

```<code><div title="example" value to display> example value to display</div>
</code>```

i am not sure what the issue is most probably the template literal is assuming that the space is the end of the string, anyone have a solution please help

答:
Add quotes (" or ') around title value as your title value contains space.

let value = "example value to display";
$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parentDiv'></div></code>```

Body:
i need to assign the title attribute of a div which is creating using java-script
the issue i am facing is when the title includes multiple words separated by space the example code is

let value = "example value to display";
$("#parentDiv").append(`<div title=${value}> ${value}</div>`);

the result i am getting is

 example value to display

i am not sure what the issue is most probably the template literal is assuming that the space is the end of the string, anyone have a solution please help

Body:
Add quotes (" or ') around title value as your title value contains space.

let value = "example value to display";
$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='parentDiv'></div>


问:
Entity is null for most of the requests - LUIS
Bot Framework version - 3.11.0

I have added intents as below in LUIS:

Whenever I call the API as here I get entities empty. It works randomly like this query works

Am I missing anything? What might be the reason LUIS can able to find the entity in one case than other, as both are using same utterance and intent?

答: You are using very few utterances. You should use at least 12 and with a varied structure, not just "Who know..." "Who knows..." etc. Also for the other intents you need to add enough utterances as well.</p>


答:
Attributes containing spaces or other non-alphanumeric characters must be enclosed with " or ':

let value = "example value to display";
$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDiv"></div></code>```

But really, it's a bad idea to build HTML this way. jQuery has methods for setting elements' attributes and text. So go ahead and use them:

let value = "example value to display";
$("#parentDiv").append($('
').attr('title', value).text(value));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDiv"></div></code>```

Title: using template literal to assign value to title attribute using javascript

Body:
Attributes containing spaces or other non-alphanumeric characters must be enclosed with " or ':

let value = "example value to display";
$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDiv"></div>

But really, it's a bad idea to build HTML this way. jQuery has methods for setting elements' attributes and text. So go ahead and use them:

let value = "example value to display";
$("#parentDiv").append($('<div>').attr('title', value).text(value));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDiv"></div>


答:
Your template is missing double quotes on your title attribute.</p>

```<code>let value = "example value to display";
$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);
</code>```

Body:
Your template is missing double quotes on your title attribute.

let value = "example value to display";
$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);


问:
How do I mock whatwg-fetch for testing in Jest?
I have a component that fetches some data in its componentDidMount function.  The function that fetches the data is in fetch-data.js.  I am trying to test this component, and want to mock the fetched data.  I am trying to follow this link in mocking the fetch function for tests: http://facebook.github.io/jest/docs/en/manual-mocks.html

I have my __mocks__ folder adjacent to my node_modules folder:

```<code>...
node_modules
__mocks__
└── whatwg-fetch.js
...
</code>```

my whatwg-fetch.js mock looks like this:

```<code>const whatwgFetch = jest.genMockFromModule('whatwg-fetch');
whatwgFetch.fetch = (url) => jest.fn().mockImplementation(() => Promise.resolve({ ok: true }));

module.exports = whatwgFetch;
</code>```

However, when I run tests, I still get this error:

```<code> RUNS  src/scenes/Home/Home.spec.js
 myproject/node_modules/react-scripts/scripts/test.js:20
  throw err;
  ^

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (/Local/Users/john/Documents/js/react/haiku/node_modules/whatwg-fetch/fetch.js:436:16)
</code>```

The XHR request in question is not going to a third party, but is a local URL (fetch('/my/local/file')), if that makes any difference.

edit: It seems like even if there is nothing in the component tests, I get the same error.  Everything is commented out in MyComponent.spec.js and it seems to still try and make network requests.  Anyone know why?

答:
So, I had installed jest-fetch-mock and added these lines to my src/setupTests.js:

```<code>global.fetch = require('jest-fetch-mock');
fetch.mockResponse(JSON.stringify({ testing: true }));
</code>```

and now the tests run.

Body:
I have a component that fetches some data in its componentDidMount function.  The function that fetches the data is in fetch-data.js.  I am trying to test this component, and want to mock the fetched data.  I am trying to follow this link in mocking the fetch function for tests: http://facebook.github.io/jest/docs/en/manual-mocks.html

I have my __mocks__ folder adjacent to my node_modules folder:

...
node_modules
__mocks__
└── whatwg-fetch.js
...

my whatwg-fetch.js mock looks like this:

const whatwgFetch = jest.genMockFromModule('whatwg-fetch');
whatwgFetch.fetch = (url) => jest.fn().mockImplementation(() => Promise.resolve({ ok: true }));

module.exports = whatwgFetch;

However, when I run tests, I still get this error:

 RUNS  src/scenes/Home/Home.spec.js
 myproject/node_modules/react-scripts/scripts/test.js:20
  throw err;
  ^

TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (/Local/Users/john/Documents/js/react/haiku/node_modules/whatwg-fetch/fetch.js:436:16)

The XHR request in question is not going to a third party, but is a local URL (fetch('/my/local/file')), if that makes any difference.

edit: It seems like even if there is nothing in the component tests, I get the same error.  Everything is commented out in MyComponent.spec.js and it seems to still try and make network requests.  Anyone know why?

Body:
So, I had installed jest-fetch-mock and added these lines to my src/setupTests.js:

global.fetch = require('jest-fetch-mock');
fetch.mockResponse(JSON.stringify({ testing: true }));

and now the tests run.


问:
Conditional values for calculated column in MySql
I'm trying to calculate the difference between two date columns, which works just fine as:

```<code>select (ship_date - due_date) AS DaysTaken;
</code>```

Basically, I want to determine if orders were shipped on time and, if not, how many days late. This works fine, as expected, except, if the order is shipped early, I get a negative number.  What I'd like to do is to evaluate the results and return 0, if it calculates a negative value.

I don't know how to do this in a MySQL select statement.  Can anyone help?

答:
You can use the GREATEST() function to replace negative numbers with 0:</p>

```<code>select GREATEST((ship_date - due_date),0) AS DaysTaken;
</code>```

Body:
I'm trying to calculate the difference between two date columns, which works just fine as:

select (ship_date - due_date) AS DaysTaken;

Basically, I want to determine if orders were shipped on time and, if not, how many days late. This works fine, as expected, except, if the order is shipped early, I get a negative number.  What I'd like to do is to evaluate the results and return 0, if it calculates a negative value.

I don't know how to do this in a MySQL select statement.  Can anyone help?

Body:
You can use the GREATEST() function to replace negative numbers with 0:

select GREATEST((ship_date - due_date),0) AS DaysTaken;


问:
How can I remove rows from a postgres table that all have the same value in a column, if any of those rows contains a certain value in another column?
I have a table that looks like this:

```<code>Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Frank | 300   | 20
Mr. Frank | 401   | 0
Mr. Smith | 102   | 20
Ms. Date  | 300   | 0
Mr. First | 100   | 10
</code>```

I want to query and get back a table that has removed any teacher (all of their rows) who has a class of zero students, so the result I'm looking for is:

```<code>Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Smith | 102   | 20
Mr. First | 100   | 10
</code>```

Any idea how I can do this? I am stumped.

答:
Your table is not normalized. You have no choice but to use the teacher name. That will be an issue if there are teachers with the same name, but here is how you do it:

```<code>SELECT *
FROM teachers t1
WHERE t1.teacher NOT IN (SELECT t2.teacher
                    FROM teachers t2
                    WHERE t2.teacher = t1.teacher
                    AND number_of_students = 0)
</code>```

Or a probably simpler approach:

```<code>SELECT *
FROM teachers t1
WHERE (SELECT COUNT(*)
       FROM teachers t2
       WHERE t2.teacher = t1.teacher
       AND number_of_students = 0) > 0
</code>```

Or you can use Klin's slightly better performing answer.

Body:
I have a table that looks like this:

Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Frank | 300   | 20
Mr. Frank | 401   | 0
Mr. Smith | 102   | 20
Ms. Date  | 300   | 0
Mr. First | 100   | 10

I want to query and get back a table that has removed any teacher (all of their rows) who has a class of zero students, so the result I'm looking for is:

Teacher   | Class | Number of students
Ms. Smith | 101   | 101
Mr. Smith | 102   | 20
Mr. First | 100   | 10

Any idea how I can do this? I am stumped.

Body:
Your table is not normalized. You have no choice but to use the teacher name. That will be an issue if there are teachers with the same name, but here is how you do it:

SELECT *
FROM teachers t1
WHERE t1.teacher NOT IN (SELECT t2.teacher
                    FROM teachers t2
                    WHERE t2.teacher = t1.teacher
                    AND number_of_students = 0)

Or a probably simpler approach:

SELECT *
FROM teachers t1
WHERE (SELECT COUNT(*)
       FROM teachers t2
       WHERE t2.teacher = t1.teacher
       AND number_of_students = 0) > 0

Or you can use Klin's slightly better performing answer.


答:
The result is
 example value to display
. This is caused by the fact that there are no double quotes at all.

It should be instead:

```<code>$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);
</code>```

Body:
The result is <div title=example value to display> example value to display</div>. This is caused by the fact that there are no double quotes at all.

It should be instead:

$("#parentDiv").append(`<div title="${value}"> ${value}</div>`);


问:
Selenium WebDriver C# -- continue when exception thrown
I want to check for the presence of a number of elements on the page and if any were not present I want to see a list of custom error messages telling me which ones were not present.

At the moment I have:

Test case:

```<code>[Test]
public void CheckAllElementsArePresent()
{
    Assert.IsTrue(Results.CheckFirstElement());
    Assert.IsTrue(Results.CheckSecondElement());
    Assert.IsTrue(Results.CheckThirdElement());
}
</code>```

Framework:

```<code>public static bool CheckFirstElement()
{
    var results = Driver.Instance.FindElement(By.CssSelector("firstElementSelector']"));

    if (results == null)
    {
        throw new Exception("Cannot find first element");
    }

    var attr = results.GetAttribute("id");
    if (attr == null)
    {
        throw new Exception("Cannot find first element");
    }

    if (attr.Contains("someTextIWantToFind"))
    {
        return true;
    }
    return false;
}
</code>```

This will work, however, the test will fail if any of these fails. I need a way to continue running the test and then spit out any errors at the end of the test, eg: "Cannot find the first element", "Cannot find the third element" etc.

Thanks.

答:
Create a new class that will hold methods for your needs

```<code>public static class MakeSure
{
    private static List<string> errorsFound = new List<string>();
    public static List<string> getErrors() { return errorsFound; }

    public void ElementIsNotNull(IWebElement element, string elementName)
    {
        if(element == null)
        {
           errorsFound.Add("Cannot find element " + elementName +".");
        }
    }

    public void ElementHasAttribute(IWebElement element, string elementName, string attribute)
    {
        if(element.GetAttribute(attribute) == null)
        {
            errorsFound.Add("Cannot find " + attribute + " attribute of the element.");
        }
    }

    public void ElementContaisText(IWebElement element, string elementName, string attribute, string text)
    {
        if(!element.GetAttribute(attribute).Text.Contains(text))
        {
            errorsFound.Add("Cannot find the text " + text +" in " + elementName +" element");
        }
    }
}
</code>```

and you can call them from your Test Case to "MakeSure" your element has a specific attribute,is not null etc. You can create more overloads so you won't have to put "ID" to "attribute" everytime, like so:

```<code>public void ElementHasAttribute(IWebElement element, string elementName)
{
    ElementHasAttribute(element, elementName, "id");
}
</code>```

So everytime you want your attribute to be "id", you just call the overload method. You can pretty much do anything following the above example and change the code/methods to your needs.

You can also modify your Results class to do the following

```<code>public void CheckFirstElement()
{
    IWebElement firstElement;
    MakeSure.ElementIsNotNull(firstElement, "first element");
    MakeSure.ElementHasAttribute(firstElement, "first element", "id");
    MakeSure.ElementContaisText(firstElement, "first element", "id", "Text to validate.");
}
</code>```

So all you will have to do in your test is:

```<code>Results.CheckFirstElement();
</code>```

Body:
I want to check for the presence of a number of elements on the page and if any were not present I want to see a list of custom error messages telling me which ones were not present.

At the moment I have:

Test case:

[Test]
public void CheckAllElementsArePresent()
{
    Assert.IsTrue(Results.CheckFirstElement());
    Assert.IsTrue(Results.CheckSecondElement());
    Assert.IsTrue(Results.CheckThirdElement());
}

Framework:

public static bool CheckFirstElement()
{
    var results = Driver.Instance.FindElement(By.CssSelector("firstElementSelector']"));

    if (results == null)
    {
        throw new Exception("Cannot find first element");
    }

    var attr = results.GetAttribute("id");
    if (attr == null)
    {
        throw new Exception("Cannot find first element");
    }

    if (attr.Contains("someTextIWantToFind"))
    {
        return true;
    }
    return false;
}

This will work, however, the test will fail if any of these fails. I need a way to continue running the test and then spit out any errors at the end of the test, eg: "Cannot find the first element", "Cannot find the third element" etc.

Thanks.

Body:
Create a new class that will hold methods for your needs

public static class MakeSure
{
    private static List<string> errorsFound = new List<string>();
    public static List<string> getErrors() { return errorsFound; }

    public void ElementIsNotNull(IWebElement element, string elementName)
    {
        if(element == null)
        {
           errorsFound.Add("Cannot find element " + elementName +".");
        }
    }

    public void ElementHasAttribute(IWebElement element, string elementName, string attribute)
    {
        if(element.GetAttribute(attribute) == null)
        {
            errorsFound.Add("Cannot find " + attribute + " attribute of the element.");
        }
    }

    public void ElementContaisText(IWebElement element, string elementName, string attribute, string text)
    {
        if(!element.GetAttribute(attribute).Text.Contains(text))
        {
            errorsFound.Add("Cannot find the text " + text +" in " + elementName +" element");
        }
    }
}

and you can call them from your Test Case to "MakeSure" your element has a specific attribute,is not null etc. You can create more overloads so you won't have to put "ID" to "attribute" everytime, like so:

public void ElementHasAttribute(IWebElement element, string elementName)
{
    ElementHasAttribute(element, elementName, "id");
}

So everytime you want your attribute to be "id", you just call the overload method. You can pretty much do anything following the above example and change the code/methods to your needs.

You can also modify your Results class to do the following

public void CheckFirstElement()
{
    IWebElement firstElement;
    MakeSure.ElementIsNotNull(firstElement, "first element");
    MakeSure.ElementHasAttribute(firstElement, "first element", "id");
    MakeSure.ElementContaisText(firstElement, "first element", "id", "Text to validate.");
}

So all you will have to do in your test is:

Results.CheckFirstElement();


问:
Console pause c#
In this code

```<code>Console.Write("Enter any number from 0 to 9:");
int k = Console.Read();
Console.Write("The ASCII code for it is:");
Console.WriteLine(k);
Console.Read();
</code>```

after I input a number my console close instantly.
If I write this code

```<code>Console.Write("Enter any string:");
string k = Console.ReadLine();
Console.Write("Your string is:");
Console.WriteLine(k);
Console.Read();
</code>```

my console stops so I can see what I wrote.
Why is that happening?

答:
ReadLine, Read etc. should work but you can also run it via Ctrl-F5 instead, which will keep the window open until you hit a key. Or remove the ReadLine at the end completely if you just want it to close.

Note Ctrl-F5 is running without debugging. If you're after breakpoints don't do this.

Although with your code you're only going to going to get the behaviour you expect from the .Read on line 2.

```<code>num=Console.Read();
</code>```

I think it will be the ASCII code for the first 'character' of your number i.e. if you enter 322 it will just read 3 and the ASCII for 3 is 51, which will be what is assigned to num.

Title: Console pause c#

Body:
In this code

Console.Write("Enter any number from 0 to 9:");
int k = Console.Read();
Console.Write("The ASCII code for it is:");
Console.WriteLine(k);
Console.Read();

after I input a number my console close instantly.
If I write this code

Console.Write("Enter any string:");
string k = Console.ReadLine();
Console.Write("Your string is:");
Console.WriteLine(k);
Console.Read();

my console stops so I can see what I wrote.
Why is that happening?

Body:
ReadLine, Read etc. should work but you can also run it via Ctrl-F5 instead, which will keep the window open until you hit a key. Or remove the ReadLine at the end completely if you just want it to close.

Note Ctrl-F5 is running without debugging. If you're after breakpoints don't do this.

Although with your code you're only going to going to get the behaviour you expect from the .Read on line 2.

num=Console.Read();

I think it will be the ASCII code for the first 'character' of your number i.e. if you enter 322 it will just read 3 and the ASCII for 3 is 51, which will be what is assigned to num.


问:
How do I add a auto_increment primary key in SQL Server database?
I have a table set up that currently has no primary key. All I need to do is add a primary key, no null, auto_increment.

I'm working with a Microsoft SQL Server database. I understand that it can't be done in a single command but every command I try keeps returning syntax errors.

edit ---------------

I have created the primary key and even set it as not null. However, I can't set up the auto_increment.

I've tried:

```<code>ALTER TABLE tableName MODIFY id NVARCHAR(20) auto_increment
ALTER TABLE tableName ALTER COLUMN id NVARCHAR(20) auto_increment
ALTER TABLE tableName MODIFY id NVARCHAR(20) auto_increment
ALTER TABLE tableName ALTER COLUMN id NVARCHAR(20) auto_increment
</code>```

I'm using NVARCHAR because it wouldn't let me set NOT NULL under int

答:
you can try this...</p>
```<code>ALTER TABLE Your_Table
 ADD table_ID int NOT NULL PRIMARY KEY auto_increment;
</code>```

Body:
I have a table set up that currently has no primary key. All I need to do is add a primary key, no null, auto_increment.

I'm working with a Microsoft SQL Server database. I understand that it can't be done in a single command but every command I try keeps returning syntax errors.

edit ---------------

I have created the primary key and even set it as not null. However, I can't set up the auto_increment.

I've tried:

ALTER TABLE tableName MODIFY id NVARCHAR(20) auto_increment
ALTER TABLE tableName ALTER COLUMN id NVARCHAR(20) auto_increment
ALTER TABLE tableName MODIFY id NVARCHAR(20) auto_increment
ALTER TABLE tableName ALTER COLUMN id NVARCHAR(20) auto_increment

I'm using NVARCHAR because it wouldn't let me set NOT NULL under int

Body:
you can try this...

ALTER TABLE Your_Table
 ADD table_ID int NOT NULL PRIMARY KEY auto_increment;

ContentLicense: CC BY-SA 4.0


问:
How to reassign the value in angular2 component getting undefined
I have a component  here declare the  numbers array  public numbers :number[] =[]; and given the value for the numbers array in service response and getting 10 and after the ngInit block it shows as undefined

app.component.ts

```<code>    export class AppComponent implements OnInit {

      public numbers :number[] =[];  // here declare the variable
      public numberss :Iproduct[]

       ngOnInit(){
    // here call the service

     this._productService.getproducts().subscribe((response) => {this.numberss = response;

    this.errornumber = 10;  // here ressign the value

    }
 }),(err)=> {this.errorMsg =<any>err};

       } // end of ngInit

// here is the 3rd party chart js  pass the this.errornumber gets undefined

    public doughnutChartOptions: any = {
      elements: {
        center: {
          text:this.errornumber +"% <br>products" ,
        }
      }
    };

    } // end of component
</code>```

Here it is undefined why:text:this.errornumber

答:
Beacuse at the moment when doughnutChartOptions is defined this.errornumber not exist yet so it is undefined. After products are return by service then it is created and initialized. So, you should move creating doughnutChartOptions field to subscribe.

```<code>Example
</code>```

https://plnkr.co/edit/CSXxSoWhxppw9ran4AcM?p=preview

Body:
I have a component  here declare the  numbers array  public numbers :number[] =[]; and given the value for the numbers array in service response and getting 10 and after the ngInit block it shows as undefined

app.component.ts

    export class AppComponent implements OnInit {

      public numbers :number[] =[];  // here declare the variable
      public numberss :Iproduct[]

       ngOnInit(){
    // here call the service

     this._productService.getproducts().subscribe((response) => {this.numberss = response;

    this.errornumber = 10;  // here ressign the value

    }
 }),(err)=> {this.errorMsg =<any>err};

       } // end of ngInit

// here is the 3rd party chart js  pass the this.errornumber gets undefined

    public doughnutChartOptions: any = {
      elements: {
        center: {
          text:this.errornumber +"%
products" ,
        }
      }
    };

    } // end of component

Here it is undefined why:text:this.errornumber

Body:
Beacuse at the moment when doughnutChartOptions is defined this.errornumber not exist yet so it is undefined. After products are return by service then it is created and initialized. So, you should move creating doughnutChartOptions field to subscribe.

Example

https://plnkr.co/edit/CSXxSoWhxppw9ran4AcM?p=preview


问:
PySide: event-filter for QGraphicsView in container class
I have communications working between similar widgets from imported child widgets and the parent main window and widgets. However, I am stumped when it comes to a QGraphicsScene widget imported as a module and sub-widget. I have put some simplified files below. So, QGraphicsView (from the QGraphicsScene) will be the actual widget I need to emit and signal events to other QWidgets inside the main window.

If I have all classes in one file, it works but if I have the classes as separate modules, I get "does not have attribute" errors, specifically in the simple version here for QGraphicsScene .viewport

```<code>Attribute Error "self.graphicsView.viewport().installEventFilter(self)"
</code>```

I guess that the composite graphics widget is actually now a QWidget and I am not initialising the imported module functions/attributes for the QGraphicsView element. Thing is, I want it to exist that way so I can separate the GUI elements and functions of different modules. The others I have used so far have been straightforward QWidget to QWidget signals derived from QObjects, so work fine, but I haven't been able to achieve the same with the imported QGraphicsScene to QWidgets since it errors when it tries to reach QGraphicsView within the main window. Again, all fine if all classes exist in one large file.

Any kind person can point out my error here? How can I separate the module scripts to behave the same way as the single script?

Working single script:

```<code># QWidgetAll.py
from PySide import QtGui, QtCore

class GraphicsView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget")
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.viewport().installEventFilter(self)
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsLabel)
        layout.addWidget(self.edit)
        layout.addWidget(self.graphicsView)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.graphicsView.viewport()):
            pos = event.pos()
            self.edit.setText('x: %d, y: %d' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = GraphicsView()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())
</code>```

The same file as separate modules. qWidgetView.py errors with attribute error:

```<code># qWidgetView.py
from PySide import QtGui, QtCore
from qGraphicView import GraphicsView

class WidgetView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = GraphicsView()
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.viewport().installEventFilter(self)
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.graphicsView)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.graphicsView.viewport()):
            pos = event.pos()
            self.edit.setText('x: %d, y: %d' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = WidgetView()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())
</code>```

with imported qGraphicView.py module:

```<code># qGraphicView.py
from PySide import QtGui, QtCore

class GraphicsView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget")
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsLabel)
        layout.addWidget(self.graphicsView)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = GraphicsView()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())
</code>```

答:
You need to filter events for the QGraphicsView that is a child widget of the GraphicsView class, because you only want mouse-moves on the graphics-view itself, not the whole container widget. So I would suggest something like this:

The qGraphicView.py module:

```<code>class GraphicsView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsView.setMouseTracking(True)
        self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget")
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsLabel)
        layout.addWidget(self.graphicsView)

    def viewport(self):
        return self.graphicsView.viewport()
</code>```

The qWidgetView.py module:

```<code>class WidgetView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = GraphicsView()
        self.graphicsView.viewport().installEventFilter(self)
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.graphicsView)
</code>```

Body:
I have communications working between similar widgets from imported child widgets and the parent main window and widgets. However, I am stumped when it comes to a QGraphicsScene widget imported as a module and sub-widget. I have put some simplified files below. So, QGraphicsView (from the QGraphicsScene) will be the actual widget I need to emit and signal events to other QWidgets inside the main window.

If I have all classes in one file, it works but if I have the classes as separate modules, I get "does not have attribute" errors, specifically in the simple version here for QGraphicsScene .viewport

Attribute Error "self.graphicsView.viewport().installEventFilter(self)"

I guess that the composite graphics widget is actually now a QWidget and I am not initialising the imported module functions/attributes for the QGraphicsView element. Thing is, I want it to exist that way so I can separate the GUI elements and functions of different modules. The others I have used so far have been straightforward QWidget to QWidget signals derived from QObjects, so work fine, but I haven't been able to achieve the same with the imported QGraphicsScene to QWidgets since it errors when it tries to reach QGraphicsView within the main window. Again, all fine if all classes exist in one large file.

Any kind person can point out my error here? How can I separate the module scripts to behave the same way as the single script?

Working single script:

# QWidgetAll.py
from PySide import QtGui, QtCore

class GraphicsView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget")
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.viewport().installEventFilter(self)
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsLabel)
        layout.addWidget(self.edit)
        layout.addWidget(self.graphicsView)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.graphicsView.viewport()):
            pos = event.pos()
            self.edit.setText('x: %d, y: %d' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = GraphicsView()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())

The same file as separate modules. qWidgetView.py errors with attribute error:

# qWidgetView.py
from PySide import QtGui, QtCore
from qGraphicView import GraphicsView

class WidgetView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = GraphicsView()
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.viewport().installEventFilter(self)
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.graphicsView)

    def eventFilter(self, source, event):
        if (event.type() == QtCore.QEvent.MouseMove and
            source is self.graphicsView.viewport()):
            pos = event.pos()
            self.edit.setText('x: %d, y: %d' % (pos.x(), pos.y()))
        return QtGui.QWidget.eventFilter(self, source, event)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = WidgetView()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())

with imported qGraphicView.py module:

# qGraphicView.py
from PySide import QtGui, QtCore

class GraphicsView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget")
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsLabel)
        layout.addWidget(self.graphicsView)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    window = GraphicsView()
    window.show()
    window.resize(200, 100)
    sys.exit(app.exec_())

Body:
You need to filter events for the QGraphicsView that is a child widget of the GraphicsView class, because you only want mouse-moves on the graphics-view itself, not the whole container widget. So I would suggest something like this:

The qGraphicView.py module:

class GraphicsView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = QtGui.QGraphicsView(self)
        self.graphicsView.setMouseTracking(True)
        self.graphicsLabel = QtGui.QLabel("Graphics View within QWidget")
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.graphicsLabel)
        layout.addWidget(self.graphicsView)

    def viewport(self):
        return self.graphicsView.viewport()

The qWidgetView.py module:

class WidgetView(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.graphicsView = GraphicsView()
        self.graphicsView.viewport().installEventFilter(self)
        self.edit = QtGui.QLineEdit(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.graphicsView)


答:
```<code>SELECT  GREATEST(ship_date - due_date, 0) AS DaysTaken
</code>```

Title: Conditional values for calculated column in MySql


问:
JavaScript: Uncaught TypeError: Cannot read property 'appendChild' of null
I am a beginner and I am currently working on a memory card game. Help me, please.

Here is my code to which the error message applies:

HTML

```<code><div id="game-board" class="board clearfix"></div>
</code>```

Javascript

```<code>var createBoard = function() {
    for (var i = 0; i < cards.length; i++) {
        var cardElement = document.createElement('img');
        cardElement.setAttribute('src', "images/back.png");
        cardElement.setAttribute('data-id', i);
        document.getElementsByTagName('img')[0].addEventListener('click', flipCard);
        document.querySelector('game-board').appendChild(cardElement);
    }
}

createBoard();
</code>```

答:
You can't access elements without attaching them to DOM.. as your code you are creating img tag and trying to access them before appending them.
Here is the modified code

```<code>document.getElementsByTagName('img')[0].addEventListener('click', flipCard);
document.querySelector('game-board').appendChild(cardElement);
</code>```

var createBoard = function() {
    for (var i = 0; i < 5; i++) {
        var cardElement = document.createElement('img');
        cardElement.setAttribute('src', "images/back.png");
        cardElement.setAttribute('data-id', i);

        document.querySelector('.game-board').appendChild(cardElement);
        document.getElementsByTagName('img')[0].addEventListener('click', cardElement);
    }
}

createBoard();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='game-board' class='game-board'></div></code>```

Body:
I am a beginner and I am currently working on a memory card game. Help me, please.

Here is my code to which the error message applies:

HTML

Javascript

var createBoard = function() {
    for (var i = 0; i < cards.length; i++) {
        var cardElement = document.createElement('img');
        cardElement.setAttribute('src', "images/back.png");
        cardElement.setAttribute('data-id', i);
        document.getElementsByTagName('img')[0].addEventListener('click', flipCard);
        document.querySelector('game-board').appendChild(cardElement);
    }
}

createBoard();

Body:
You can't access elements without attaching them to DOM.. as your code you are creating img tag and trying to access them before appending them.
Here is the modified code

document.getElementsByTagName('img')[0].addEventListener('click', flipCard);
document.querySelector('game-board').appendChild(cardElement);

var createBoard = function() {
    for (var i = 0; i < 5; i++) {
        var cardElement = document.createElement('img');
        cardElement.setAttribute('src', "images/back.png");
        cardElement.setAttribute('data-id', i);

        document.querySelector('.game-board').appendChild(cardElement);
        document.getElementsByTagName('img')[0].addEventListener('click', cardElement);
    }
}

createBoard();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='game-board' class='game-board'></div>


问:
Raycast or timing or lag?
So i'm running a test on a raycast physics handler from a tutorial. I am dropping a block from the same height each simulation with the goal to have the block land on top of a flat surface in one smooth motion. Currently, I have raycasts projecting out of the bottom of the box through a skin width with the raylength scaling off the velocity.y as seen below:

```<code>rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x);
//Sends out the ray at its respective spot an length

RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);
Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

//If the ray hits, make velocity = distance to the hit distance - skin width
//Also reset the rayLength for edge height discrepencies
if (hit)
{
    //Reports the very first hit.distance and velocity.y at the first hit
    if (!temp && hit.distance != 0)
    {
        Debug.Log(hit.distance);
        Debug.Log(velocity.y);
        temp = true;
    }

    velocity.y = (hit.distance - skinWidth) * directionY;
    rayLength = hit.distance;
}
</code>```

My problem is that when i run this simulation over and over, about half the time when the block collides with the flat surface it produces this initial "stopping force" a bit above the surface, and then the gravity on the block restarts and pulls it directly onto the surface.

So basically, sometimes it is sensing a collision at higher distances than other times forcing it to stop mid-air too early. I have mapped this out by watching the Debug.Log on the hit.distance and velocity.y. The times where this unfavorable effect happens, the hit.distance is above 0.1 and the velocity.y is about -9.56, while the times that are favorable the hit.distance is somewhere below 0.1 and the velocity.y is -9.67.

What is causing this difference in the simulation heights and numbers when i am not changing the system at all? Is it lag in the editor or something that needs to be accounted for? Will it show up on a mobile App?

Thanks for your help.

答:
As comments confirmed, my suspicion was true:

You are running this code in Update() not FixedUpdate() and therefore it isn't synchronized with the physics engine. The discrepancy (at a sub-update interval) caused the Update loop's code to execute early, imparting too much force, so by the time the physics simulation ran (on FixedUpdate's schedule) the object was still too high and gravity took over once more.

The only solution is to move your code to FixedUpdate()

Title: Raycast or timing or lag?

Body:
So i'm running a test on a raycast physics handler from a tutorial. I am dropping a block from the same height each simulation with the goal to have the block land on top of a flat surface in one smooth motion. Currently, I have raycasts projecting out of the bottom of the box through a skin width with the raylength scaling off the velocity.y as seen below:

rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x);
//Sends out the ray at its respective spot an length

RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask);
Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red);

//If the ray hits, make velocity = distance to the hit distance - skin width
//Also reset the rayLength for edge height discrepencies
if (hit)
{
    //Reports the very first hit.distance and velocity.y at the first hit
    if (!temp && hit.distance != 0)
    {
        Debug.Log(hit.distance);
        Debug.Log(velocity.y);
        temp = true;
    }

    velocity.y = (hit.distance - skinWidth) * directionY;
    rayLength = hit.distance;
}

My problem is that when i run this simulation over and over, about half the time when the block collides with the flat surface it produces this initial "stopping force" a bit above the surface, and then the gravity on the block restarts and pulls it directly onto the surface.

So basically, sometimes it is sensing a collision at higher distances than other times forcing it to stop mid-air too early. I have mapped this out by watching the Debug.Log on the hit.distance and velocity.y. The times where this unfavorable effect happens, the hit.distance is above 0.1 and the velocity.y is about -9.56, while the times that are favorable the hit.distance is somewhere below 0.1 and the velocity.y is -9.67.

What is causing this difference in the simulation heights and numbers when i am not changing the system at all? Is it lag in the editor or something that needs to be accounted for? Will it show up on a mobile App?

Thanks for your help.


问:
PHP - Store a SELECT Query and use it inside a INSERT query
Hi i'm having trouble using the data from a select query inside a insert query.

This is my php code -

```<code>   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbName = "arestaurant";

    $ID = $_GET["Id"];
    $QUANTITY = $_GET["Quantity"];
    $TABLE = $_GET["Table"];

    //Make connection
    $conn = new mysqli($servername,$username,$password,$dbName);
    // check connection
    if(!$conn) {
        die("Connection Failed. ".mysqli_connect_error());
    }

    $sql = "INSERT INTO tableorders (tableNumber,isPaid)
            VALUES ('".$TABLE."','0')";
    $result = mysqli_query($conn,$sql);

    $y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
    $resulty = mysqli_query($conn,$y);

    if ($resulty !== false) {
    $value = mysqli_fetch_field($resulty);
    $orderid = $value['orderId']; < --  error

}

    $sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
            VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
    $result2 = mysqli_query($conn,$sqlquery);

?>
</code>```

but im getting -

Fatal error: Cannot use object of type stdClass as array on line 30.

I have several ways in storing it and then using it again, but i can seem to find the solution.

please help?

答:
If you wants get data of column please use fetch assoc like this: </p>

```<code>$y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
$resulty = mysqli_query($conn,$y);

if ($resulty !== false) {
    $fila = $resultado->fetch_assoc()
    $orderid = $fila['orderId'];
}
</code>```

Body:
Hi i'm having trouble using the data from a select query inside a insert query.

This is my php code -

   <?php
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbName = "arestaurant";

    $ID = $_GET["Id"];
    $QUANTITY = $_GET["Quantity"];
    $TABLE = $_GET["Table"];

    //Make connection
    $conn = new mysqli($servername,$username,$password,$dbName);
    // check connection
    if(!$conn) {
        die("Connection Failed. ".mysqli_connect_error());
    }

    $sql = "INSERT INTO tableorders (tableNumber,isPaid)
            VALUES ('".$TABLE."','0')";
    $result = mysqli_query($conn,$sql);

    $y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
    $resulty = mysqli_query($conn,$y);

    if ($resulty !== false) {
    $value = mysqli_fetch_field($resulty);
    $orderid = $value['orderId']; < --  error

}

    $sqlquery = "INSERT INTO orderitems (orderId, productId, quantity)
            VALUES ('".$orderid."','".$ID."','".$QUANTITY."')";
    $result2 = mysqli_query($conn,$sqlquery);

?>

but im getting -

Fatal error: Cannot use object of type stdClass as array on line 30.

I have several ways in storing it and then using it again, but i can seem to find the solution.

please help?

Body:
If you wants get data of column please use fetch assoc like this:

$y = "SELECT orderId from tableorders WHERE tableNumber='$TABLE' ORDER by orderDate DESC limit 1 offset 0 ";
$resulty = mysqli_query($conn,$y);

if ($resulty !== false) {
    $fila = $resultado->fetch_assoc()
    $orderid = $fila['orderId'];
}


问:
Conflicting layout constraints, translatesAutoresizingMaskIntoConstraints not working
First of all, this is what I want to achieve:

The view needs to be centered, with a height of 200. The trailing an leading anchors should touch the layoutmargins. I am creating my constraints programatically.

```<code>import UIKit

class CustomView: UIView {

    var dialogView : UIView!

    func show()
    {
        UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
        dialogView = UIView()
        dialogView.translatesAutoresizingMaskIntoConstraints = false

        dialogView.backgroundColor = .red
        addSubview(dialogView)

        let dialogViewCenterYConstraint = dialogView.centerYAnchor.constraint(equalTo: self.centerYAnchor)
        dialogViewCenterYConstraint.isActive = true

        let dialogViewHeightConstraint = dialogView.heightAnchor.constraint(equalToConstant: 200)
        dialogViewHeightConstraint.isActive = true

        let margins = self.layoutMarginsGuide

        let dialogViewLeadingConstraint = dialogView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
        dialogViewLeadingConstraint.isActive = true

        let dialogViewTrailingConstraint = dialogView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
        dialogViewTrailingConstraint.isActive = true
    }

    override func layoutSubviews() {
        frame = UIScreen.main.bounds
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        CustomView().show()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

It is working, but it also prints the following warning:

```<code>[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x60000009ee60 h=--& v=--& ArtAlertView.CustomView:0x7f9f86c0f770.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000009ed20 UIView:0x7f9f86c100d0.leading == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>",
    "<NSLayoutConstraint:0x60000009eb90 'UIView-leftMargin-guide-constraint' H:|-(8)-[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>",
    "<NSLayoutConstraint:0x60000009ec30 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide']-(8)-|(LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
</code>```

I noticed one of the constraints is an NSAutoresizingMaskLayoutConstraint. I thought setting translatesAutoresizingMaskIntoConstraints to false would get rid of these.

Any thoughts?

答:
Try the following:

```<code>func addSubview(_ view: UIView, with height: CGFloat = 200.0)
{
    //  Check whether superview is non-nil
    if view.superview != nil
    {
        view.removeFromSuperview()
    }
    //  Add self to view as subview
    self.addSubview(view)
    //  translatesAutoresizingMaskIntoConstraints is true by default, which breaks UIView.addConstraints() function
    view.translatesAutoresizingMaskIntoConstraints = false
    //  Create constraints
    let centerY = NSLayoutConstraint(item: view,
                                     attribute: .centerY,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .centerY,
                                     multiplier: 1,
                                     constant: constants.top)
    let leading = NSLayoutConstraint(item: view,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .leading,
                                     multiplier: 1,
                                     constant: constants.leading)
    let trailing = NSLayoutConstraint(item: view,
                                      attribute: .trailing,
                                      relatedBy: .equal,
                                      toItem: self,
                                      attribute: .trailing,
                                      multiplier: 1,
                                      constant: constants.trailing)
    //  Add constraints to superview and return them
    self.addConstraints([top, bottom, leading, trailing])

    let height = NSLayoutConstraint(item: view,
                                    attribute: .height,
                                    relatedBy: .equal,
                                    toItem: nil,
                                    attribute: nil,
                                    multiplier: 1,
                                    constant: height)
    view.addConstraints([height])
}
</code>```

I'm not sure that this exact text will work however (height constraint in untested). The idea is to create new constraints for leading, trailing and centerY and add those to your CustomView intance. Height constraint must be added to the dialogView.

Body:
First of all, this is what I want to achieve:

The view needs to be centered, with a height of 200. The trailing an leading anchors should touch the layoutmargins. I am creating my constraints programatically.

import UIKit

class CustomView: UIView {

    var dialogView : UIView!

    func show()
    {
        UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(self)
        dialogView = UIView()
        dialogView.translatesAutoresizingMaskIntoConstraints = false

        dialogView.backgroundColor = .red
        addSubview(dialogView)

        let dialogViewCenterYConstraint = dialogView.centerYAnchor.constraint(equalTo: self.centerYAnchor)
        dialogViewCenterYConstraint.isActive = true

        let dialogViewHeightConstraint = dialogView.heightAnchor.constraint(equalToConstant: 200)
        dialogViewHeightConstraint.isActive = true

        let margins = self.layoutMarginsGuide

        let dialogViewLeadingConstraint = dialogView.leadingAnchor.constraint(equalTo: margins.leadingAnchor)
        dialogViewLeadingConstraint.isActive = true

        let dialogViewTrailingConstraint = dialogView.trailingAnchor.constraint(equalTo: margins.trailingAnchor)
        dialogViewTrailingConstraint.isActive = true
    }

    override func layoutSubviews() {
        frame = UIScreen.main.bounds
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        CustomView().show()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

It is working, but it also prints the following warning:

[LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
    (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSAutoresizingMaskLayoutConstraint:0x60000009ee60 h=--& v=--& ArtAlertView.CustomView:0x7f9f86c0f770.width == 0   (active)>",
    "<NSLayoutConstraint:0x60000009ed20 UIView:0x7f9f86c100d0.leading == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.leading   (active)>",
    "<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>",
    "<NSLayoutConstraint:0x60000009eb90 'UIView-leftMargin-guide-constraint' H:|-(8)-[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'](LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>",
    "<NSLayoutConstraint:0x60000009ec30 'UIView-rightMargin-guide-constraint' H:[UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide']-(8)-|(LTR)   (active, names: '|':ArtAlertView.CustomView:0x7f9f86c0f770 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x60000009ed70 UIView:0x7f9f86c100d0.trailing == UILayoutGuide:0x6000001b8b80'UIViewLayoutMarginsGuide'.trailing   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

I noticed one of the constraints is an NSAutoresizingMaskLayoutConstraint. I thought setting translatesAutoresizingMaskIntoConstraints to false would get rid of these.

Any thoughts?

Body:
Try the following:

func addSubview(_ view: UIView, with height: CGFloat = 200.0)
{
    //  Check whether superview is non-nil
    if view.superview != nil
    {
        view.removeFromSuperview()
    }
    //  Add self to view as subview
    self.addSubview(view)
    //  translatesAutoresizingMaskIntoConstraints is true by default, which breaks UIView.addConstraints() function
    view.translatesAutoresizingMaskIntoConstraints = false
    //  Create constraints
    let centerY = NSLayoutConstraint(item: view,
                                     attribute: .centerY,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .centerY,
                                     multiplier: 1,
                                     constant: constants.top)
    let leading = NSLayoutConstraint(item: view,
                                     attribute: .leading,
                                     relatedBy: .equal,
                                     toItem: self,
                                     attribute: .leading,
                                     multiplier: 1,
                                     constant: constants.leading)
    let trailing = NSLayoutConstraint(item: view,
                                      attribute: .trailing,
                                      relatedBy: .equal,
                                      toItem: self,
                                      attribute: .trailing,
                                      multiplier: 1,
                                      constant: constants.trailing)
    //  Add constraints to superview and return them
    self.addConstraints([top, bottom, leading, trailing])

    let height = NSLayoutConstraint(item: view,
                                    attribute: .height,
                                    relatedBy: .equal,
                                    toItem: nil,
                                    attribute: nil,
                                    multiplier: 1,
                                    constant: height)
    view.addConstraints([height])
}

I'm not sure that this exact text will work however (height constraint in untested). The idea is to create new constraints for leading, trailing and centerY and add those to your CustomView intance. Height constraint must be added to the dialogView.


问:
Making Object using JSON.stringify
I can't seem to access object data after JSON.stringify. I'm getting undefined with console.log(data[0].colour)

```<code>let data = [];
let colours = ['#340068' , '#ff6978' , '#fffcf9' , '#b1ede8' , '#6d435a']
let names = ['coffee' , 'cake' , 'holiday' , 'break' , 'lunch']

var result = colours.map(function(element , i){
  data.push(`{'colour' : '${element}','name' : '${names[i]}'}`)
})
</code>```

Thanks in advance

```<code>JSON.stringify(data)

console.log(data[0].colour)
</code>```

答:
First and Foremost  single quotes

'

represents character.... for string use double quotes

"

Secondly
JSON stringify doesn't get objects...

JSON.PARSE on a valid JSON String makes the JSON object..

let data = [];
let colours = ['#340068' , '#ff6978' , '#fffcf9' , '#b1ede8' , '#6d435a']
let names = ['coffee' , 'cake' , 'holiday' , 'break' , 'lunch']

var result = colours.map(function(element , i){
var item = `{"colour" : "${element}","name" : "${names[i]}"}`;
var itemstr = JSON.stringify(item);
var itemObj = JSON.parse(itemstr);
 data.push(itemObj) //replaced '
})

var FirstItemOBj = JSON.parse(data[0]);
console.log(FirstItemOBj.colour);  //  gets the first object of strings
 ```

Title: Making Object using JSON.stringify

Body:
I can't seem to access object data after JSON.stringify. I'm getting undefined with console.log(data[0].colour)

let data = [];
let colours = ['#340068' , '#ff6978' , '#fffcf9' , '#b1ede8' , '#6d435a']
let names = ['coffee' , 'cake' , 'holiday' , 'break' , 'lunch']

var result = colours.map(function(element , i){
  data.push(`{'colour' : '${element}','name' : '${names[i]}'}`)
})

Thanks in advance

JSON.stringify(data)

console.log(data[0].colour)