问:
Convert : to comma separated value
I came across a row which has multiple values separated by a colon (:).
SQL considers the values to be one and throws an error" Cannot fine the requested Privilege". Example of the row shown below.

```<code>Servername  Instancename    Databasename Environment userid      access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV       userid SYSADMIN:SERVERADMIN
</code>```

Here 2 roles are requested seperated by :
Need some assistance on how can we make SQL consider the values different?

答:
You could also differentiate them

```<code>SELECT Servername,
       Instancename,
       Databasename,
       Environment,
       userid,
       a.value('.', 'VARCHAR(MAX)') [access]
FROM
(
    SELECT Servername,
           Instancename,
           Databasename,
           Environment,
           userid,
           CAST('<A>'+REPLACE(access, ':', '</A><A>')+'</A>' AS XML) AS access
    FROM <table>
) A
CROSS APPLY access.nodes('/A') AS split(a);
</code>```

Result :

```<code>Servername      Instancename    Databasename Environment userid   access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV          userid      SYSADMIN
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV          userid      SERVERADMIN
</code>```

Title: Convert : to comma separated value

Body:
I came across a row which has multiple values separated by a colon (:).
SQL considers the values to be one and throws an error" Cannot fine the requested Privilege". Example of the row shown below.

Servername  Instancename    Databasename Environment userid      access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV       userid SYSADMIN:SERVERADMIN

Here 2 roles are requested seperated by :
Need some assistance on how can we make SQL consider the values different?

Body:
You could also differentiate them

SELECT Servername,
       Instancename,
       Databasename,
       Environment,
       userid,
       a.value('.', 'VARCHAR(MAX)') [access]
FROM
(
    SELECT Servername,
           Instancename,
           Databasename,
           Environment,
           userid,
           CAST('<A>'+REPLACE(access, ':', '</A><A>')+'</A>' AS XML) AS access
    FROM <table>
) A
CROSS APPLY access.nodes('/A') AS split(a);

Result :

Servername      Instancename    Databasename Environment userid   access
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV          userid      SYSADMIN
ITSUSMPW01430   ITSUSMPW01430   ALL        DEV          userid      SERVERADMIN


来源: stackexchange

问:
Map Promise.all output with promises index
I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

```<code>let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);
</code>```

Here I get all the collected response of all the responses, but I actually want to map this by user.
For example currently I am getting data in this format:

```<code>[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]
</code>```

But I want data in this format:

```<code>[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]
</code>```

I am sure there must be a way to map every promise by user, but I am not aware of.

答:
as described here
How to use Promise.all with an object as input

Here is a simple ES2015 function that takes an object with properties that might be promises and returns a promise of that object with resolved properties.

```<code>function promisedProperties(object) {

  let promisedProperties = [];
  const objectKeys = Object.keys(object);

  objectKeys.forEach((key) => promisedProperties.push(object[key]));

  return Promise.all(promisedProperties)
    .then((resolvedValues) => {
      return resolvedValues.reduce((resolvedObject, property, index) => {
        resolvedObject[objectKeys[index]] = property;
        return resolvedObject;
      }, object);
    });

}
</code>```

And then you will use it like so:

```<code>var promisesObject = {};
users.map((element, index) => object[element] = this.myApiHelper.getUsersData(users[index]));
promisedProperties(object).then(response => console.log(response));
</code>```

Note that first of all you need an object with key/promise.

ContentLicense: CC BY-SA 3.0

Body:
I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);

Here I get all the collected response of all the responses, but I actually want to map this by user.
For example currently I am getting data in this format:

[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]

But I want data in this format:

[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]

I am sure there must be a way to map every promise by user, but I am not aware of.

Body:
as described here
How to use Promise.all with an object as input

Here is a simple ES2015 function that takes an object with properties that might be promises and returns a promise of that object with resolved properties.

function promisedProperties(object) {

  let promisedProperties = [];
  const objectKeys = Object.keys(object);

  objectKeys.forEach((key) => promisedProperties.push(object[key]));

  return Promise.all(promisedProperties)
    .then((resolvedValues) => {
      return resolvedValues.reduce((resolvedObject, property, index) => {
        resolvedObject[objectKeys[index]] = property;
        return resolvedObject;
      }, object);
    });

}

And then you will use it like so:

var promisesObject = {};
users.map((element, index) => object[element] = this.myApiHelper.getUsersData(users[index]));
promisedProperties(object).then(response => console.log(response));

Note that first of all you need an object with key/promise.


问:
C# constraint generic parameter to a T<T2> for Fluent interface / compiler can't infer types
WCF client classes are typically setup like:

```<code>public class Client : ClientBase<IService>, IService
</code>```

I want to extend these clients with an extension method that is Fluent, so that I can declare a using statement like:

```<code>using (new Client().WithCookies(...)) {}
</code>```

However, I can't figure out a way to maintain the original Type of the caller, without creating some rather clunky calling syntax:

```<code>new Client().WithCookies<Client,IService>(...)
</code>```

I'm not sure why the compiler can't infer the T based on what I've passed in, but it can't, based on the definition of the extension method:

```<code>public static T WithCookies<T, TChannel>(this T clientBase, IEnumerable<Cookie> cookies)
   where T : ClientBase<TChannel>, TChannel
   where TChannel : class
{
   HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
   requestProperty.Headers.Add(HttpCookieHeader, string.Join("; ", cookies.Select(c => c.ToCookieString(false))));

   new OperationContext(clientBase.InnerChannel).OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
   return clientBase;
}
</code>```

I know Eric Lippert in his blog, dismisses the notion of specifying a 'I don't care what the type argument to the generic is' (and for generally good reasons)
http://blogs.msdn.com/b/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx

A psuedo-implementation would be something like:

```<code>public static T WithCookies<T>(this T clientBase, IEnumerable<Cookie> cookies)
   where T : ClientBase<>
{
   HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
   requestProperty.Headers.Add(HttpCookieHeader, string.Join("; ", cookies.Select(c => c.ToCookieString(false))));

   new OperationContext(clientBase.InnerChannel).OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
   return clientBase;
}
</code>```

This is one scenario where it seems to me a good fit, as I don't care what TChannel is -- I'm not going to use it in my code, I just want to use any ClientBase<> as a constraint.

With that said, can anyone come up with a creative way to implement my Fluent requirement without the specification of the Types?

Keep in mind that if you don't return the original item passed in, you lose the ability to call service methods implemented in IService.

答:
This was answered in another thread by Eric Lippert -

Generic extension method : Type argument cannot be inferred from the usage

The short answer is, compiler inference doesn't work like that unfortunately.

More details on his blog:
http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

ContentLicense: CC BY-SA 2.5

Body:
WCF client classes are typically setup like:

public class Client : ClientBase<IService>, IService

I want to extend these clients with an extension method that is Fluent, so that I can declare a using statement like:

using (new Client().WithCookies(...)) {}

However, I can't figure out a way to maintain the original Type of the caller, without creating some rather clunky calling syntax:

new Client().WithCookies<Client,IService>(...)

I'm not sure why the compiler can't infer the T based on what I've passed in, but it can't, based on the definition of the extension method:

public static T WithCookies<T, TChannel>(this T clientBase, IEnumerable<Cookie> cookies)
   where T : ClientBase<TChannel>, TChannel
   where TChannel : class
{
   HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
   requestProperty.Headers.Add(HttpCookieHeader, string.Join("; ", cookies.Select(c => c.ToCookieString(false))));

   new OperationContext(clientBase.InnerChannel).OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
   return clientBase;
}

I know Eric Lippert in his blog, dismisses the notion of specifying a 'I don't care what the type argument to the generic is' (and for generally good reasons)
http://blogs.msdn.com/b/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx

A psuedo-implementation would be something like:

public static T WithCookies<T>(this T clientBase, IEnumerable<Cookie> cookies)
   where T : ClientBase<>
{
   HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty();
   requestProperty.Headers.Add(HttpCookieHeader, string.Join("; ", cookies.Select(c => c.ToCookieString(false))));

   new OperationContext(clientBase.InnerChannel).OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty;
   return clientBase;
}

This is one scenario where it seems to me a good fit, as I don't care what TChannel is -- I'm not going to use it in my code, I just want to use any ClientBase<> as a constraint.

With that said, can anyone come up with a creative way to implement my Fluent requirement without the specification of the Types?

Keep in mind that if you don't return the original item passed in, you lose the ability to call service methods implemented in IService.


问:
Memory leak c++ list of array
We have code like this:

```<code>  void main(){
  std::list<int *> ll;
  for(int i=0;i<100;i++)
   {
      int *a = new int[10000];
      ll.push_back(a);
   }
  for(int *b : ll)
  {
     delete [] b;
  }
 ll.clear();

}
</code>```

But the memory not free?
Why?
When run this code work correctly:

```<code>void main(){
 for(int i=0;i<100;i++)
 {
     int *a = new int[10000];
     delete [] a;
 }
}
</code>```

I monitor memory with top command in linux and system monitoring, so in first code in first for the memory was going up and after that i expect that in last for the app free the memory but not free memory.

答:
Like others said valgrind is the appropriate tool to use when tracking down memory leaks. Using valgrind on your program indeed shows that you have no memory leak:</p>

```<code>    $ valgrind --leak-check=yes ./example
==3945== Memcheck, a memory error detector
==3945== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3945== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==3945== Command: ./example
==3945==
==3945==
==3945== HEAP SUMMARY:
==3945==     in use at exit: 0 bytes in 0 blocks
==3945==   total heap usage: 200 allocs, 200 frees, 4,002,400 bytes allocated
==3945==
==3945== All heap blocks were freed -- no leaks are possible
==3945==
==3945== For counts of detected and suppressed errors, rerun with: -v
==3945== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Title: Memory leak c++ list of array

Body:
We have code like this:

  void main(){
  std::list<int *> ll;
  for(int i=0;i<100;i++)
   {
      int *a = new int[10000];
      ll.push_back(a);
   }
  for(int *b : ll)
  {
     delete [] b;
  }
 ll.clear();

}

But the memory not free?
Why?
When run this code work correctly:

void main(){
 for(int i=0;i<100;i++)
 {
     int *a = new int[10000];
     delete [] a;
 }
}

I monitor memory with top command in linux and system monitoring, so in first code in first for the memory was going up and after that i expect that in last for the app free the memory but not free memory.

Body:
Like others said valgrind is the appropriate tool to use when tracking down memory leaks. Using valgrind on your program indeed shows that you have no memory leak:

    $ valgrind --leak-check=yes ./example
==3945== Memcheck, a memory error detector
==3945== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==3945== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info
==3945== Command: ./example
==3945==
==3945==
==3945== HEAP SUMMARY:
==3945==     in use at exit: 0 bytes in 0 blocks
==3945==   total heap usage: 200 allocs, 200 frees, 4,002,400 bytes allocated
==3945==
==3945== All heap blocks were freed -- no leaks are possible
==3945==
==3945== For counts of detected and suppressed errors, rerun with: -v
==3945== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)


问:
Node js App integration with power bi rest Api
Is there a way using power bi rest API in node js, I watched video ,Ran Breuer and Arina Hantsis were showing the demo here,Setting up and Getting Started with Power BI Embedded I want to achieve same but using node js, in our development environment we do not use c#.
I found the Node SDK but it saying we no longer support node SDK,Node SDK

Do I have to change development structure from Node js to c#  in order to use power bi Rest API!!

答:
@Jo Joy what is the seen you should know .

https://github.com/Microsoft/PowerBI-Node/issues/40

It about priorities these company decide in which project they do .

They can response very well about this. But as far as discussion there are no such plan to do so . You can access api before feb 2017 .

If newer api you have to try it for your . May be you folk it . We as commundity will contribute .


问:
How to set title of DXRibbonWindow in its center
I'm using DXRibbonwindow like this:

```<code><dxr:DXRibbonWindow  x:Class="MyNameSpace.MyRibbonWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:dxn="http://schemas.devexpress.com/winfx/2008/xaml/navbar"
    xmlns:dxb="http://schemas.devexpress.com/winfx/2008/xaml/bars"
    xmlns:dxd="http://schemas.devexpress.com/winfx/2008/xaml/docking"
    xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol"
    xmlns:dxr="http://schemas.devexpress.com/winfx/2008/xaml/ribbon"
    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
    SnapsToDevicePixels="True"
    WindowStartupLocation="CenterScreen" WindowState="Maximized"
    Title="title">
    <Grid>
        ...
    </Grid>
</dxr:DXRibbonWindow>
</code>```

I want the title to be in the middle of the window's titlebar, but it doesn't, how can i make it? I'm using DevExpress 14.2.5 .

答: This problem occured in version 14.5 of DEVExpress, I upgrade its version to the newest 17.1 then the problem has been solved, thanks for the DevExpress developer.</p>

Body:
I'm using DXRibbonwindow like this:

<dxr:DXRibbonWindow  x:Class="MyNameSpace.MyRibbonWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:dxn="http://schemas.devexpress.com/winfx/2008/xaml/navbar"
    xmlns:dxb="http://schemas.devexpress.com/winfx/2008/xaml/bars"
    xmlns:dxd="http://schemas.devexpress.com/winfx/2008/xaml/docking"
    xmlns:dxlc="http://schemas.devexpress.com/winfx/2008/xaml/layoutcontrol"
    xmlns:dxr="http://schemas.devexpress.com/winfx/2008/xaml/ribbon"
    xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"
    SnapsToDevicePixels="True"
    WindowStartupLocation="CenterScreen" WindowState="Maximized"
    Title="title">
    <Grid>
        ...
    </Grid>
</dxr:DXRibbonWindow>

I want the title to be in the middle of the window's titlebar, but it doesn't, how can i make it? I'm using DevExpress 14.2.5 .


问:
Problems trying to import a .js file in codeigniter
Hello friends I'm having problems trying to use some functions that I have in two .js file. I already tried putting  base_url(); and the location of the file, I also added the 'url' in the config.php

```<code><script type="text/javascript" src="<?php echo base_url();?>js/pdf.js" ></script>
<script type="text/javascript" src="<?php echo base_url();?>js/pdf.worker.js" ></script>
</code>```

I have the file in folder called: js

ERROR I GET ON THE GOOGLE CHROME CONSOLE:

GET http://[::1]/registro/js/pdf.worker.js net::ERR_ABORTED

EDITED
CONSOLE ERROR

答:
Edit /application/config/config.php file

Remove this line
$config['base_url'] = '';

Rdd this code in config.php file

```<code>$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;
</code>```

Edit /application/config/autoload.php file.

```<code>$autoload['helper'] = array('url');
</code>```

Body:
Hello friends I'm having problems trying to use some functions that I have in two .js file. I already tried putting  base_url(); and the location of the file, I also added the 'url' in the config.php

I have the file in folder called: js

ERROR I GET ON THE GOOGLE CHROME CONSOLE:

GET http://[::1]/registro/js/pdf.worker.js net::ERR_ABORTED

EDITED
CONSOLE ERROR

Body:
Edit /application/config/config.php file

Remove this line
$config['base_url'] = '';

Rdd this code in config.php file

$root = "http://".$_SERVER['HTTP_HOST'];
$root .= str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
$config['base_url'] = $root;

Edit /application/config/autoload.php file.

$autoload['helper'] = array('url');


问:
Adding custom methods to standard ruby objects
How can I add custom methods to standard ruby objects, such as strings and integers?

I have seen this in, for example, rails, and the mojinizer library for ruby that can convert a romaji string into hiragana, as in

```<code>"tsukue".hiragana #=> "つくえ"
</code>```

答:
```<code>class String
  def add_exclamation_mark
    self + "!"
  end
end

> "hello".add_exclamation_mark
"hello!"
</code>```

That way you are adding new methods to a String class.

Body:
How can I add custom methods to standard ruby objects, such as strings and integers?

I have seen this in, for example, rails, and the mojinizer library for ruby that can convert a romaji string into hiragana, as in

"tsukue".hiragana #=> "つくえ"

Body:
class String
  def add_exclamation_mark
    self + "!"
  end
end

> "hello".add_exclamation_mark
"hello!"

That way you are adding new methods to a String class.


问:
Exactly what quantifiers is SMT complete for?
I've been looking at various SMT solvers, mainly Z3, CVC4, and VeriT. They all have vague descriptions of their ability to solve SMT problems with quantifiers. Their documentation is primarily example based (Z3), or consists of academic papers, describing possible changes that may or may not actually be implemented.

I know that there are decidable fragments of First-order logic, such as:

Finitely-bounded quantifiers

Monadic first-order logic

What I'd like to know is, which (if any) classes of FOL are the various SMT solvers guaranteed to be complete for? How can I know whether a problem I'm looking at is in the fragments they are complete for?

答:
At the risk of unhelpfully not answering the question, there are reasons why this material is hard to find.

The link between decideability and "actually can solve my specific problem in an amount of time I am willing to wait" is not that strong.  So often examples, sets of benchmarks and experimental results are a better indicator (and thus are presented).

Also, most solvers do an amount of heuristic rewriting and problem manipulation before trying to solve.  So classical, syntactic ways of expressing decideable fragments aren't always applicable as other problems can be rewritten into decieable ones (hopefully not the other way around but I couldn't promise it never happens!).

Finally, many solvers use heuristic semi-decision procedures which work well but are hard to describe in something more formal than code.  Thus there are things that may not appear in any known decideable fragment, but for which answers can be found.


问:
How to compute right kernel of a matrix with Eigen library?
I've started to implementation of an algorithm with Eigen library. I needed to calculate null space(kernel) of a matrix. I have tried with a cube's matrix that,

```<code>0, 0, 1,
0, 1, 0,
1, 0, 0,
-1, 0, 0,
0, 0, -1,
0, -1, 0
</code>```

Then, I call, its source

```<code>A.transposeInPlace();
std::cout << "and after being transposed:\n" << A << std::endl;
FullPivLU<MatrixXf> lu(A);
MatrixXf A_null_space = lu.kernel();
std::cout << "Null space:\n" << A_null_space << std::endl;
A_null_space.transposeInPlace();
std::cout << "Null space Transposed_A:\n" << A_null_space;
</code>```

I obtain,

```<code> 0.5    0   -1    1    0    0    0    0    0  0.5
-0.5    0   -0    0    1    0    0    0    0 -0.5
 0.5    0   -0    0    0    1    0    0    0 -0.5
 0.5    0   -0    0    0    0    1    0    0  0.5
  -1    0    1    0    0    0    0    1    0   -1
-0.5    0    1    0    0    0    0    0    1 -0.5
-0.5    1   -0    0    0    0    0    0    0  0.5
</code>```

But, I realized later on that its right kernel and left kernel is same and seemingly the code snippet calculates left kernel. The code is getting crazy output on the other test case. So, how can be the right kernel be calculated? The link is also to show the difference btw right and left kernels with examples. However, if I remove first line, the output is 0 0 0

Clearly problem of the case is,

```<code>MatrixXf A{10, 3};
A <<
        1, 0, 1 ,
        1, 0, 0 ,
        0, 1, 1 ,
        0, 1, 0 ,
        0, 0, 1 ,
        -1, 0, 0 ,
        0, 0, -1 ,
        0, -1, 1 ,
        0, -1, 0 ,
        -1, 0, 1;
</code>```

Its output is expected as,

```<code> 1  0  0  0  0  0  0 -2  2  1
 0  1  0  0  0  0  0 -1  1  1
 0  0  1  0  0  0  0 -1  2  0
 0  0  0  1  0  0  0  0  1  0
 0  0  0  0  1  0  0 -1  1  0
 0  0  0  0  0  1  0  1 -1 -1
 0  0  0  0  0  0  1  1 -1  0
</code>```

QR factorization,

```<code>HouseholderQR<MatrixXf> qr(A);
    cout << "\nQR matrix to compare \n" << qr.matrixQR().transpose();
</code>```

Then I get,

```<code>   -1.41421           0    0.414214
  -0.707107   -0.707107          -1
  -0.707107    0.707107           1
          0           0           1
  -0.707107    0.707107           0
   0.707107    0.707107           0
   0.707107   -0.707107           0
  -0.707107    0.707107          -1
          0           0          -1
1.19209e-07     1.41421 5.96046e-08
</code>```

@Edit 2, Does Eigen calculate wrongly?

Source

@Edit 3,

I'm really but really confused because both matrix seem right! How come?

答: As you observed, both matrices are valid right kernels. This is because they correspond to two different basis of the same subspace. To check it, you can reduce the two matrices to the reduced row echelon form (rref function in matlab, or see this online calculator). This transformation is unique and does not change the span defined by the matrix. Your reference kernel basis is already in this form. So all you have to do is to reduce the one returned by Eigen and see that it gives you the same matrix as your reference one.

Body:
I've started to implementation of an algorithm with Eigen library. I needed to calculate null space(kernel) of a matrix. I have tried with a cube's matrix that,

0, 0, 1,
0, 1, 0,
1, 0, 0,
-1, 0, 0,
0, 0, -1,
0, -1, 0

Then, I call, its source

A.transposeInPlace();
std::cout << "and after being transposed:\n" << A << std::endl;
FullPivLU<MatrixXf> lu(A);
MatrixXf A_null_space = lu.kernel();
std::cout << "Null space:\n" << A_null_space << std::endl;
A_null_space.transposeInPlace();
std::cout << "Null space Transposed_A:\n" << A_null_space;

I obtain,

 0.5    0   -1    1    0    0    0    0    0  0.5
-0.5    0   -0    0    1    0    0    0    0 -0.5
 0.5    0   -0    0    0    1    0    0    0 -0.5
 0.5    0   -0    0    0    0    1    0    0  0.5
  -1    0    1    0    0    0    0    1    0   -1
-0.5    0    1    0    0    0    0    0    1 -0.5
-0.5    1   -0    0    0    0    0    0    0  0.5

But, I realized later on that its right kernel and left kernel is same and seemingly the code snippet calculates left kernel. The code is getting crazy output on the other test case. So, how can be the right kernel be calculated? The link is also to show the difference btw right and left kernels with examples. However, if I remove first line, the output is 0 0 0

Clearly problem of the case is,

MatrixXf A{10, 3};
A <<
        1, 0, 1 ,
        1, 0, 0 ,
        0, 1, 1 ,
        0, 1, 0 ,
        0, 0, 1 ,
        -1, 0, 0 ,
        0, 0, -1 ,
        0, -1, 1 ,
        0, -1, 0 ,
        -1, 0, 1;

Its output is expected as,

 1  0  0  0  0  0  0 -2  2  1
 0  1  0  0  0  0  0 -1  1  1
 0  0  1  0  0  0  0 -1  2  0
 0  0  0  1  0  0  0  0  1  0
 0  0  0  0  1  0  0 -1  1  0
 0  0  0  0  0  1  0  1 -1 -1
 0  0  0  0  0  0  1  1 -1  0

QR factorization,

HouseholderQR<MatrixXf> qr(A);
    cout << "\nQR matrix to compare \n" << qr.matrixQR().transpose();

Then I get,

   -1.41421           0    0.414214
  -0.707107   -0.707107          -1
  -0.707107    0.707107           1
          0           0           1
  -0.707107    0.707107           0
   0.707107    0.707107           0
   0.707107   -0.707107           0
  -0.707107    0.707107          -1
          0           0          -1
1.19209e-07     1.41421 5.96046e-08

@Edit 2, Does Eigen calculate wrongly?

Source

@Edit 3,

I'm really but really confused because both matrix seem right! How come?


问:
Get a variable from Object Symbol
I have an object that when inspected by Developer Tools Console looks like this:

```<code>console.log("clicked: ", clickedMarker);
</code>```

How can I get the address content form Symbol(vars)?

```<code>console.log("vars: ", clickedMarker["Symbol(vars)"]);
console.log("address: ", clickedMarker.address);
console.log("address2: ", clickedMarker["address"]);
console.log("vars2: ", clickedMarker["vars"]);
console.log("vars3: ", clickedMarker.vars);
console.log("Symbol(vars): ", clickedMarker._objectInstance["Symbol(vars)"]);
</code>```

but it all comes out undefined.

Edit: This is a Typescript application but the Javascript solution worked fine.

答:
The issue is likely that you are looking for a string key instead of a symbol one.

To read more about what a Symbol is (which is a primitive in javascript, anyway), please check this: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Symbol

To solve the issue, find the correct Symbol by using the comfortable toString prototype, and make use of the getOwnPropertySymbols method of the generic Object:

```<code>// look for the symbol having key "vars" in the object's symbols list.
var mFound = Object.getOwnPropertySymbols(clickedMarker._objectInstance)
                   .find(e => e.toString() === "Symbol(vars)");
// Use the above symbol as the object's key.
var address = clickedMarker._objectInstance[mFound].address;
</code>```

Please remember that, for further safety, you should check if mFound is effectively found (hence NOT undefined, or generically not falsey).

Title: Get a variable from Object Symbol

Body:
I have an object that when inspected by Developer Tools Console looks like this:

console.log("clicked: ", clickedMarker);

How can I get the address content form Symbol(vars)?

console.log("vars: ", clickedMarker["Symbol(vars)"]);
console.log("address: ", clickedMarker.address);
console.log("address2: ", clickedMarker["address"]);
console.log("vars2: ", clickedMarker["vars"]);
console.log("vars3: ", clickedMarker.vars);
console.log("Symbol(vars): ", clickedMarker._objectInstance["Symbol(vars)"]);

but it all comes out undefined.

Edit: This is a Typescript application but the Javascript solution worked fine.

Body:
The issue is likely that you are looking for a string key instead of a symbol one.

To read more about what a Symbol is (which is a primitive in javascript, anyway), please check this: https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/Symbol

To solve the issue, find the correct Symbol by using the comfortable toString prototype, and make use of the getOwnPropertySymbols method of the generic Object:

// look for the symbol having key "vars" in the object's symbols list.
var mFound = Object.getOwnPropertySymbols(clickedMarker._objectInstance)
                   .find(e => e.toString() === "Symbol(vars)");
// Use the above symbol as the object's key.
var address = clickedMarker._objectInstance[mFound].address;

Please remember that, for further safety, you should check if mFound is effectively found (hence NOT undefined, or generically not falsey).


问:
Border becomes wider when position it with translate
I want to have a vertical line which always stays in the middle of div container, no matter of screen size, and I also want it to be 1px thin. But when I add transform: translate(-50%, -50%); , I don't know why, but my border becomes fatter then I expected. This is my HTML/CSS code.

.cases-container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    background-color: black;
    width: 480px;
    height: 110px;
    position: relative;
}
.item-border {
    border-left: 1px solid #ff5a00;
    height: 95px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cases-container">

  <div class="item-border"></div>

</div></code>```

So, what is the issue here ?

答:
Here is the updated code for your reference:

List item

.cases-container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    background-color: black;
    width: 480px;
    height: 110px;
    position: relative;
}
.item-border {
    border-left: 1px solid #ff5a00;
    height: 95px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateY(-50%);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="cases-container">

  <div class="item-border"></div>

</div></code>```

Body:
I want to have a vertical line which always stays in the middle of div container, no matter of screen size, and I also want it to be 1px thin. But when I add transform: translate(-50%, -50%); , I don't know why, but my border becomes fatter then I expected. This is my HTML/CSS code.

.cases-container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    background-color: black;
    width: 480px;
    height: 110px;
    position: relative;
}
.item-border {
    border-left: 1px solid #ff5a00;
    height: 95px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

So, what is the issue here ?

Body:
Here is the updated code for your reference:

List item

.cases-container {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    background-color: black;
    width: 480px;
    height: 110px;
    position: relative;
}
.item-border {
    border-left: 1px solid #ff5a00;
    height: 95px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateY(-50%);

<div class="cases-container">

  <div class="item-border"></div>

</div>


问:
Interface between service and activity
I have a service bound to an activity. I defined an interface that is implemented by the activity. In the service I have an object of the interface that implements the activity, i give memory to this object when I call the method that returns the binder.

The service implements socket.io when I receive a message from the server, I call the interface method to update data in the activity.

My question is, am I using bad practices? Should I implement a LocalBroadcastReceiver to communicate with the activity instead of using the interface?

what do you suggest me?

答:
Short answer is yes it is really a bad practice.

Long answer, even though you reference your activity over an interface it's still the same object in the memory. So let's say you have long running operation on your service then when the activity is recreated after a rotation or any kind of configuration change your old reference will be kept in the Service and it will be leaked.

So since your question is too generic I can just list the alternative methods, you can look through all of them and apply whichever fits on your style.

EventBus (Publish/Subscribe pattern, the easiest solution)

Dependency Injection (Use Dagger or similar to inject your model on
both Activity and Service

BroadcastReceiver

Messenger

Title: Interface between service and activity


问:
How do I reverse a list or loop over it backwards?
How do I iterate over a list in reverse in Python?

See also: How can I get a reversed copy of a list (avoid a separate statement when chaining a method after .reverse)?

答:
With reversed and list:

```<code>>>> list1 = [1,2,3]
>>> reversed_list = list(reversed(list1))
>>> reversed_list
>>> [3, 2, 1]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
With reversed and list:

>>> list1 = [1,2,3]
>>> reversed_list = list(reversed(list1))
>>> reversed_list
>>> [3, 2, 1]


问:
Fetch new posts from facebook using Graph API
I am using Graph API to authorize a user with my app to fetch posts from their timeline and from their liked pages.

I'm able to fetch all posts and save them. But, when I fetch again after a period of time it includes both the new posts and old ones which creates duplicate entries. I only want the new posts which are not fetched yet. I know about the webhooks in facebook. But, I want to know any other way to do this just like twitter (using since_id).

NB: I'm using spring-social-facebook for these operations.

Looking for some ideas.

答:
I think that you can use since and until parameters to filter the results. Try this call: https://developers.facebook.com/tools/explorer/135669679827333/?method=GET&path=me%2Ffeed%3Fsince%3D1%20january%202017%26until%3Dnow&version=v2.5

You can store your lastUpdateDate and then use since lastUpdateDate until now.


问:
How do I configure MPU registers in cortex m4?
I want to add a protection to a region of a memory, starting from 0x20000000. The size of the region is 64 bytes. Permission is read only, no flag set except xn. Here's how I think it should be,

```<code>#define MPU_CTRL         (*((volatile unsigned long*) 0xE000ED94))    // MPU Control register
#define MPU_RNR          (*((volatile unsigned long*) 0xE000ED98))    // MPU Region Number register
#define MPU_RBAR         (*((volatile unsigned long*) 0xE000ED9C))    // MPU Region Base Address Register
#define MPU_RASR         (*((volatile unsigned long*) 0xE000EDA0))    // MPU Region attributes and size register

void Registers_Init(void)
{
    //MPU Configuring
    MPU_RNR = 0x00000000;                       // use region 0
    MPU_RBAR = 0x20000000;                      // base address is 0x20000000
    MPU_RASR = 0x1608FF0B;                      // enable bit=1, 64 bytes,not subregions, s=c=b=0, xn=1, permission= ro/ro.
    MPU_CTRL = 0x00000005;                      // enable memory protection unit,guaranteeing default priviliged access
}

int main()
{
    Registers_Init();
    return 0;
}
</code>```

Is this correct? Am I doing it wrong? Please guide.

答:
Yes this looks correct to configure a region. However you have disabled all the sub-regions which mean you will not have any access to this memory block. The sub-region disable bits should be 0 (enabled). You have also set privileged and unprivileged read only.

You don't have to use the RNR register as you can use the VALID and REGION fields in the RBAR register instead.

If at any point you change to unprivileged  mode you will not have any access to you code or data memory (other than is what is defined in the region) so you will get an MPU fault. I would suggest adding an MPU fault handler if you have not already and possibly defining a read only region to allow access to all of the flash (although you already have privileged access through the background region).

Body:
I want to add a protection to a region of a memory, starting from 0x20000000. The size of the region is 64 bytes. Permission is read only, no flag set except xn. Here's how I think it should be,

#define MPU_CTRL         (*((volatile unsigned long*) 0xE000ED94))    // MPU Control register
#define MPU_RNR          (*((volatile unsigned long*) 0xE000ED98))    // MPU Region Number register
#define MPU_RBAR         (*((volatile unsigned long*) 0xE000ED9C))    // MPU Region Base Address Register
#define MPU_RASR         (*((volatile unsigned long*) 0xE000EDA0))    // MPU Region attributes and size register

void Registers_Init(void)
{
    //MPU Configuring
    MPU_RNR = 0x00000000;                       // use region 0
    MPU_RBAR = 0x20000000;                      // base address is 0x20000000
    MPU_RASR = 0x1608FF0B;                      // enable bit=1, 64 bytes,not subregions, s=c=b=0, xn=1, permission= ro/ro.
    MPU_CTRL = 0x00000005;                      // enable memory protection unit,guaranteeing default priviliged access
}

int main()
{
    Registers_Init();
    return 0;
}

Is this correct? Am I doing it wrong? Please guide.


问:
Can I do an UpsertRequest that checks if the name of the entity exists?
In C#, I'm writing a program that transfers data from an old Microsoft Dynamics CRM system to a new one.

For most of the entities, I can use the UpsertRequest. Though, for contacts and accounts, there are already records in the new environment. As I don't want to have doubles, I would like to have the UpsertRequest check on the "Name" field in case of accounts and on "Fullname" in case of contacts.

Would that be possible? I (searched a lot and) cannot find examples on this. If not, what would be the best way to proceed?

Thanks for any feedback.

答:
for such case I would make a plugin on message create of contact and account such like this one :

```<code>public void Execute(IServiceProvider serviceProvider)
    {
        ITracingService tracingService =
           (ITracingService)serviceProvider.GetService(typeof(ITracingService));

        IPluginExecutionContext context = (IPluginExecutionContext)
            serviceProvider.GetService(typeof(IPluginExecutionContext));

        IOrganizationServiceFactory serviceFactory =
            (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService organizationService = serviceFactory.CreateOrganizationService(context.UserId);

        Entity TargetEntity = new Entity();

        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            TargetEntity = (Entity)context.InputParameters["Target"];

            QueryExpression queryDuplicateDetect = new QueryExpression(TargetEntity.LogicalName);

            if (TargetEntity.LogicalName == "account" && TargetEntity.Attributes.Contains("name"))
            {
                queryDuplicateDetect.ColumnSet = new ColumnSet(new string[] { "name" });
                queryDuplicateDetect.Criteria.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, TargetEntity["name"].ToString()));
            }
            else if (TargetEntity.LogicalName == "contact" && TargetEntity.Attributes.Contains("fullname"))
            {
                queryDuplicateDetect.ColumnSet = new ColumnSet(new string[] { "fullname" });
                queryDuplicateDetect.Criteria.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, TargetEntity["fullname"].ToString()));
            }

            try
            {
                EntityCollection resultsColl = organizationService.RetrieveMultiple(queryDuplicateDetect);
                if (resultsColl.Entities.Count > 0)
                {
                    foreach (Entity e in resultsColl.Entities)
                    {
                        tracingService.Trace("Record Found with ID {0}", e.Id);
                    }

                    //log results in some entity for more info
                    throw new InvalidPluginExecutionException("Duplicate detected.");

                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
    }
</code>```

and on the create side i'll use simple try catch to skip existing records

```<code> Entity x = new Entity("account");
            x["name"] = "mohamed0";

            Entity y = new Entity("contact");
            y["fullname"] = "mohamed";

            Entity z = new Entity("contact");
            z["fullname"] = "mohamed";

            try
            {

                var r = _orgService.Create(x);
                r = _orgService.Create(y);
                r = _orgService.Create(z);
            }
            catch (Exception e)
            {

                throw;
            }
</code>```

hope this will help.

Body:
for such case I would make a plugin on message create of contact and account such like this one :

public void Execute(IServiceProvider serviceProvider)
    {
        ITracingService tracingService =
           (ITracingService)serviceProvider.GetService(typeof(ITracingService));

        IPluginExecutionContext context = (IPluginExecutionContext)
            serviceProvider.GetService(typeof(IPluginExecutionContext));

        IOrganizationServiceFactory serviceFactory =
            (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
        IOrganizationService organizationService = serviceFactory.CreateOrganizationService(context.UserId);

        Entity TargetEntity = new Entity();

        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            TargetEntity = (Entity)context.InputParameters["Target"];

            QueryExpression queryDuplicateDetect = new QueryExpression(TargetEntity.LogicalName);

            if (TargetEntity.LogicalName == "account" && TargetEntity.Attributes.Contains("name"))
            {
                queryDuplicateDetect.ColumnSet = new ColumnSet(new string[] { "name" });
                queryDuplicateDetect.Criteria.AddCondition(new ConditionExpression("name", ConditionOperator.Equal, TargetEntity["name"].ToString()));
            }
            else if (TargetEntity.LogicalName == "contact" && TargetEntity.Attributes.Contains("fullname"))
            {
                queryDuplicateDetect.ColumnSet = new ColumnSet(new string[] { "fullname" });
                queryDuplicateDetect.Criteria.AddCondition(new ConditionExpression("fullname", ConditionOperator.Equal, TargetEntity["fullname"].ToString()));
            }

            try
            {
                EntityCollection resultsColl = organizationService.RetrieveMultiple(queryDuplicateDetect);
                if (resultsColl.Entities.Count > 0)
                {
                    foreach (Entity e in resultsColl.Entities)
                    {
                        tracingService.Trace("Record Found with ID {0}", e.Id);
                    }

                    //log results in some entity for more info
                    throw new InvalidPluginExecutionException("Duplicate detected.");

                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
    }

and on the create side i'll use simple try catch to skip existing records

 Entity x = new Entity("account");
            x["name"] = "mohamed0";

            Entity y = new Entity("contact");
            y["fullname"] = "mohamed";

            Entity z = new Entity("contact");
            z["fullname"] = "mohamed";

            try
            {

                var r = _orgService.Create(x);
                r = _orgService.Create(y);
                r = _orgService.Create(z);
            }
            catch (Exception e)
            {

                throw;
            }

hope this will help.


问:
How can I access a protected property of a Model located in a package (vendor folders)
The model is in the vendor folder (normal package). I need to access an attribute of the model which is protected.
NOTE: Not possible of making a getter in the model class.</p>

答:
The only way to get a protected variable is by a get-method in the class or by extending the class itself.

If you are not able to modify the class in question, then you have to extend the class with your own and create a getter function.


问:
Why undefined elements inside ngOnInit method in Angular
I am initializing a library in my ngOnInit method as follows:

```<code>ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});
......
}
</code>```

then i am calling this method from that instance, inside ngOnInit as well:

```<code> // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );
</code>```

so it the method finally looks like this:

```<code>ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );

}
</code>```

But I dont understand why the result printed by console.log is undefined if actually is this.$grid who is calling console.log.

I need to use that instance again inside that method to do something like this:

```<code>// bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  this.$grid.masonry('layout');
} );
</code>```

but I can not because this.$grid is undefined inside that method which does no makes sense for me at all.

Any ideas?

答:
This is because of the way you are binding your event.

In your code this refers to the execution context of the anonymous function you've passed to the on function (e.g. itself).

If you want to preserve the context of this, you have to use an arrow function like this:

```<code>this.$grid.on( 'layoutComplete', () => {
    this.$grid.masonry('layout');
});
</code>```

Body:
I am initializing a library in my ngOnInit method as follows:

ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});
......
}

then i am calling this method from that instance, inside ngOnInit as well:

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );

so it the method finally looks like this:

ngOnInit() {
this.$grid = jQuery('.grid').masonry({
  // options
  itemSelector: '.grid-item',//,
  columnWidth: 384,
  gutter: 24
});

 // bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  console.log(this.$grid);
} );

}

But I dont understand why the result printed by console.log is undefined if actually is this.$grid who is calling console.log.

I need to use that instance again inside that method to do something like this:

// bind event listener
this.$grid.on( 'layoutComplete',function onLayout() {
  this.$grid.masonry('layout');
} );

but I can not because this.$grid is undefined inside that method which does no makes sense for me at all.

Any ideas?

Body:
This is because of the way you are binding your event.

In your code this refers to the execution context of the anonymous function you've passed to the on function (e.g. itself).

If you want to preserve the context of this, you have to use an arrow function like this:

this.$grid.on( 'layoutComplete', () => {
    this.$grid.masonry('layout');
});


问:
Android Studio: Failed to load dx.jar
When I run my module in Android Studio I get this error:

Error:Android Dex: [GradleDevBuild] Failed to load dx.jar

I have searched endlessly for a solution online but everything is related to eclipse, there is nothing when it comes to Android Studio.

The path to the dex.jar is C:\AndroidSdk\build-tools\26.0.0\lib\dex.jar
So it does exists, I've moved it out of the folder and was notified that it moved so AS is aware of where it is. I have tried copying it into the root directory and into the platform-tools folder however that did nothing.

This is the full list of errors that all seem to be stemming from this dx.jar error.

```<code>Error:Android Dex: [GradleDevBuild] Failed to load dx.jar
Error:Android Dex: [GradleDevBuild] java.lang.ClassNotFoundException: com.android.dx.command.DxConsole
Error:Android Dex: [GradleDevBuild] at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.loadDex(AndroidDxRunner.java:80)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:136)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:336)
Error:Android Dex: [GradleDevBuild] Exception in thread "main" java.lang.NullPointerException
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:139)
</code>```

答: In my case I copied the dx.jar file from pathToYourSDK/build-tools/25.0.1/lib to pathToYourSDK/build-tools/25.0.1/ and it worked.</p>

Title: Android Studio: Failed to load dx.jar

Body:
When I run my module in Android Studio I get this error:

Error:Android Dex: [GradleDevBuild] Failed to load dx.jar

I have searched endlessly for a solution online but everything is related to eclipse, there is nothing when it comes to Android Studio.

The path to the dex.jar is C:\AndroidSdk\build-tools\26.0.0\lib\dex.jar
So it does exists, I've moved it out of the folder and was notified that it moved so AS is aware of where it is. I have tried copying it into the root directory and into the platform-tools folder however that did nothing.

This is the full list of errors that all seem to be stemming from this dx.jar error.

Error:Android Dex: [GradleDevBuild] Failed to load dx.jar
Error:Android Dex: [GradleDevBuild] java.lang.ClassNotFoundException: com.android.dx.command.DxConsole
Error:Android Dex: [GradleDevBuild] at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
Error:Android Dex: [GradleDevBuild] at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.loadDex(AndroidDxRunner.java:80)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:136)
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.main(AndroidDxRunner.java:336)
Error:Android Dex: [GradleDevBuild] Exception in thread "main" java.lang.NullPointerException
Error:Android Dex: [GradleDevBuild] at org.jetbrains.android.compiler.tools.AndroidDxRunner.runDex(AndroidDxRunner.java:139)


问:
Testing async calls with Jest, redux-mock-store and Moxios
I create a simple case to test my actions, but my store.dispatch is not returning a promise. Can someone tell me what is wrong?

Action.js code:

```<code>export const handleSubmit = inputData =>
(dispatch) => {
axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });
</code>```

};

And my test:

```<code>import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import * as actions from './../../../../src/modules/inputData/action';
import { API_URL } from './../../../../src/constants';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('InputData actions', () => {
 test('Test input value update', () => {
 moxios.install();
 moxios.stubRequest(`${API_URL}/process-input/`, { status: 200, response: 'A nice test result' });
 const store = mockStore();

 return store.dispatch(actions.handleSubmit('anyData'))
  .then(() => {
    expect(store.getActions()).toEqual([
      { type: 'UPDATE_OUTPUTT', payload: 'A nice test result' },
    ]);
  });
</code>```

});
});

The error that is returning is: Cannot read property 'then' of undefined

答:
Your redux action is not returning a promise. You should return the axios.post function.</p>

```<code>export const handleSubmit = inputData =>
(dispatch) => {
return axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });
};
</code>```

Body:
I create a simple case to test my actions, but my store.dispatch is not returning a promise. Can someone tell me what is wrong?

Action.js code:

export const handleSubmit = inputData =>
(dispatch) => {
axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });

};

And my test:

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import * as actions from './../../../../src/modules/inputData/action';
import { API_URL } from './../../../../src/constants';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('InputData actions', () => {
 test('Test input value update', () => {
 moxios.install();
 moxios.stubRequest(`${API_URL}/process-input/`, { status: 200, response: 'A nice test result' });
 const store = mockStore();

 return store.dispatch(actions.handleSubmit('anyData'))
  .then(() => {
    expect(store.getActions()).toEqual([
      { type: 'UPDATE_OUTPUTT', payload: 'A nice test result' },
    ]);
  });

});
});

The error that is returning is: Cannot read property 'then' of undefined

Body:
Your redux action is not returning a promise. You should return the axios.post function.

export const handleSubmit = inputData =>
(dispatch) => {
return axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });
};


问:
Scraping a dynamic weather slideshow
I am making a weather page and I would need to screen scape the radar image on http://www.weather.bm/radarMobile.asp just the radar images. Fatherstorm has help me before and given me a php script it worked but with some bugs.

```<code>$localOffset = "+2 Hours"; //change this to your local offset from the image times you need. for me (CST) it's 2 hours.....
$start=  strtotime("-90 Minutes " . $localOffset); // go back 90 minutes (The limit of the available images)
$start=($start-($start % (600))+(60*6)); //go to the next earlier 6 minute mark (all images appear to be at the 6 minute mark))appear to be at the 6 minute mark))
for($x=1;$x<=9;$x++){
$DateTime = date("Y-m-d-Hi", $start); // set the image time we want.
$fName = ("http://www.weather.bm/images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-  $DateTime.jpg"); // set the filename
echo" $min <img src='$fName' alt='$fName'/><br/>"; // echo (or add to a stack or variable...) your image node
$start+=(600);//add 10 minutes     }
</code>```

Here are the problems:
most of the time some images and discription is not showing due to different time.
the script has 10 images but some times the site only displays 9 or 8.

I need a script that could scrape the images put it in a div ul li so I can animate it like in the original site(I mean the slideshow effect) or make it's path absolute don't know how it would help but I sure want to know how to do that also. The weather sites images is in a javascript array which I am not familliar.

I need the whole script so I can study it before using it so I can learn in the process.

答:
I personally think its NOT OK to screen scrape. It may be OK to use API if they have one, but if they don't provide API Or XML feed for what you need, then you may be violating some copyrights by copying their images, even if it's a radar map.

Proceed at your own risk but remember that it's possible that they will find out and take legal actions.

Title: Scraping a dynamic weather slideshow

Body:
I am making a weather page and I would need to screen scape the radar image on http://www.weather.bm/radarMobile.asp just the radar images. Fatherstorm has help me before and given me a php script it worked but with some bugs.

$localOffset = "+2 Hours"; //change this to your local offset from the image times you need. for me (CST) it's 2 hours.....
$start=  strtotime("-90 Minutes " . $localOffset); // go back 90 minutes (The limit of the available images)
$start=($start-($start % (600))+(60*6)); //go to the next earlier 6 minute mark (all images appear to be at the 6 minute mark))appear to be at the 6 minute mark))
for($x=1;$x<=9;$x++){
$DateTime = date("Y-m-d-Hi", $start); // set the image time we want.
$fName = ("http://www.weather.bm/images/Radar/CurrentRadarAnimation_100km_sri/100km_sri-radar-  $DateTime.jpg"); // set the filename
echo" $min
"; // echo (or add to a stack or variable...) your image node
$start+=(600);//add 10 minutes     }

Here are the problems:
most of the time some images and discription is not showing due to different time.
the script has 10 images but some times the site only displays 9 or 8.

I need a script that could scrape the images put it in a div ul li so I can animate it like in the original site(I mean the slideshow effect) or make it's path absolute don't know how it would help but I sure want to know how to do that also. The weather sites images is in a javascript array which I am not familliar.

I need the whole script so I can study it before using it so I can learn in the process.


问:
Running ant as administrator...through Eclipse
I just inherited a project that uses Tomcat to serve JSPs, but Apache httpd to server Javascript...

The Ant build for this project creates and deletes directories inside the C:\Program Files\Apache Software Foundation\Apache2.2\ directory, which is an "admin" directory in Windows 7 land.

When I try to run this Ant build inside of Eclipse, the build fails because it is unable to create the necessary directories because its getting permission/access denied errors.

Is there any way to configure Ant (run arguments, etc.) to run as administrator from inside Eclipse? Thanks in advance.

答:
Even if this is an old question...I recently had a similar authorization problem with Win10 and Ant v.1.10.1 inside Eclipse Oxygen (4.7.1). I was trying to control a Windows Service (Tomcat) from an Ant-task but got:
    stopTomcat:
     [exec] System error 5 has occurred.
     [exec] Access is denied.
     [exec] Result: 2
    startTomcat:
     [echo] Start Tomcat
     [exec] System error 5 has occurred.
     [exec] Access is denied.
     [exec] Result: 2

Starting/running Eclipse as administrator made all the difference :-)


问:
How to replace the image running in Amazon ECS with a newer docker image automatically
I have a docker image running in Amazon ECS (Amazon EC2 Container Registry). The docker image path is defined in task definition.

Now after I make edits to my code, Jenkins automatically build the new image and pushes it to the Amazon repository registry and I get a new PATH based on the build number.

The new URL is like

```<code>1234.dkr.ecr.ap-southeast-1.amazonaws.com/csr:13
</code>```

The old URL is like

```<code>1234.dkr.ecr.ap-southeast-1.amazonaws.com/csr:12
</code>```

Now I want that Jenkins run some command in CLI to tell ECS that there is a new image that it should run on the EC2 instance instead of old.

I was reading AWS CLI documentation and I came across commands like aws ecs register-task-definition and aws ecs run-task but I am not sure.

I am clueless how devops do this? What is the proper way?
Please help.

A simple task definition looks like this:

```<code>{
    "networkMode": "bridge",
    "taskRoleArn": null,
    "containerDefinitions": [
        {
            "volumesFrom": [],
            "memory": 512,
            "extraHosts": [],
            "linuxParameters": {
                "capabilities": {
                    "add": null,
                    "drop": null
                },
                "devices": null,
                "initProcessEnabled": null
            },
            "dnsServers": [],
            "disableNetworking": null,
            "dnsSearchDomains": [],
            "portMappings": [
                {
                    "hostPort": 9000,
                    "containerPort": 9000,
                    "protocol": "tcp"
                },
                {
                    "hostPort": 3306,
                    "containerPort": 3306,
                    "protocol": "tcp"
                },
                {
                    "hostPort": 80,
                    "containerPort": 80,
                    "protocol": "tcp"
                },
                {
                    "hostPort": 443,
                    "containerPort": 443,
                    "protocol": "tcp"
                }
            ],
            "hostname": null,
            "essential": true,
            "entryPoint": [],
            "mountPoints": [],
            "name": "phpfpm-nginx",
            "ulimits": [],
            "dockerSecurityOptions": [],
            "environment": [
                {
                    "name": "ERRORS",
                    "value": "1"
                },
                {
                    "name": "WEBROOT",
                    "value": "/data/www/public_html/"
                }
            ],
            "links": [],
            "workingDirectory": null,
            "readonlyRootFilesystem": false,
            "image": "1234.dkr.ecr.ap-southeast-1.amazonaws.com/csr:13",
            "command": [],
            "user": null,
            "dockerLabels": {},
            "logConfiguration": null,
            "cpu": 0,
            "privileged": false,
            "memoryReservation": null
        }
    ],
    "volumes": [],
    "family": "ecscompose-CSR",
    "placementConstraints": []
}
</code>```

答:
To anyone who is wondering same question as I was few minutes ago,
I found an open source cli program called ecs-deploy

It pushes your new image to ECS easily.
I hope it helps someone in future.

Body:
I have a docker image running in Amazon ECS (Amazon EC2 Container Registry). The docker image path is defined in task definition.

Now after I make edits to my code, Jenkins automatically build the new image and pushes it to the Amazon repository registry and I get a new PATH based on the build number.

The new URL is like

1234.dkr.ecr.ap-southeast-1.amazonaws.com/csr:13

The old URL is like

1234.dkr.ecr.ap-southeast-1.amazonaws.com/csr:12

Now I want that Jenkins run some command in CLI to tell ECS that there is a new image that it should run on the EC2 instance instead of old.

I was reading AWS CLI documentation and I came across commands like aws ecs register-task-definition and aws ecs run-task but I am not sure.

I am clueless how devops do this? What is the proper way?
Please help.

A simple task definition looks like this:

{
    "networkMode": "bridge",
    "taskRoleArn": null,
    "containerDefinitions": [
        {
            "volumesFrom": [],
            "memory": 512,
            "extraHosts": [],
            "linuxParameters": {
                "capabilities": {
                    "add": null,
                    "drop": null
                },
                "devices": null,
                "initProcessEnabled": null
            },
            "dnsServers": [],
            "disableNetworking": null,
            "dnsSearchDomains": [],
            "portMappings": [
                {
                    "hostPort": 9000,
                    "containerPort": 9000,
                    "protocol": "tcp"
                },
                {
                    "hostPort": 3306,
                    "containerPort": 3306,
                    "protocol": "tcp"
                },
                {
                    "hostPort": 80,
                    "containerPort": 80,
                    "protocol": "tcp"
                },
                {
                    "hostPort": 443,
                    "containerPort": 443,
                    "protocol": "tcp"
                }
            ],
            "hostname": null,
            "essential": true,
            "entryPoint": [],
            "mountPoints": [],
            "name": "phpfpm-nginx",
            "ulimits": [],
            "dockerSecurityOptions": [],
            "environment": [
                {
                    "name": "ERRORS",
                    "value": "1"
                },
                {
                    "name": "WEBROOT",
                    "value": "/data/www/public_html/"
                }
            ],
            "links": [],
            "workingDirectory": null,
            "readonlyRootFilesystem": false,
            "image": "1234.dkr.ecr.ap-southeast-1.amazonaws.com/csr:13",
            "command": [],
            "user": null,
            "dockerLabels": {},
            "logConfiguration": null,
            "cpu": 0,
            "privileged": false,
            "memoryReservation": null
        }
    ],
    "volumes": [],
    "family": "ecscompose-CSR",
    "placementConstraints": []
}


问:
<g> element inside of a .svg doesn't scale up on :hover (css)
I'm new to coding and have some issues I'm unable to resolve and hope you can help me.
The thing is: I've exported a svg-file out of Visio drawing and now I'm trying to scale an element inside this svg.
I've used the transform: scale(2) !important command on hover inside the css but the element (#shape72-136 - which is the top left rectangle) is kind of vibrating instead of scaling up. Also it doesn't change to desired color.

Hope you can help me out.

```<code>.st1 {fill:none;stroke:none;stroke-linecap:round;stroke-linejoin:round;stroke-width:0.75}
    .st2 {fill:#00b050;font-family:Calibri;font-size:1.00001em}
    .st3 {fill:#ffffff;stroke:#00b050;stroke-linecap:round;stroke-linejoin:round;stroke-width:1}
    .st4 {fill:none;fill-rule:evenodd;font-size:12px;overflow:visible;stroke-linecap:square;stroke-miterlimit:3}

#shape72-136:hover {fill:blue !important; width: 400px; height: 100px; transform: scale(2) !important; animation-name: example; animation-duration: 4s; animation-iteration-count: infinite;}
@keyframes example {
0% {
filter: brightness(1);
filter: contrast(1);

}
50% {
filter: brightness(2);
filter: contrast(0.1);

}
100% {
filter: brightness(1);
filter: contrast(1);

 }
}
</code>```

You can fiddle the code:
https://jsfiddle.net/pickle/kcuntLLz/

答:
Here's one way, move the static transform onto the rect element and then specify transform-origin and transform-box to ensure that the scaling works from the rect centre.

.st1 {fill:none;stroke:none;stroke-linecap:round;stroke-linejoin:round;stroke-width:0.75}
  .st2 {fill:#00b050;font-family:Calibri;font-size:1.00001em}
  .st3 {fill:#ffffff;stroke:#00b050;stroke-linecap:round;stroke-linejoin:round;stroke-width:1}
  .st4 {fill:none;
    fill-rule:evenodd;
    font-size:12px;
    overflow:visible;
    stroke-linecap:square;
    stroke-miterlimit:3}

#shape73-138:hover {
  fill: blue !important;
  transform: scale(1.5);
  /*animation-name: example;*/
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

#shape73-138 {
  transform-origin: center center;
  transform-box: fill-box;
}

@keyframes example {
  0% {
    filter: brightness(1);
    filter: contrast(1);

  }
  50% {
    filter: brightness(2);
    filter: contrast(0.1);

  }
  100% {
    filter: brightness(1);
    filter: contrast(1);

  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" width="9.90261in" height="2.57908in" viewBox="0 0 712.988 185.694" xml:space="preserve" color-interpolation-filters="sRGB" class="st4">

    <g>
        <g id="shape73-138">
            <title>Rechteck.69</title>
            <rect transform="translate(48.5326,-103.539)" x="0" y="143.174" width="20.1861" height="42.5197" class="st3"/>
        </g>
    </g>
</svg></code>```

Body:
I'm new to coding and have some issues I'm unable to resolve and hope you can help me.
The thing is: I've exported a svg-file out of Visio drawing and now I'm trying to scale an element inside this svg.
I've used the transform: scale(2) !important command on hover inside the css but the element (#shape72-136 - which is the top left rectangle) is kind of vibrating instead of scaling up. Also it doesn't change to desired color.

Hope you can help me out.

.st1 {fill:none;stroke:none;stroke-linecap:round;stroke-linejoin:round;stroke-width:0.75}
    .st2 {fill:#00b050;font-family:Calibri;font-size:1.00001em}
    .st3 {fill:#ffffff;stroke:#00b050;stroke-linecap:round;stroke-linejoin:round;stroke-width:1}
    .st4 {fill:none;fill-rule:evenodd;font-size:12px;overflow:visible;stroke-linecap:square;stroke-miterlimit:3}

#shape72-136:hover {fill:blue !important; width: 400px; height: 100px; transform: scale(2) !important; animation-name: example; animation-duration: 4s; animation-iteration-count: infinite;}
@keyframes example {
0% {
filter: brightness(1);
filter: contrast(1);

}
50% {
filter: brightness(2);
filter: contrast(0.1);

}
100% {
filter: brightness(1);
filter: contrast(1);

 }
}

You can fiddle the code:
https://jsfiddle.net/pickle/kcuntLLz/

Body:
Here's one way, move the static transform onto the rect element and then specify transform-origin and transform-box to ensure that the scaling works from the rect centre.

.st1 {fill:none;stroke:none;stroke-linecap:round;stroke-linejoin:round;stroke-width:0.75}
  .st2 {fill:#00b050;font-family:Calibri;font-size:1.00001em}
  .st3 {fill:#ffffff;stroke:#00b050;stroke-linecap:round;stroke-linejoin:round;stroke-width:1}
  .st4 {fill:none;
    fill-rule:evenodd;
    font-size:12px;
    overflow:visible;
    stroke-linecap:square;
    stroke-miterlimit:3}

#shape73-138:hover {
  fill: blue !important;
  transform: scale(1.5);
  /*animation-name: example;*/
  animation-duration: 4s;
  animation-iteration-count: infinite;
}

#shape73-138 {
  transform-origin: center center;
  transform-box: fill-box;
}

@keyframes example {
  0% {
    filter: brightness(1);
    filter: contrast(1);

  }
  50% {
    filter: brightness(2);
    filter: contrast(0.1);

  }
  100% {
    filter: brightness(1);
    filter: contrast(1);

  }
}

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:ev="http://www.w3.org/2001/xml-events" width="9.90261in" height="2.57908in" viewBox="0 0 712.988 185.694" xml:space="preserve" color-interpolation-filters="sRGB" class="st4">

    <g>
        <g id="shape73-138">
            <title>Rechteck.69</title>
            <rect transform="translate(48.5326,-103.539)" x="0" y="143.174" width="20.1861" height="42.5197" class="st3"/>
        </g>
    </g>
</svg>


问:
How to get the id of the value when using auto complete AJAX in Laravel?
Can I get only id of the value in autocomplete search in Laravel? The current situation is like I am getting the value of employer name, but I want to get the id of employer name, so I can save it to another table in the database without saving of the employer name.

Here is my controller code:

```<code>public function index2(){
    return view('autocomplete.index');
}

public function autoComplete2(Request $request) {
    $query = $request->get('term','');

    $products=Employer::where('employer_name','LIKE','%'.$query.'%')->get();

    $data=array();
    foreach ($products as $product) {
         $data[]=array('value'=>$product->employer_name,'id'=>$product->id);
    }
    if(count($data))
        return $data;
    else
        return ['value'=>'No Result Found','id'=>''];
}
</code>```

Here is my view:

```<code>{!! Form::open(['route' => 'calllogs.store', 'method' => 'post']) !!}

  <div class="form-group">
    {!! Form::label('Company Recommend ') !!}
    <input class="typeahead form-control" value="" type="text" name="searchajax" id="search_text">
  </div>

  {!! Form::submit(__('Create'), ['class' => 'btn btn-primary pull-right']) !!}
{!! Form::close() !!}

<script>
$(document).ready(function() {
    src = "{{ route('searchajax') }}";
    $("#search_text").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: src,
                dataType: "json",
                data: {
                    term : request.term
                },
                success: function(data) {
                    response(data);

                }
            });
        },
        minLength: 1,

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

Any helps would be appreciated.

答:
This is not related to laravel but for Jquery UI.jqueryUI autocomplete has a option call 'select' and it trigger after clicked on a autocomplete list item.</p>

```<code>$(document).ready(function() {
    src = "{{ route('searchajax') }}";
    $("#search_text").autocomplete({
        select: function (event, ui) {//trigger when you click on the autocomplete item
            event.preventDefault();//you can prevent the default event
            alert( ui.item.id);//employee id
            alert( ui.item.value);//employee name

        },
        source: function(request, response) {
            $.ajax({
                url: src,
                dataType: "json",
                data: {
                    term : request.term
                },
                success: function(data) {
                    response(data);

                }
            });
        },
        minLength: 1,

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

Body:
Can I get only id of the value in autocomplete search in Laravel? The current situation is like I am getting the value of employer name, but I want to get the id of employer name, so I can save it to another table in the database without saving of the employer name.

Here is my controller code:

public function index2(){
    return view('autocomplete.index');
}

public function autoComplete2(Request $request) {
    $query = $request->get('term','');

    $products=Employer::where('employer_name','LIKE','%'.$query.'%')->get();

    $data=array();
    foreach ($products as $product) {
         $data[]=array('value'=>$product->employer_name,'id'=>$product->id);
    }
    if(count($data))
        return $data;
    else
        return ['value'=>'No Result Found','id'=>''];
}

Here is my view:

{!! Form::open(['route' => 'calllogs.store', 'method' => 'post']) !!}

    {!! Form::label('Company Recommend ') !!}
    <input class="typeahead form-control" value="" type="text" name="searchajax" id="search_text">

  {!! Form::submit(__('Create'), ['class' => 'btn btn-primary pull-right']) !!}
{!! Form::close() !!}

Any helps would be appreciated.

Body:
This is not related to laravel but for Jquery UI.jqueryUI autocomplete has a option call 'select' and it trigger after clicked on a autocomplete list item.

$(document).ready(function() {
    src = "{{ route('searchajax') }}";
    $("#search_text").autocomplete({
        select: function (event, ui) {//trigger when you click on the autocomplete item
            event.preventDefault();//you can prevent the default event
            alert( ui.item.id);//employee id
            alert( ui.item.value);//employee name

        },
        source: function(request, response) {
            $.ajax({
                url: src,
                dataType: "json",
                data: {
                    term : request.term
                },
                success: function(data) {
                    response(data);

                }
            });
        },
        minLength: 1,

    });
});


问:
MS Access append query with a parameter fails with type conversion failure - text to text
I am running an append query that selects records from an existing table in the database.  All the fields in the receiving table are defined as text.  Since this table will receive new records on a regular basis, I want to add a file date in text form to the record when it's written so I can identify when each record was added.  I don't need the file date to be an actual date, and it will not be the date I'm actually running the query. The field is defined as text, and the query prompts for the date.

Query from comment:

INSERT INTO tblMaster_Vendor ( Vendor_ID, FileDate )
SELECT DISTINCT FULL_EXTRACT.Vendor_ID, [File Date] AS Expr1
FROM FULL_EXTRACT
WHERE FULL_EXTRACT.Vendor_Type = "84"
```

Every time, I get a 'data type conversion error', even though I'm adding text (like 20171106) to a text field.

Here's what I've tried:
- changed the field name and prompt from 'File Date' to 'Entered' in case there was a reserved word issue
- Entered straight text into the parameter query box (aaaabbcc)
- Changed the table field type to date/time and entered the date as 11/10/2017
- Entered the text in the parameter box with quotes ('aaaabbcc')

If I don't try to enter the file date as part of the append query, I can run an update query after the append and update the field to my desired value (20171106).

Has anyone seen this behavior before?

答:
Have you tried using the Cstr function? e.g., something of this structure?</p>

```<code>INSERT INTO Table2 ( ID, fileupdated ) SELECT Table1.ID, CStr(Now()) AS Expr1 FROM Table1 WHERE (((Table1.ID)>2));
</code>```

Body:
I am running an append query that selects records from an existing table in the database.  All the fields in the receiving table are defined as text.  Since this table will receive new records on a regular basis, I want to add a file date in text form to the record when it's written so I can identify when each record was added.  I don't need the file date to be an actual date, and it will not be the date I'm actually running the query. The field is defined as text, and the query prompts for the date.

Query from comment:

INSERT INTO tblMaster_Vendor ( Vendor_ID, FileDate )
SELECT DISTINCT FULL_EXTRACT.Vendor_ID, [File Date] AS Expr1
FROM FULL_EXTRACT
WHERE FULL_EXTRACT.Vendor_Type = "84"

Every time, I get a 'data type conversion error', even though I'm adding text (like 20171106) to a text field.

Here's what I've tried:
- changed the field name and prompt from 'File Date' to 'Entered' in case there was a reserved word issue
- Entered straight text into the parameter query box (aaaabbcc)
- Changed the table field type to date/time and entered the date as 11/10/2017
- Entered the text in the parameter box with quotes ('aaaabbcc')

If I don't try to enter the file date as part of the append query, I can run an update query after the append and update the field to my desired value (20171106).

Has anyone seen this behavior before?

Body:
Have you tried using the Cstr function? e.g., something of this structure?

INSERT INTO Table2 ( ID, fileupdated ) SELECT Table1.ID, CStr(Now()) AS Expr1 FROM Table1 WHERE (((Table1.ID)>2));


问:
Python MySQLdb: Inserting duplicate entry into a table with UNIQUE fields
I have a MySQL database that contains a table named commands with the following structure:

```<code>+-----------+---------------+------+-----+---------+----------------+
| Field     | Type          | Null | Key | Default | Extra          |
+-----------+---------------+------+-----+---------+----------------+
| id        | int(11)       | NO   | PRI | NULL    | auto_increment |
| input     | varchar(3000) | NO   |     | NULL    |                |
| inputhash | varchar(66)   | YES  | UNI | NULL    |                |
+-----------+---------------+------+-----+---------+----------------+
</code>```

I am trying to insert rows in it, but only if the inputhash field does not already exist. I thought INSERT IGNORE was the way to do this, but I am still getting warnings.

For instance, suppose that the able already contains

```<code>+----+---------+------------------------------------------------------------------+
| id | input   | inputhash                                                        |
+----+---------+------------------------------------------------------------------+
|  1 | enable  | 234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9 |
+----+---------+------------------------------------------------------------------+
</code>```

Then when using the following Python code to insert a row

```<code>import MySQLdb

db = MySQLdb.connect(host='xxx.xxx.xxx.xxx', user='xxxx', passwd='xxxx', db='dbase')
c = db.cursor()
c.execute('INSERT IGNORE INTO `commands` (`input`, `inputhash`) VALUES (%s, %s)', ('enable', '234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9',))
</code>```

I am getting the warning

```<code>Warning: Duplicate entry '234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9' for key 'inputhash'
  c.execute('INSERT IGNORE INTO `commands` (`input`, `inputhash`) VALUES (%s, %s)', ('enable','234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9',))
</code>```

Why does this happen? I thought that the whole point of using INSERT IGNORE on a table with UNIQUE fields is to suppress the error and simply ignore the write attempt?

What is the proper way to resolve this? I suppose I can suppress the warning in Python with warnings.filterwarnings('ignore') but why does the warning appear in the first place?

答:
I hope it will help you !

```<code>import MySQLdb

db = MySQLdb.connect(host='xxx.xxx.xxx.xxx', user='xxxx', passwd='xxxx',
db='dbase')
c = db.cursor()
c.execute('INSERT INTO `commands` (`input`, `inputhash`) VALUES ('enable',
'234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9') ON
DUPLICATE KEY UPDATE 'inputhash'='inputhash')
</code>```

Body:
I have a MySQL database that contains a table named commands with the following structure:

+-----------+---------------+------+-----+---------+----------------+
| Field     | Type          | Null | Key | Default | Extra          |
+-----------+---------------+------+-----+---------+----------------+
| id        | int(11)       | NO   | PRI | NULL    | auto_increment |
| input     | varchar(3000) | NO   |     | NULL    |                |
| inputhash | varchar(66)   | YES  | UNI | NULL    |                |
+-----------+---------------+------+-----+---------+----------------+

I am trying to insert rows in it, but only if the inputhash field does not already exist. I thought INSERT IGNORE was the way to do this, but I am still getting warnings.

For instance, suppose that the able already contains

+----+---------+------------------------------------------------------------------+
| id | input   | inputhash                                                        |
+----+---------+------------------------------------------------------------------+
|  1 | enable  | 234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9 |
+----+---------+------------------------------------------------------------------+

Then when using the following Python code to insert a row

import MySQLdb

db = MySQLdb.connect(host='xxx.xxx.xxx.xxx', user='xxxx', passwd='xxxx', db='dbase')
c = db.cursor()
c.execute('INSERT IGNORE INTO `commands` (`input`, `inputhash`) VALUES (%s, %s)', ('enable', '234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9',))

I am getting the warning

Warning: Duplicate entry '234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9' for key 'inputhash'
  c.execute('INSERT IGNORE INTO `commands` (`input`, `inputhash`) VALUES (%s, %s)', ('enable','234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9',))

Why does this happen? I thought that the whole point of using INSERT IGNORE on a table with UNIQUE fields is to suppress the error and simply ignore the write attempt?

What is the proper way to resolve this? I suppose I can suppress the warning in Python with warnings.filterwarnings('ignore') but why does the warning appear in the first place?

Body:
I hope it will help you !

import MySQLdb

db = MySQLdb.connect(host='xxx.xxx.xxx.xxx', user='xxxx', passwd='xxxx',
db='dbase')
c = db.cursor()
c.execute('INSERT INTO `commands` (`input`, `inputhash`) VALUES ('enable',
'234a86bf393cadeba1bcbc09a244a398ac10c23a51e7fd72d7c449ef0edaa9e9') ON
DUPLICATE KEY UPDATE 'inputhash'='inputhash')


问:
Get some random and some specific records in a single query?
So I have a cover-flow style image carousel populated by a query like

```<code>SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;
</code>```

My client would like to add to this a set of permanent images.  Due to the way the results are used it would be very handy if I could make those records part of my original query.

I tried

```<code>SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y'
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;
</code>```

I was hoping the records with the ids would necessarily be in the result set but nope the RAND() shuffles the whole set.

So my question is whether any single query could provide the x permanent records and then y random records?

// EDIT WITH REVISED QUERY USING Adrian Serafin's answer:

```<code>(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')
</code>```

答:
You can try union command in sql.</p>

```<code>select random
  union
select choosed
</code>```

Body:
So I have a cover-flow style image carousel populated by a query like

SELECT foo FROM `imageTable` ORDER BY RAND() LIMIT 0, 12;

My client would like to add to this a set of permanent images.  Due to the way the results are used it would be very handy if I could make those records part of my original query.

I tried

SELECT foo FROM `imageTable` WHERE `id` = 'x' OR `id` = 'y'
  OR `id` IS NOT NULL ORDER BY RAND() LIMIT 0, 12;

I was hoping the records with the ids would necessarily be in the result set but nope the RAND() shuffles the whole set.

So my question is whether any single query could provide the x permanent records and then y random records?

// EDIT WITH REVISED QUERY USING Adrian Serafin's answer:

(SELECT * FROM `imageTable` ORDER BY RAND() LIMIT 0, 6)
UNION
(SELECT * FROM `imageTable`  WHERE `id` = 'foo' OR `id` = 'bar' OR `id` = 'baz')

Body:
You can try union command in sql.

select random
  union
select choosed


问:
Unable to render automatic slideshow with react
I'm trying to create an automatic slideshow in react, using react-slideshow. I'm very new to react and have just begun. I got this code from here.

```<code>import React from 'react';
import { Fade } from 'react-slideshow-image';
const images = [
  './img/p1.png',
  './img/p1.png',
  './img/p1.png'
];

const Slideshow = () => {
return (
    <Fade
      images={images}
      duration="5000"
      transitionDuration="1000"/>
   )
}
</code>```

What I am not getting is how to make this slideshow actually render. What I have done is called this function from inside a component in the same file i.e.

```<code>class App extends Component {
  render() {
    return (
      <div className="App">
      {Slideshow();}
    </div>
    );
  }
}
export default App;
</code>```

This is not rendering any slideshow or image, about which I'm not too surprised. The function is running. I console logged something and it got logged on the console. The rest of the page (I have other divs not shown here) is rendered and there is no error thrown. How to make this work?

答:
Nothing seems wrong in this code.

try defining Slideshow() function inside app component.

make a call like  "{ this.Slideshow }".

Check by removing "./" in image path. (Try..)

Also check the path of image. Sometime they refer to public folder outside the src folder. maybe public/images/img.png

Body:
I'm trying to create an automatic slideshow in react, using react-slideshow. I'm very new to react and have just begun. I got this code from here.

import React from 'react';
import { Fade } from 'react-slideshow-image';
const images = [
  './img/p1.png',
  './img/p1.png',
  './img/p1.png'
];

const Slideshow = () => {
return (
    <Fade
      images={images}
      duration="5000"
      transitionDuration="1000"/>
   )
}

What I am not getting is how to make this slideshow actually render. What I have done is called this function from inside a component in the same file i.e.

class App extends Component {
  render() {
    return (

      {Slideshow();}

    );
  }
}
export default App;

This is not rendering any slideshow or image, about which I'm not too surprised. The function is running. I console logged something and it got logged on the console. The rest of the page (I have other divs not shown here) is rendered and there is no error thrown. How to make this work?


问:
Group multiple columns using the CASE Condition function
I am grouping a rows in mysql using two columns userfrom and userto.  I have to select only one message of conversation between a and b. The below query does exactly what I want, but I wanted to deploy this into android sqlite query, however the sqlite takes only the CASE Condition function.

```<code> SELECT * FROM messeages WHERE userfrom='a' OR userto='a'
 group by
     IF(userfrom > userto, userfrom,userto),
     IF(userfrom > userto, userto,userfrom)
</code>```

Can someone help on translating this using the CASE Condition function.

答:
The documentation documents how this works:

```<code>GROUP BY CASE WHEN userfrom > userto THEN userfrom ELSE userto END,
         CASE WHEN userfrom > userto THEN userto ELSE userfrom END;
</code>```

However, in this case, you can simply use the non-aggregated form of min()/max():

```<code>GROUP BY max(userfrom, userto),
         min(userfrom, userto);
</code>```

Body:
I am grouping a rows in mysql using two columns userfrom and userto.  I have to select only one message of conversation between a and b. The below query does exactly what I want, but I wanted to deploy this into android sqlite query, however the sqlite takes only the CASE Condition function.

 SELECT * FROM messeages WHERE userfrom='a' OR userto='a'
 group by
     IF(userfrom > userto, userfrom,userto),
     IF(userfrom > userto, userto,userfrom)

Can someone help on translating this using the CASE Condition function.

Body:
The documentation documents how this works:

GROUP BY CASE WHEN userfrom > userto THEN userfrom ELSE userto END,
         CASE WHEN userfrom > userto THEN userto ELSE userfrom END;

However, in this case, you can simply use the non-aggregated form of min()/max():

GROUP BY max(userfrom, userto),
         min(userfrom, userto);


问:
Can I do everything with react.js just using CDN libraries, without any installations at all ?
Can I do everything with react.js just using CDN libraries, without any installations at all ? </p>

<p>For example can I always use JavaScript libraries like this? </p>

```<code><script src="https://cdn/X.js"></script>

const X = window.X;
</code>```

答: No,not a good idea.Your application performance drops.You will not able to use npm module features,if you don't install NPM. Make use of create-react-app or react-boilerplate which ships some great features and easy to setup.</p>

Body:
Can I do everything with react.js just using CDN libraries, without any installations at all ?

For example can I always use JavaScript libraries like this?

const X = window.X;


问:
Async not working as I expected
I've read all I can find on async programming in asp.net (c#). I've made sense of most of how it's supposed to work and when it should be used. Yet I find basic examples not working as I expect. Without Task.Run it doesn't seem to actually run asynchronously.

Can someone tell me what I'm missing in this example?

Say the code is like so

```<code>public async Task SubTask2()
{
    LongRunningOperation2();
    Response.Write("<br>------------------------ Finished -------------------------<br>");
}

private async Task<Boolean> LongRunningOperation1()
{
    int counter;

    for (counter = 0; counter < 50000; counter++)
    {
        Response.Write(counter + "<br>");
    }
    return await Task.FromResult<bool>(true);
}

private async Task<Boolean> LongRunningOperation2()
{
    await LongRunningOperation1();
    Response.Write("<br>------------------------ Long Task -------------------------<br>");
    return true;
}
</code>```

Shouldn't LongRunningOperation2() return to SubTask2() and print "finished" before or while writing out numbers? Instead it prints finished at the end. Using Task.Run works as expected but then I don't see the point of ever not using Task.Run

答:
First, you're missing await in SubTask2(), so it actually runs synchronously (waits for LongRunningOperation2() to finish).
Secondly, even with asynchronous execution, "finished" wouldn't be printed before LongRunningOperation2() finished it's work. The point of using it is to free the thread, so it can do some other work in the meantime (e.g. handle another request).

Title: Async not working as I expected

Body:
I've read all I can find on async programming in asp.net (c#). I've made sense of most of how it's supposed to work and when it should be used. Yet I find basic examples not working as I expect. Without Task.Run it doesn't seem to actually run asynchronously.

Can someone tell me what I'm missing in this example?

Say the code is like so

public async Task SubTask2()
{
    LongRunningOperation2();
    Response.Write("
------------------------ Finished -------------------------
");
}

private async Task<Boolean> LongRunningOperation1()
{
    int counter;

    for (counter = 0; counter < 50000; counter++)
    {
        Response.Write(counter + "
");
    }
    return await Task.FromResult<bool>(true);
}

private async Task<Boolean> LongRunningOperation2()
{
    await LongRunningOperation1();
    Response.Write("
------------------------ Long Task -------------------------
");
    return true;
}

Shouldn't LongRunningOperation2() return to SubTask2() and print "finished" before or while writing out numbers? Instead it prints finished at the end. Using Task.Run works as expected but then I don't see the point of ever not using Task.Run


问:
Changing fopen() mode midway through?
I this piece of code:

```<code>$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);
</code>```

Basically what I want to do is: open a file > lock it > read it > do some stuff > clear the file > write to file > unlock it > close it.

The problem is the clearing part. I know I could do it with fopen($file, 'w+') but then reading would be a problem. Maybe I can change the mode somehow?

Any help would be appreciated, Paul

答:
```<code>fopen($file, 'r+')
</code>```

Includes reading and writing.  Go forth and prosper.

r+ description:
Open for reading and writing; place the file pointer at the beginning of the file.

w+ description:
Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Source: http://php.net/manual/en/function.fopen.php

Title: Changing fopen() mode midway through?

Body:
I this piece of code:

$file = fopen($path, 'r+');
flock($file, LOCK_EX);
// reading the file into an array and doing some stuff to it
for ($i=0; $i<count($array); $i++)
  {
  fwrite($file, $array[$i]);
  }
flock($file, LOCK_UN);
fclose($file);

Basically what I want to do is: open a file > lock it > read it > do some stuff > clear the file > write to file > unlock it > close it.

The problem is the clearing part. I know I could do it with fopen($file, 'w+') but then reading would be a problem. Maybe I can change the mode somehow?

Any help would be appreciated, Paul

Body:
fopen($file, 'r+')

Includes reading and writing.  Go forth and prosper.

r+ description:
Open for reading and writing; place the file pointer at the beginning of the file.

w+ description:
Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

Source: http://php.net/manual/en/function.fopen.php