问:
how to solve pgcc&openacc linker error "__pgi_uacc_multicorestart", "__pgi_uacc_multicoreend"
I am trying to parallelize my program in C with OpenACC 2.5 on Ubuntu 16.04 LTS. After a simple modification which is just adding one line, I can compile all my .c files to .o files. In the linking step, pgcc compiler shows

undefined reference to `__pgi_uacc_multicorestart'

and

undefined reference to `__pgi_uacc_multicoreend'

. Google search shows nothing related to these error message. Please help me on this problem.

Here is the information and source code related to my system and program. I try to post the essential part and please let me know if you need anything else.

OS, software:

```<code>LSB Version:    core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:printing-9.20160110ubuntu0.2-amd64:printing-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3 LTS
Release:    16.04
Codename:   xenial

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.4.0-6ubuntu1~16.04.5' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)

pgcc 17.10-0 64-bit target on x86-64 Linux -tp haswell
PGI Compilers and Tools
Copyright (c) 2017, NVIDIA CORPORATION.  All rights reserved.
</code>```

.bashrc:

```<code>#CUDA
export PATH=/usr/local/cuda/bin:$PATH;
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH;
#####
ulimit -s unlimited
#####
#Environment Modules
source /usr/share/modules/init/bash
module add /opt/pgi/modulefiles/pgi64/17.10
module add /opt/pgi/modulefiles/openmpi/2.1.2/2017
#####
#intel compiler
source /opt/intel/bin/compilervars.sh intel64
#intel vtune
source /opt/intel/vtune_amplifier/amplxe-vars.sh
#intel advisor
source /opt/intel/advisor/advixe-vars.sh
#intel inspector
source /opt/intel/inspector/inspxe-vars.sh
#intel mkl
source /opt/intel/mkl/bin/mklvars.sh intel64
</code>```

makefile:

```<code>CC = pgcc
CFLAGS_pgcc = -O0 -Minform=inform -Minfo -ta=multicore -g -pg -Mprof=time
CFLAGS = $(CFLAGS_$(CC)) -c
LFLAGS = $(LFLAGS_$(CC)) -L${MKLROOT}/lib/intel64 -lmkl_rt -lpthread -lm -ldl
IFLAGS = $(IFLAGS_$(CC)) -I${MKLROOT}/include

<content is partially neglected>

serial: $(C_OBJ)
        $(CC)  $(IFLAGS) $(CFLAGS) -c msg_ser.c
        $(CC)  $(IFLAGS) -o dplbe $(C_OBJ) msg_ser.o $(LFLAGS)
</code>```

error message:

```<code>lbe.o: In function `equilibrium_distrib':
<content is partially neglected>lbe.c:548: undefined reference to `__pgi_uacc_multicorestart'
<content is partially neglected>lbe.c:583: undefined reference to `__pgi_uacc_multicoreend'
makefile:57: recipe for target 'serial' failed
make: *** [serial] Error 2
</code>```

lbe.c, to which I only add one line as a babystep to use OpenACC.

```<code>#include "header.h"
extern int    max_x, max_y, max_z;
extern int    num_x, x_min, x_max;
extern int    num_proc, n_proc;
extern double tau[2], tau_v[2];

<content is partially neglected>

void equilibrium_distrib(int xy, int z, double ***velcs_df, double dt,
     struct vector forceDen,  struct vector *correctedVel, double *f_eq)
{

<content is partially neglected>

#pragma acc kernels
  {
  for(int q=0; q < 19; q++)
  {
    double term1 = (c_x[q] * correctedVel->x + c_y[q] * correctedVel->y +
                    c_z[q] * correctedVel->z)*3.;
    double term2 = 0.5*term1*term1;
    f_eq[q] = weight[q]*density*(1 + term1 + term2 - term3);
  }
  }
}
</code>```

compile lbe.c to lbe.o message:

```<code>pgcc-Warning--Mprof=time is not supported

PGC-I-0222-Redundant definition for symbol __THROW (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 74)
PGC-I-0222-Redundant definition for symbol __extension__ (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 358)
lbe_zcol:

<content is partially neglected>

equilibrium_distrib:
    558, FMA (fused multiply-add) instruction(s) generated
    559, FMA (fused multiply-add) instruction(s) generated
    560, FMA (fused multiply-add) instruction(s) generated
    565, FMA (fused multiply-add) instruction(s) generated
    566, FMA (fused multiply-add) instruction(s) generated
    567, FMA (fused multiply-add) instruction(s) generated
    573, FMA (fused multiply-add) instruction(s) generated
    577, Loop is parallelizable
         Generating Multicore code
        577, #pragma acc loop gang
    580, FMA (fused multiply-add) instruction(s) generated
</code>```

答:
Thank you very much for your useful hint. I went to check my makefile and found out that it is actually a little bit mess up or said out of date. The "Variables Used by Implicit Rules" in the old makefile are not completely in the correct format. It is why the pgcc compiler and linker did not work correctly.

Here is a new makefile wrote by myself, it is more clean and neat.

```<code>CC = pgcc
CFLAGS = -I${MKLROOT}/include -O0 -Minform=inform -Minfo -ta=multicore -g -pg
LDFLAGS = -L${MKLROOT}/lib/intel64
LDLIBS = -lmkl_rt -lpthread -lm -ldl

C_OBJ = main.o driver.o update.o lbe_update.o \
    bnodes.o bnodes_init.o bnodes_dp.o implicit_force.o lbe.o modes_write.o \
    lub.o velcs_update.o hs3d.o n_list.o objects_init.o objects_map.o \
    clusters.o cluster_force.o cluster_update.o cj_grad.o \
    global_sums.o utils.o output.o \
    init_sphere.o ran_num.o get_forces.o verlet_update.o aggregation.o \
    jacobi_eigenvalue.o

clean:
    rm -f *.o dplbe

%.o : %.c
    $(CC) $(CFLAGS) -c $< -o $@ $(LDFLAGS) $(LDLIBS)

serial: $(C_OBJ)
    $(CC) $(CFLAGS) -c msg_ser.c $(LDFLAGS) $(LDLIBS)
    $(CC) $(CFLAGS) -o dplbe $(C_OBJ) msg_ser.o $(LDFLAGS) $(LDLIBS)
</code>```

Body:
I am trying to parallelize my program in C with OpenACC 2.5 on Ubuntu 16.04 LTS. After a simple modification which is just adding one line, I can compile all my .c files to .o files. In the linking step, pgcc compiler shows

undefined reference to `__pgi_uacc_multicorestart'

and

undefined reference to `__pgi_uacc_multicoreend'

. Google search shows nothing related to these error message. Please help me on this problem.

Here is the information and source code related to my system and program. I try to post the essential part and please let me know if you need anything else.

OS, software:

LSB Version:    core-9.20160110ubuntu0.2-amd64:core-9.20160110ubuntu0.2-noarch:printing-9.20160110ubuntu0.2-amd64:printing-9.20160110ubuntu0.2-noarch:security-9.20160110ubuntu0.2-amd64:security-9.20160110ubuntu0.2-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.3 LTS
Release:    16.04
Codename:   xenial

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/5/lto-wrapper
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 5.4.0-6ubuntu1~16.04.5' --with-bugurl=file:///usr/share/doc/gcc-5/README.Bugs --enable-languages=c,ada,c++,java,go,d,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-5 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-libmpx --enable-plugin --with-system-zlib --disable-browser-plugin --enable-java-awt=gtk --enable-gtk-cairo --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-5-amd64/jre --enable-java-home --with-jvm-root-dir=/usr/lib/jvm/java-1.5.0-gcj-5-amd64 --with-jvm-jar-dir=/usr/lib/jvm-exports/java-1.5.0-gcj-5-amd64 --with-arch-directory=amd64 --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --enable-objc-gc --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5)

pgcc 17.10-0 64-bit target on x86-64 Linux -tp haswell
PGI Compilers and Tools
Copyright (c) 2017, NVIDIA CORPORATION.  All rights reserved.

.bashrc:

#CUDA
export PATH=/usr/local/cuda/bin:$PATH;
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH;
#####
ulimit -s unlimited
#####
#Environment Modules
source /usr/share/modules/init/bash
module add /opt/pgi/modulefiles/pgi64/17.10
module add /opt/pgi/modulefiles/openmpi/2.1.2/2017
#####
#intel compiler
source /opt/intel/bin/compilervars.sh intel64
#intel vtune
source /opt/intel/vtune_amplifier/amplxe-vars.sh
#intel advisor
source /opt/intel/advisor/advixe-vars.sh
#intel inspector
source /opt/intel/inspector/inspxe-vars.sh
#intel mkl
source /opt/intel/mkl/bin/mklvars.sh intel64

makefile:

CC = pgcc
CFLAGS_pgcc = -O0 -Minform=inform -Minfo -ta=multicore -g -pg -Mprof=time
CFLAGS = $(CFLAGS_$(CC)) -c
LFLAGS = $(LFLAGS_$(CC)) -L${MKLROOT}/lib/intel64 -lmkl_rt -lpthread -lm -ldl
IFLAGS = $(IFLAGS_$(CC)) -I${MKLROOT}/include

<content is partially neglected>

serial: $(C_OBJ)
        $(CC)  $(IFLAGS) $(CFLAGS) -c msg_ser.c
        $(CC)  $(IFLAGS) -o dplbe $(C_OBJ) msg_ser.o $(LFLAGS)

error message:

lbe.o: In function `equilibrium_distrib':
<content is partially neglected>lbe.c:548: undefined reference to `__pgi_uacc_multicorestart'
<content is partially neglected>lbe.c:583: undefined reference to `__pgi_uacc_multicoreend'
makefile:57: recipe for target 'serial' failed
make: *** [serial] Error 2

lbe.c, to which I only add one line as a babystep to use OpenACC.

#include "header.h"
extern int    max_x, max_y, max_z;
extern int    num_x, x_min, x_max;
extern int    num_proc, n_proc;
extern double tau[2], tau_v[2];

<content is partially neglected>

void equilibrium_distrib(int xy, int z, double ***velcs_df, double dt,
     struct vector forceDen,  struct vector *correctedVel, double *f_eq)
{

<content is partially neglected>

#pragma acc kernels
  {
  for(int q=0; q < 19; q++)
  {
    double term1 = (c_x[q] * correctedVel->x + c_y[q] * correctedVel->y +
                    c_z[q] * correctedVel->z)*3.;
    double term2 = 0.5*term1*term1;
    f_eq[q] = weight[q]*density*(1 + term1 + term2 - term3);
  }
  }
}

compile lbe.c to lbe.o message:

pgcc-Warning--Mprof=time is not supported

PGC-I-0222-Redundant definition for symbol __THROW (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 74)
PGC-I-0222-Redundant definition for symbol __extension__ (/usr/include/x86_64-linux-gnu/sys/cdefs.h: 358)
lbe_zcol:

<content is partially neglected>

equilibrium_distrib:
    558, FMA (fused multiply-add) instruction(s) generated
    559, FMA (fused multiply-add) instruction(s) generated
    560, FMA (fused multiply-add) instruction(s) generated
    565, FMA (fused multiply-add) instruction(s) generated
    566, FMA (fused multiply-add) instruction(s) generated
    567, FMA (fused multiply-add) instruction(s) generated
    573, FMA (fused multiply-add) instruction(s) generated
    577, Loop is parallelizable
         Generating Multicore code
        577, #pragma acc loop gang
    580, FMA (fused multiply-add) instruction(s) generated

Body:
Thank you very much for your useful hint. I went to check my makefile and found out that it is actually a little bit mess up or said out of date. The "Variables Used by Implicit Rules" in the old makefile are not completely in the correct format. It is why the pgcc compiler and linker did not work correctly.

Here is a new makefile wrote by myself, it is more clean and neat.

CC = pgcc
CFLAGS = -I${MKLROOT}/include -O0 -Minform=inform -Minfo -ta=multicore -g -pg
LDFLAGS = -L${MKLROOT}/lib/intel64
LDLIBS = -lmkl_rt -lpthread -lm -ldl

C_OBJ = main.o driver.o update.o lbe_update.o \
    bnodes.o bnodes_init.o bnodes_dp.o implicit_force.o lbe.o modes_write.o \
    lub.o velcs_update.o hs3d.o n_list.o objects_init.o objects_map.o \
    clusters.o cluster_force.o cluster_update.o cj_grad.o \
    global_sums.o utils.o output.o \
    init_sphere.o ran_num.o get_forces.o verlet_update.o aggregation.o \
    jacobi_eigenvalue.o

clean:
    rm -f *.o dplbe

%.o : %.c
    $(CC) $(CFLAGS) -c $< -o $@ $(LDFLAGS) $(LDLIBS)

serial: $(C_OBJ)
    $(CC) $(CFLAGS) -c msg_ser.c $(LDFLAGS) $(LDLIBS)
    $(CC) $(CFLAGS) -o dplbe $(C_OBJ) msg_ser.o $(LDFLAGS) $(LDLIBS)


来源: stackexchange

问:
l[:] performance problem
Recently I was debugging a code like following

```<code>def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])
</code>```

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?

答:
list = org_list[:] makes a copy of org_list.  Usually you see something like this when you need to modify the list but you want to keep the original around as well.

The code you are showing me doesn't seem like it actually modifies org_list, and if doSomethingelse(list[0]) doesn't modify list, I don't see why it's actually being copied in the first place.  Even if it does modify list, as long as org_list isn't needed after those few lines of code, you could probably get away with just using org_list and not doing the slice copy.

ContentLicense: CC BY-SA 2.5

Title: l[:] performance problem

Body:
Recently I was debugging a code like following

def getList():
    #query db and return a list
    total_list = Model.objects.all()
    result = list()
    for item in total_list:
        if item.attr1:
            result.append(item)
    return result

# in main code
org_list = getList()
list = orgList[:]#this line cause cpu problems.

if len(org_list)>0 and org_list[0].is_special:
    my_item = org_list[0]

for i in list:
    print_item(i)

doSomethingelse(list[0])

In order to simplify the code I change most of it but the main part is here.

In getList method we query db and get 20~30 rows. Then we create a python list from it and return it.
in main method we get org_list variable from getList method
and slice it with orgList[:]

and loop over this list and call spesific elements on it like list[0]

The problem here is that this code runs on a really busy server and unfortunaletty it uses most of the cpu and eventually locks our servers.
Problem here is the line that we slice list varibale with list[:]
if we dont do that and just use org_list variable instead our servers does not have a problem. Does anybosy have any idea why that might happen. is slicing uses alot of cpu or when we use a sliced list. does it uses alot of cpu?


问:
Process Laravel/Redis job from multiple server
We are building a reporting app on Laravel that need to fetch users data from a third-party server that allow 1 request per seconds.

We need to fetch 100K to 1000K rows based on user and we can fetch max 250 rows per request.

So the restriction is:

1. We can send 1 request per seconds

2. 250 rows per request

So, it requires 400-4000 request/jobs to fetch a user data, So, loading data for multiple users is very time-consuming and the server gets slow.

So, now, we are planning to load the data using multiple servers, like 4-10 servers to fetch users data, so we can send 10 requests per second from 10 servers.

How can we design the system and process jobs from multiple servers?

Is it possible to use a dedicated server for hosting Redis and connect to that Redis server from multiple servers and execute jobs? Can any conflict/race-condition happen?

Any hint or prior experience related to this would be really helpful.

答:
The short answer is yes, this is absolutely possible and is something I've implemented in production apps many times before.

Redis is just like any other service and can run anywhere, with clients from anywhere, connecting to it. It's all up to your configuration of the server to dictate how exactly that happens (and adding passwords, configuring spiped, limiting access via the firewall, etc.). I'd reccommend reading up on the documentation they have in the Administration section here: https://redis.io/documentation

Also, when you do make the move to a dedicated Redis host, with multiple clients accessing it, you'll likely want to look into having more than just one Redis server running for reliability, high availability, etc. Redis has efficient and easy replication available with a few simple configuration commands, which you can read more about here: https://redis.io/topics/replication

Last thing on Redis, if you do end up implementing a master-slave set up, you may want to look into high availability and auto-failover if your Master instance were to go down. Redis has a really great utility built into the application that can monitor your Master and Slaves, detect when the Master is down, and automatically re-configure your servers to promote one of the slaves to the new master. The utility is called Redis Sentinel, and you can read about that here: https://redis.io/topics/sentinel

For your question about race conditions, it depends on how exactly you write your jobs that are pushed onto the queue. For your use case though, it doesn't sound like this would be too much of an issue, but it really depends on the constraints of the third-party system. Either way, if you are subject to a race condition, you can still implement a solution for it, but would likely need to use something like a Redis Lock (https://redis.io/topics/distlock). Taylor recently added a new feature to the upcoming Laravel version 5.6 that I believe implements a version of the Redis Lock in the scheduler (https://medium.com/@taylorotwell/laravel-5-6-preview-single-server-scheduling-54df8e0e139b). You can look into how that was implemented, and adapt for your use case if you end up needing it.

ContentLicense: CC BY-SA 3.0


问:
404 for Custom ttf Font on Azure (.NET MVC 5)
I have an issue that I have seen previously answered.  I implemented the solutions, but the problem persists.

I downloaded two custom ttf fonts to use in my project, Monterey and Bakery.

Both fonts are installed.  Both fronts are in my content folder.  I've updated the font properties for both so that content copies "if newer" on build.  I added necessary language to my web config file.  I create font-face rules in my CSS.

On my local machine, even when accessing the AzureSites version of my app, the custom fonts appear.  On every other computer, they do not appear and present a 404 in the console.

Please see the pictures below.  Thanks in advance for the help!

EDITED to add images of the CSS files.

答:
My suspicion is that the issue is the ..  in ..\fonts/baker.ttf.

Let's say that your directory structure is

```<code>content/
   styles/
     stylesheet.css
   fonts/
     baker.ttf
</code>```

so when your html contains

```<code><link rel="stylesheet" href="/content/styles/stylesheet.css"/>
</code>```

the resolved url is /content/styles/../fonts/baker.ttf and everything works great.

But with mvc when its deployed, your stylesheet is probably getting bundled and compiled with bundler. The link is probably something like

```<code><link href="/bundles/css?v=Mny4y0TdpT_Ey6yWlayc6zrqhuQE-XSEh-dK8IJOsqc1" rel="stylesheet">
</code>```

so then the resolved url is /bundles/../fonts/baker.ttf which does not exist. I cannot see from the screenshot if that is the case but that is my guess.

Try using an absolute url such as /content/fonts/baker.ttf for the font-face import rather than a relative one.

Also, that backslash is highly suspect. Use a forward slash, backslashes are not a valid separator in urls.

Body:
My suspicion is that the issue is the ..  in ..\fonts/baker.ttf.

Let's say that your directory structure is

content/
   styles/
     stylesheet.css
   fonts/
     baker.ttf

so when your html contains

<link rel="stylesheet" href="/content/styles/stylesheet.css"/>

the resolved url is /content/styles/../fonts/baker.ttf and everything works great.

But with mvc when its deployed, your stylesheet is probably getting bundled and compiled with bundler. The link is probably something like

<link href="/bundles/css?v=Mny4y0TdpT_Ey6yWlayc6zrqhuQE-XSEh-dK8IJOsqc1" rel="stylesheet">

so then the resolved url is /bundles/../fonts/baker.ttf which does not exist. I cannot see from the screenshot if that is the case but that is my guess.

Try using an absolute url such as /content/fonts/baker.ttf for the font-face import rather than a relative one.

Also, that backslash is highly suspect. Use a forward slash, backslashes are not a valid separator in urls.


问:
How to install System.Security.Cryptography.Pkcs for .Net Framework 4.5
I need to use System.Security.Cryptography.Pkcs for that I have found following command to install Nuget Package.
Install-Package System.Security.Cryptography.Pkcs -Version 4.4.0 with 4.5

When I execute this from PM. it shows error as
Could not install package 'System.Security.Cryptography.Pkcs 4.4.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

答:
If you are on .NET Framework 4.5 you shouldn't need the System.Security.Cryptography.Pkcs package, as it only contains types already in .NET Framework, in System.Security.dll.

Here's the entirety of the net46 implementation of the library, per ildasm:

```<code>.class extern forwarder System.Security.Cryptography.CryptographicAttributeObject
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.CryptographicAttributeObjectCollection
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.CryptographicAttributeObjectEnumerator
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.AlgorithmIdentifier
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.CmsRecipient
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.CmsRecipientCollection
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.CmsRecipientEnumerator
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.ContentInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.EnvelopedCms
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.KeyAgreeRecipientInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.KeyTransRecipientInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9AttributeObject
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9ContentType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9DocumentName
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9MessageDigest
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9SigningTime
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.PublicKeyInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfoCollection
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfoEnumerator
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfoType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifier
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifierOrKey
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifierOrKeyType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifierType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Xml.X509IssuerSerial
{
  .assembly extern System.Security
}
</code>```

If you're needing to interoperate with something using .NET Standard you need to upgrade to at least .NET Framework 4.6, because no cryptography types are defined prior to .NET Standard 1.3 (which aligns to .NET Framework 4.6)

Body:
If you are on .NET Framework 4.5 you shouldn't need the System.Security.Cryptography.Pkcs package, as it only contains types already in .NET Framework, in System.Security.dll.

Here's the entirety of the net46 implementation of the library, per ildasm:

.class extern forwarder System.Security.Cryptography.CryptographicAttributeObject
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.CryptographicAttributeObjectCollection
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.CryptographicAttributeObjectEnumerator
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.AlgorithmIdentifier
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.CmsRecipient
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.CmsRecipientCollection
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.CmsRecipientEnumerator
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.ContentInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.EnvelopedCms
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.KeyAgreeRecipientInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.KeyTransRecipientInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9AttributeObject
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9ContentType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9DocumentDescription
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9DocumentName
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9MessageDigest
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.Pkcs9SigningTime
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.PublicKeyInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfo
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfoCollection
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfoEnumerator
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.RecipientInfoType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifier
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifierOrKey
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifierOrKeyType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Pkcs.SubjectIdentifierType
{
  .assembly extern System.Security
}
.class extern forwarder System.Security.Cryptography.Xml.X509IssuerSerial
{
  .assembly extern System.Security
}

If you're needing to interoperate with something using .NET Standard you need to upgrade to at least .NET Framework 4.6, because no cryptography types are defined prior to .NET Standard 1.3 (which aligns to .NET Framework 4.6)


问:
Add value to Hashtable using lambda
Fist of all, I'm pretty new to Java my approach to the problem might not be optimal.

I have some lists of strings, say {"a", "b", "e", "g"} and {"no", "a", "g", "great"}, which contain 4 items each from a set of values.

I want to create a Hashtable of that set, assigning an int value to each String. For a specific String, I want to use a lambda expression to assign different values to it based on the other items in the list it's contained in, something like:

```<code>class bla {
    static Map stuff;
    static {
        // If I write it like this, I get the error "Cannot resolve method ContainsAll"
         stuff.put("g", (aList) -> (aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 1 : 2));
    }
}
</code>```

If I add a List<String> to (aList) like so, (List <String> aList) then I get, a "Target type of a lambda expression must be an interface" error.

If I replace () with {} for the lambda body, I get the "; expected error".

How can I write this to work? Or, do you have a better idea?

答:
This should do the trick for you.

Oh, and you want a Map<String,Integer>, not a Hashtable. Hashtable is not deprecated, but very bad and slow for most of your use-cases.

```<code>import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
  public static void main(String[] args) {
    Map<String,Integer> map = Stream.of("no", "a", "g", "great")
      .collect(Collectors.toMap(
        Function.identity(),
        x -> Arrays.asList("a", "b", "e", "g").contains(x) ? 1 : 2
      ));
    System.out.println(map);
  }
}
</code>```

Output:

```<code>{a=1, no=2, g=1, great=2}
</code>```

Title: Add value to Hashtable using lambda

Body:
Fist of all, I'm pretty new to Java my approach to the problem might not be optimal.

I have some lists of strings, say {"a", "b", "e", "g"} and {"no", "a", "g", "great"}, which contain 4 items each from a set of values.

I want to create a Hashtable of that set, assigning an int value to each String. For a specific String, I want to use a lambda expression to assign different values to it based on the other items in the list it's contained in, something like:

class bla {
    static Map stuff;
    static {
        // If I write it like this, I get the error "Cannot resolve method ContainsAll"
         stuff.put("g", (aList) -> (aList.containsAll(Arrays.asList("a", "b", "e", "g")) ? 1 : 2));
    }
}

If I add a List<String> to (aList) like so, (List <String> aList) then I get, a "Target type of a lambda expression must be an interface" error.

If I replace () with {} for the lambda body, I get the "; expected error".

How can I write this to work? Or, do you have a better idea?

Body:
This should do the trick for you.

Oh, and you want a Map<String,Integer>, not a Hashtable. Hashtable is not deprecated, but very bad and slow for most of your use-cases.

import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
  public static void main(String[] args) {
    Map<String,Integer> map = Stream.of("no", "a", "g", "great")
      .collect(Collectors.toMap(
        Function.identity(),
        x -> Arrays.asList("a", "b", "e", "g").contains(x) ? 1 : 2
      ));
    System.out.println(map);
  }
}

Output:

{a=1, no=2, g=1, great=2}


问:
No taskbar icon for application
So I have this application I have made in VB. The problem is that when I start it it does not show up in my taskbar. It only shows up if I maximize another window infront of it and then minimize it. Also it has the basic VB icon even though I changed the icon in the properties.

There is no relevant code for this issue.

答:
I found the same thing; no icon was showing in the taskbar. I had to go into Task Manager and Switch To the program to get it to show. I could ' maximize another window in front of it and then minimize it as well.'
Found the solution that worked for me. The 'Main' form did not have anything in the 'text' property because I was doing that and a Ver number in the program. As soon as I put text into the 'text' property, it started working. The problem was only with VB2015. Worked fine in VB2010.</p>

Title: No taskbar icon for application


问:
PHP password recovery
I realize that for security that passwords should not be stored in a DB as plaintext.  If I hash them, I can validate them for login purposes.

But if I want to set up a password recovery system, what's the best strategy since there is no undoing of the hashing?

Could someone give me a brief overview of a good and secure strategy for storing and recovering passwords?

答:
You can not recover password that were hashed, neither should you.

What you should do instead is:

Put some verification on the password reset request, like CAPTCHA.

Create an one-time random code and send a link with it to user's email.

Have this code expire in, say, an hour.

Have this code expire immediately once used.

On the link with the code, if it validates, allow him to change his password.

Notify him that the password was changed, but do not send it in the email.

Title: PHP password recovery


问:
Javascript create zip file
I am developing a website using react.js and admin-on-rest. One feature is allowing users to upload a pdf file.

I get the file as type FILE and want to get the file from FILE, compress it to zip, and then make it to type FILE.

So it should be FILE -> origin file -> zip file -> FILE from zip file.

I tried JSZip but still can not figure it out.

Any help is appreciated. Thanks

答: There is a small app called jszip for this. Try, it would help. https://stuk.github.io/jszip/</p>

Title: Javascript create zip file


问:
Combine non NA values for n Lists R

A -  I have a list containing igraph graph objects:

```<code>goodgg

[[1]]
IGRAPH UN-- 3 3 --
+ attr: name (v/c), color (v/c), value (e/n), sourceID (e/n), targetID (e/n)
+ edges (vertex names):
[1] 89315--89316 89315--89928 89316--89928

[[2]]
IGRAPH UN-- 3 2 --
+ attr: name (v/c), color (v/c), value (e/n), sourceID (e/n), targetID (e/n)
+ edges (vertex names):
[1] 106277--106278 106278--106279
</code>```

I can combine these into a single object using [union][1]:

```<code>combine = graph.union(goodgg[[1]], goodgg[[2]], byname=T)

combine
IGRAPH UN-- 6 5 --
+ attr: color_1 (v/c), color_2 (v/c), name (v/c)
+ edges (vertex names):
</code>```

From this, I can extract particular attributes e.g. a color, which lines up with the order of the original objects (1 - 2):

```<code>as.list(get.vertex.attribute(combine))
$color_1
[1] "red"    "red"    "orange" NA       NA       NA

$color_2
[1] NA    NA    NA    "red" "red" "red"

$name
[1] "89315"  "89316"  "89928"  "106277" "106278" "106279"
</code>```

How can I extract the non NA values in $color_1 and $color_2 and merge them into a new list when I have an arbitrary number of color_n entries? (E.g. I have n entries)?

To get:

```<code>[1] "red"    "red"    "orange" "red"    "red"    "red"
</code>```

What I tried (which does not work for n color_ variables:

In this simple case I can do what this answer did here:

```<code>V(combine)$color <- ifelse(is.na(get.vertex.attribute(combine)$color_1), get.vertex.attribute(combine)$color_2,get.vertex.attribute(combine)$color_1)

get.vertex.attribute(combine)$color
[1] "red"    "red"    "orange" "red"    "red"    "red"
</code>```

However, in reality my list could have n elements. How can I adjust this to account for n elements?

I considered using multiple nested IFELSE statements such as here and here a la:

```<code>V(combine)$color <- ifelse(is.na(get.vertex.attribute(combine)$color_1), ifelse(is.na(get.vertex.attribute(combine)$color_2), ifelse(get.vertex.attribute(combine)$color_3)......))
</code>```

This does not work for unknown n attributes and does not solve the issue of having an unknown number n of attributes to work with.

Many thanks for your help.

答:
You can use Reduce to "cumulatively" apply a function over a vector:

```<code>set.seed(125)

color_choices <- c("red", "orange", NA)

color_samples <- replicate(
  4,
  sample(color_choices, 5, replace = TRUE),
  simplify = FALSE
)
color_samples
# [[1]]
# [1] NA       "red"    "red"    "orange" NA
#
# [[2]]
# [1] NA       "orange" "red"    "orange" "orange"
#
# [[3]]
# [1] "red"    NA       "orange" "red"    "orange"
#
# [[4]]
# [1] "orange" "orange" NA       NA       NA

Reduce(
  f = function(a, b) ifelse(is.na(a), b, a),
  x = color_samples
)
# [1] [1] "red"    "red"    "red"    "orange" "orange"
</code>```

In this case, Reduce applied the function to the first and second elements, then to that result and the third element, then to that result and the fourth element.  If the list were longer, it would've kept going on that way.

Edit for your specific situation: save the list of attributes, find which have names like color_n, and then use the Reduce solution on those.

```<code>combine_attributes <- as.list(get.vertex.attribute(combine))
</code>```

Because I don't have your data, let's just say combine_attributes looks like the color_samples created above with an extra element:

```<code>combine_attributes
# $color_1
# [1] NA       "red"    "red"    "orange" NA
#
# $color_2
# [1] NA       "orange" "red"    "orange" "orange"
#
# $color_3
# [1] "red"    NA       "orange" "red"    "orange"
#
# $color_4
# [1] "orange" "orange" NA       NA       NA
#
# $name
# [1] "89315"  "89316"  "89928"  "106277" "106278"

color_attributes <- grep(
  "^color_\\d+$",
  names(combine_attributes),
  value = TRUE
)

color_attributes
# [1] "color_1" "color_2" "color_3" "color_4"

Reduce(
  f = function(a, b) ifelse(is.na(a), b, a),
  x = combine_attributes[color_attributes]
)
# [1] "red"    "red"    "red"    "orange" "orange"
</code>```

Title: Combine non NA values for n Lists R

Body:
A -  I have a list containing igraph graph objects:

goodgg

[[1]]
IGRAPH UN-- 3 3 --
+ attr: name (v/c), color (v/c), value (e/n), sourceID (e/n), targetID (e/n)
+ edges (vertex names):
[1] 89315--89316 89315--89928 89316--89928

[[2]]
IGRAPH UN-- 3 2 --
+ attr: name (v/c), color (v/c), value (e/n), sourceID (e/n), targetID (e/n)
+ edges (vertex names):
[1] 106277--106278 106278--106279

I can combine these into a single object using [union][1]:

combine = graph.union(goodgg[[1]], goodgg[[2]], byname=T)

combine
IGRAPH UN-- 6 5 --
+ attr: color_1 (v/c), color_2 (v/c), name (v/c)
+ edges (vertex names):

From this, I can extract particular attributes e.g. a color, which lines up with the order of the original objects (1 - 2):

as.list(get.vertex.attribute(combine))
$color_1
[1] "red"    "red"    "orange" NA       NA       NA

$color_2
[1] NA    NA    NA    "red" "red" "red"

$name
[1] "89315"  "89316"  "89928"  "106277" "106278" "106279"

How can I extract the non NA values in $color_1 and $color_2 and merge them into a new list when I have an arbitrary number of color_n entries? (E.g. I have n entries)?

To get:

[1] "red"    "red"    "orange" "red"    "red"    "red"

What I tried (which does not work for n color_ variables:

In this simple case I can do what this answer did here:

V(combine)$color <- ifelse(is.na(get.vertex.attribute(combine)$color_1), get.vertex.attribute(combine)$color_2,get.vertex.attribute(combine)$color_1)

get.vertex.attribute(combine)$color
[1] "red"    "red"    "orange" "red"    "red"    "red"

However, in reality my list could have n elements. How can I adjust this to account for n elements?

I considered using multiple nested IFELSE statements such as here and here a la:

V(combine)$color <- ifelse(is.na(get.vertex.attribute(combine)$color_1), ifelse(is.na(get.vertex.attribute(combine)$color_2), ifelse(get.vertex.attribute(combine)$color_3)......))

This does not work for unknown n attributes and does not solve the issue of having an unknown number n of attributes to work with.

Many thanks for your help.

Body:
You can use Reduce to "cumulatively" apply a function over a vector:

set.seed(125)

color_choices <- c("red", "orange", NA)

color_samples <- replicate(
  4,
  sample(color_choices, 5, replace = TRUE),
  simplify = FALSE
)
color_samples
# [[1]]
# [1] NA       "red"    "red"    "orange" NA
#
# [[2]]
# [1] NA       "orange" "red"    "orange" "orange"
#
# [[3]]
# [1] "red"    NA       "orange" "red"    "orange"
#
# [[4]]
# [1] "orange" "orange" NA       NA       NA

Reduce(
  f = function(a, b) ifelse(is.na(a), b, a),
  x = color_samples
)
# [1] [1] "red"    "red"    "red"    "orange" "orange"

In this case, Reduce applied the function to the first and second elements, then to that result and the third element, then to that result and the fourth element.  If the list were longer, it would've kept going on that way.

Edit for your specific situation: save the list of attributes, find which have names like color_n, and then use the Reduce solution on those.

combine_attributes <- as.list(get.vertex.attribute(combine))

Because I don't have your data, let's just say combine_attributes looks like the color_samples created above with an extra element:

combine_attributes
# $color_1
# [1] NA       "red"    "red"    "orange" NA
#
# $color_2
# [1] NA       "orange" "red"    "orange" "orange"
#
# $color_3
# [1] "red"    NA       "orange" "red"    "orange"
#
# $color_4
# [1] "orange" "orange" NA       NA       NA
#
# $name
# [1] "89315"  "89316"  "89928"  "106277" "106278"

color_attributes <- grep(
  "^color_\\d+$",
  names(combine_attributes),
  value = TRUE
)

color_attributes
# [1] "color_1" "color_2" "color_3" "color_4"

Reduce(
  f = function(a, b) ifelse(is.na(a), b, a),
  x = combine_attributes[color_attributes]
)
# [1] "red"    "red"    "red"    "orange" "orange"


问:
INSERT data in table with result of a SELECT
I'm trying to populate a table with the result of a select, but I always get the following error :

Duplicate entry '0' for key 'PRIMARY' SQL=INSERT INTO fab_bloquer_jours ( id,day,date ) VALUES ( '','4','2017-12-04 14:55:49' )

My table fab_bloquer_jours is :

```<code>1   id Primary  int(11)
2   day int(13)
3   date    datetime
</code>```

My query is :

```<code>$day=$data['fab_bloquer_jours___day'];

$query = $db->getQuery(true);
$query = "INSERT INTO fab_bloquer_jours (day)
SELECT *
   FROM (
        SELECT DATE_ADD('2018-01-01',
            INTERVAL n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) AS DATE
          FROM (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
         ) AS n1,
         (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
        ) AS n2,
        (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
        ) AS n3,
        (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
        ) AS n4
    ) AS a
WHERE DATE >= '2018-01-01' AND DATE < '2019-01-01'
  AND WEEKDAY(DATE) = '$day'";
$db->setQuery($query);
$query=$db->execute();
</code>```

I get the $date value through a dropdown.

I would appreciate some help here, since I can't figure out how to make it work.

答:
Try setting your id column on your table to auto increment. Then do not include it on your insert statement.

So, for your example, try this query after you update your id field to auto increment:

```<code>INSERT INTO fab_bloquer_jours (day,date) VALUES ('4','2017-12-04 14:55:49');
</code>```

Body:
I'm trying to populate a table with the result of a select, but I always get the following error :

Duplicate entry '0' for key 'PRIMARY' SQL=INSERT INTO fab_bloquer_jours ( id,day,date ) VALUES ( '','4','2017-12-04 14:55:49' )

My table fab_bloquer_jours is :

1   id Primary  int(11)
2   day int(13)
3   date    datetime

My query is :

$day=$data['fab_bloquer_jours___day'];

$query = $db->getQuery(true);
$query = "INSERT INTO fab_bloquer_jours (day)
SELECT *
   FROM (
        SELECT DATE_ADD('2018-01-01',
            INTERVAL n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) AS DATE
          FROM (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
         ) AS n1,
         (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
        ) AS n2,
        (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
        ) AS n3,
        (
              SELECT 0 AS num
              UNION ALL SELECT 1
              UNION ALL SELECT 2
              UNION ALL SELECT 3
              UNION ALL SELECT 4
              UNION ALL SELECT 5
              UNION ALL SELECT 6
              UNION ALL SELECT 7
              UNION ALL SELECT 8
              UNION ALL SELECT 9
        ) AS n4
    ) AS a
WHERE DATE >= '2018-01-01' AND DATE < '2019-01-01'
  AND WEEKDAY(DATE) = '$day'";
$db->setQuery($query);
$query=$db->execute();

I get the $date value through a dropdown.

I would appreciate some help here, since I can't figure out how to make it work.

Body:
Try setting your id column on your table to auto increment. Then do not include it on your insert statement.

So, for your example, try this query after you update your id field to auto increment:

INSERT INTO fab_bloquer_jours (day,date) VALUES ('4','2017-12-04 14:55:49');


问:
Azure AD: How to get group information in token?
We have application developed in MEAN stack. We are using adal-angular library for azure ad authentication. As per the documentation and sample

Adal.js uses the OAuth implicit flow to communicate with Azure AD. You
must enable the implicit flow for your application.

However when we enable implicit flow, Azure AD DOES NOT include group information in the token. The issue has been discussed here in detail and confirmed by @vibronet

Question

Azure AD functionalities have been changing almost everyday, so are the above answers still valid? Do we still have to enable implicit flow of our application? I want to get group information in token (i dont want to use graph api as a solution.)

another reason i am asking this question because i disabled the implicit flow and user was still able to access the application. However i still don't see group information in the token.

答:
Azure AD JWT does emit security groups in implicit flow.
In Application Registration manifest, set "groupMembershipClaims": "SecurityGroup",

Then in your server:

```<code>var groups = new List<string>();
ClaimsPrincipal.Current.Claims
    .Where(t => t.Type == "groups")
    .ForEach(g => groups.Add(g.Value));
</code>```

no need for GraphApi

https://learn.microsoft.com/en-us/azure/architecture/multitenant-identity/app-roles
https://github.com/Azure-Samples/active-directory-dotnet-webapp-groupclaims

ContentLicense: CC BY-SA 4.0

Body:
Azure AD JWT does emit security groups in implicit flow.
In Application Registration manifest, set "groupMembershipClaims": "SecurityGroup",

Then in your server:

var groups = new List<string>();
ClaimsPrincipal.Current.Claims
    .Where(t => t.Type == "groups")
    .ForEach(g => groups.Add(g.Value));

no need for GraphApi

https://learn.microsoft.com/en-us/azure/architecture/multitenant-identity/app-roles
https://github.com/Azure-Samples/active-directory-dotnet-webapp-groupclaims


问:
Style Datagrid Header border issue
I try to style datagridcolumn header but at the top right I have a double border.

I try to play with margin but it doesn't work I have always this double border at runtime.

How I can avoid this?

```<code><Style TargetType="{x:Type DataGridRow}">
    <Setter Property="Background" Value="{StaticResource BrushAbbGrey255}" />
    <Setter Property="FontFamily" Value="ABBVoice" />
</Style>

<Style TargetType="{x:Type DataGridCell}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridCell}">
                <Border Padding="7,5,7,4">
                    <ContentPresenter VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Foreground" Value="{StaticResource BrushAbbGrey90}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Border x:Name="BackgroundBorder"
                            BorderThickness="1,1,1,1"
                            Margin="-1,0,0,0"
                            Background="{StaticResource BrushAbbGrey240}"
                            BorderBrush="{StaticResource BrushAbbGrey200}"
                            Grid.ColumnSpan="2" />
                    <ContentPresenter Margin="8,10,7,10" VerticalAlignment="Center"/>
                    <Path x:Name="SortArrow" Visibility="Collapsed" Data="M0,0 L1,0 0.5,1 z" Stretch="Fill"
                        Grid.Column="1" Width="8" Height="6" Fill="White" Margin="0,0,8,0"
                        VerticalAlignment="Center" RenderTransformOrigin="0.5,0.4" />
                </Grid>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

答:
Try to set the right-margin to -1:

```<code><Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Foreground" Value="{StaticResource BrushAbbGrey90}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Border x:Name="BackgroundBorder"
                            BorderThickness="1,1,1,1"
                            Margin="-1,0,-1,0"
                            Background="{StaticResource BrushAbbGrey240}"
                            BorderBrush="{StaticResource BrushAbbGrey200}"
                            Grid.ColumnSpan="2" SnapsToDevicePixels="True" />
                    <ContentPresenter Margin="8,10,7,10" VerticalAlignment="Center"/>
                    <Path x:Name="SortArrow" Visibility="Collapsed" Data="M0,0 L1,0 0.5,1 z" Stretch="Fill"
                        Grid.Column="1" Width="8" Height="6" Fill="White" Margin="0,0,8,0"
                        VerticalAlignment="Center" RenderTransformOrigin="0.5,0.4" />
                </Grid>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

You may also want to set the SnapsToDevicePixels property of the Border to true.

Title: Style Datagrid Header border issue

Body:
Try to set the right-margin to -1:

<Style TargetType="{x:Type DataGridColumnHeader}">
    <Setter Property="Foreground" Value="{StaticResource BrushAbbGrey90}" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type DataGridColumnHeader}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="Auto" />
                    </Grid.ColumnDefinitions>
                    <Border x:Name="BackgroundBorder"
                            BorderThickness="1,1,1,1"
                            Margin="-1,0,-1,0"
                            Background="{StaticResource BrushAbbGrey240}"
                            BorderBrush="{StaticResource BrushAbbGrey200}"
                            Grid.ColumnSpan="2" SnapsToDevicePixels="True" />
                    <ContentPresenter Margin="8,10,7,10" VerticalAlignment="Center"/>
                    <Path x:Name="SortArrow" Visibility="Collapsed" Data="M0,0 L1,0 0.5,1 z" Stretch="Fill"
                        Grid.Column="1" Width="8" Height="6" Fill="White" Margin="0,0,8,0"
                        VerticalAlignment="Center" RenderTransformOrigin="0.5,0.4" />
                </Grid>

            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

You may also want to set the SnapsToDevicePixels property of the Border to true.


问:
Rhino Mock 3.6 Repository Expected #0, Actual#1
I'm using Rhino Mock 3.6 Repository and Nhibernate. But I'm getting ExpectationViolationException Expected#0, Actual #1. I've spent two days on it. I don't know what i'm doing wrong. Here is my code. I'm getting error on mockRepository.Save(user) line.

```<code>        var username = "abcdef";
        var mocks = new MockRepository();
        var validationResults = new ValidationResults();
        IDataQuery query = mocks.StrictMock<IDataQuery>();
        UserRepository mockRepository = mocks.StrictMock<UserRepository>(query);
        var user = mocks.StrictMock<User>();

        user.FirstName = "javed";
        user.LastName = "ahmad";
        user.UserName = "abc";
        user.Password = "password";
        user.Email = "nadeem@test.com";
        user.IsActive = true;
        user.CreatedBy = 1000000;
        user.CreatedDate = DateTime.Today;
        user.ModifiedBy = 1000000;
        user.ModifiedDate = DateTime.Today;

        Expect.Call(user.Validate()).Return(validationResults);
        mocks.ReplayAll();

        mockRepository.Save(user);
</code>```

Thanks in Advance.

Thanks
Imran

答:
You appear to be mocking everything even the sut i.e. userrepository
you should be setting up mocks on interfaces that will be used inside the userrepository.  you will need to pass these in to the userrepository to override their default behaviour somehow.

You need to decide what you actually want to test.

The code above implies the following to me

```<code>class UserRepository
{
  public void Save(IUser user)
  {
    validationResult = user.Validate();
    if (validationResult==null)
    {
      dal.Save(user);
    }
  }
}
</code>```

That's just a guess, but the point is the code you currently have should only be mocking the user if your intention is to test that the validate method is called within the userrepository.save method

Body:
I'm using Rhino Mock 3.6 Repository and Nhibernate. But I'm getting ExpectationViolationException Expected#0, Actual #1. I've spent two days on it. I don't know what i'm doing wrong. Here is my code. I'm getting error on mockRepository.Save(user) line.

        var username = "abcdef";
        var mocks = new MockRepository();
        var validationResults = new ValidationResults();
        IDataQuery query = mocks.StrictMock<IDataQuery>();
        UserRepository mockRepository = mocks.StrictMock<UserRepository>(query);
        var user = mocks.StrictMock<User>();

        user.FirstName = "javed";
        user.LastName = "ahmad";
        user.UserName = "abc";
        user.Password = "password";
        user.Email = "nadeem@test.com";
        user.IsActive = true;
        user.CreatedBy = 1000000;
        user.CreatedDate = DateTime.Today;
        user.ModifiedBy = 1000000;
        user.ModifiedDate = DateTime.Today;

        Expect.Call(user.Validate()).Return(validationResults);
        mocks.ReplayAll();

        mockRepository.Save(user);

Thanks in Advance.

Thanks
Imran

Body:
You appear to be mocking everything even the sut i.e. userrepository
you should be setting up mocks on interfaces that will be used inside the userrepository.  you will need to pass these in to the userrepository to override their default behaviour somehow.

You need to decide what you actually want to test.

The code above implies the following to me

class UserRepository
{
  public void Save(IUser user)
  {
    validationResult = user.Validate();
    if (validationResult==null)
    {
      dal.Save(user);
    }
  }
}

That's just a guess, but the point is the code you currently have should only be mocking the user if your intention is to test that the validate method is called within the userrepository.save method


问:
Microsoft Dynamics Nav Connector For Java
Currently I am working on implementing a connector for Microsoft Dynamics Nav in Java.

For that I want to create a connection with Dynamics Nav server through NTLM. Most of the blogs and documentations I found regarding this are outdated.

Connecting to NAV Web Services from Java

It will be appreciated if anyone can suggest me a method to handle Dynamics Nav authentication using org.apache.http.client.HttpClient. (Please suggest me if there is any Java client library available for Dynamics Nav)

Furthermore, it will be appreciated if any one can suggest me a place where I can get a free Dynamics Nav testing environment to test my Dynamics Nav connector application.

答:
Windows Challenge/Response (NTLM) is the authentication protocol used on networks that include systems running the Windows operating system and on stand-alone systems. I was able to handle NTLM authentication using org.apache.http.client.HttpClient version 4.4.

Here is the Maven dependency I have used (Methods and method names can be slightly different in other versions).

```<code><dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.4</version>
</dependency>
</code>```

Following imports are required for the implementation. This is the basic requirement for a non-SSL connection.

```<code>import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
</code>```

Here is the implementation. Need to replace Username, Password, and Domain with real credentials.

```<code>CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
HttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credentialsProvider)
                .build();

credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("Username", "Password", null, "Domain"));
</code>```

Now this http client can be used to communicate with the Dynamics NAV API.

But I was unable to find a free testing environment for Microsoft Dynamics NAV within my region (Asia). But few cloud service providers are offering free testing trials for other regions.

As a Linux user I had to install Windows in a virtual environment and install Dynamics NAV on it to create a testing environment. If you are familiar with Docker you can download the Dynamics NAV Docker image from this link.

Body:
Windows Challenge/Response (NTLM) is the authentication protocol used on networks that include systems running the Windows operating system and on stand-alone systems. I was able to handle NTLM authentication using org.apache.http.client.HttpClient version 4.4.

Here is the Maven dependency I have used (Methods and method names can be slightly different in other versions).

<dependency>
 <groupId>org.apache.httpcomponents</groupId>
 <artifactId>httpclient</artifactId>
 <version>4.4</version>
</dependency>

Following imports are required for the implementation. This is the basic requirement for a non-SSL connection.

import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;

Here is the implementation. Need to replace Username, Password, and Domain with real credentials.

CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
HttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider(credentialsProvider)
                .build();

credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials("Username", "Password", null, "Domain"));

Now this http client can be used to communicate with the Dynamics NAV API.

But I was unable to find a free testing environment for Microsoft Dynamics NAV within my region (Asia). But few cloud service providers are offering free testing trials for other regions.

As a Linux user I had to install Windows in a virtual environment and install Dynamics NAV on it to create a testing environment. If you are familiar with Docker you can download the Dynamics NAV Docker image from this link.


问:
Meteor: Update object nested two arrays deep
I have a collection with a key called fields, which is an array of JSON objects. Those objects can have options which is another array of JSON objects. I’m trying to update one of the options by optionId. I tried this but it doesn't work.

```<code>Projects.update({
  'fields.options._id': optionId
}, {
  $set: {
    `fields.$.options.$.title`: title
  }
}
</code>```

This does find the correct Project document, but doesn't update it.

答:
You can use the $ operator for single level arrays only. Use of array1.$.array2.$.key is not supported.

However, if you are aware of the exact index of the element to be updated within the array, you can update like so:

```<code>Projects.update({
  'fields.options._id': optionId
}, {
  $set: {
    `fields.0.options.1.title`: title
  }
}
</code>```

This is one way to update:

```<code>Projects.find({"fields.options._id":optionId}).forEach(function(record) {
    var match = false;
    // iterate fields array
    for(var i=0; i< record.fields.length; i++){
      // iterate options array
      for(var j=0; j<record.fields[i].options.length; j++){

        if(record.fields[i].options[j]._id == optionsID){
           record.fields[i].options[j].title = title;
           match = true;
           // break;
       }

      }
    }

    if (match === true) Projects.update( { 'fields.options._id': optionId }, record );

});
</code>```

Source

Body:
I have a collection with a key called fields, which is an array of JSON objects. Those objects can have options which is another array of JSON objects. I’m trying to update one of the options by optionId. I tried this but it doesn't work.

Projects.update({
  'fields.options._id': optionId
}, {
  $set: {
    `fields.$.options.$.title`: title
  }
}

This does find the correct Project document, but doesn't update it.

Body:
You can use the $ operator for single level arrays only. Use of array1.$.array2.$.key is not supported.

However, if you are aware of the exact index of the element to be updated within the array, you can update like so:

Projects.update({
  'fields.options._id': optionId
}, {
  $set: {
    `fields.0.options.1.title`: title
  }
}

This is one way to update:

Projects.find({"fields.options._id":optionId}).forEach(function(record) {
    var match = false;
    // iterate fields array
    for(var i=0; i< record.fields.length; i++){
      // iterate options array
      for(var j=0; j<record.fields[i].options.length; j++){

        if(record.fields[i].options[j]._id == optionsID){
           record.fields[i].options[j].title = title;
           match = true;
           // break;
       }

      }
    }

    if (match === true) Projects.update( { 'fields.options._id': optionId }, record );

});

Source


问:
displaying a vector of deques in columns
I'm trying to display a vector of deques (std::vector<std::deque<int>> v) like this

```<code>v.at(0).at(0) v.at(1).at(0) v.at(2).at(0) v.at(3).at(0)
v.at(0).at(1) v.at(1).at(1) v.at(2).at(1) v.at(3).at(1)
v.at(0).at(2) v.at(1).at(2) v.at(2).at(2) v.at(3).at(2)
              v.at(1).at(3)               v.at(3).at(3)
                                          v.at(3).at(4)
</code>```

The first part of the vector is fixed at 7, the size of the actual columns are dynamic however depending on what the user chooses to do.

I was attempting something like

```<code>int row = 0;
int column;

for (column = 0; column < v.at(row).size(); column++){
      cout << "v["<< row <<"]["<< column << "]" << v.at(row).at(column) << "\t";
  while (row < v.size()){
    cout << endl;
    row++;
  }
}
</code>```

I'm getting errors like

```<code>libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
make: *** [Pile.h] Abort trap: 6
</code>```

Having one of those blah brain days. Can someone help me print this out the way I want it?

答:
First of all, I suggest to get the max queue size

```<code>std::size_t  maxQ { 0U };

for ( auto const & q : v )
    maxQ = std::max(maxQ, q.size());
</code>```

Now you can write a loop over (0U, maxQ( (the loop of lines) writing elements when available and space otherwise.

```<code>for ( auto i = 0U ; i < maxQ ; ++i )
 {
   for ( auto j = 0U ; j < v.size() ; ++j )
      if ( i < v[j].size() )
         ; // print v[j][i]
      else
         ; // print space

   std::cout << std::endl; // endl of line
 }
</code>```

I leave to you cells printing details

Body:
I'm trying to display a vector of deques (std::vector<std::deque<int>> v) like this

v.at(0).at(0) v.at(1).at(0) v.at(2).at(0) v.at(3).at(0)
v.at(0).at(1) v.at(1).at(1) v.at(2).at(1) v.at(3).at(1)
v.at(0).at(2) v.at(1).at(2) v.at(2).at(2) v.at(3).at(2)
              v.at(1).at(3)               v.at(3).at(3)
                                          v.at(3).at(4)

The first part of the vector is fixed at 7, the size of the actual columns are dynamic however depending on what the user chooses to do.

I was attempting something like

int row = 0;
int column;

for (column = 0; column < v.at(row).size(); column++){
      cout << "v["<< row <<"]["<< column << "]" << v.at(row).at(column) << "\t";
  while (row < v.size()){
    cout << endl;
    row++;
  }
}

I'm getting errors like

libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: vector
make: *** [Pile.h] Abort trap: 6

Having one of those blah brain days. Can someone help me print this out the way I want it?

Body:
First of all, I suggest to get the max queue size

std::size_t  maxQ { 0U };

for ( auto const & q : v )
    maxQ = std::max(maxQ, q.size());

Now you can write a loop over (0U, maxQ( (the loop of lines) writing elements when available and space otherwise.

for ( auto i = 0U ; i < maxQ ; ++i )
 {
   for ( auto j = 0U ; j < v.size() ; ++j )
      if ( i < v[j].size() )
         ; // print v[j][i]
      else
         ; // print space

   std::cout << std::endl; // endl of line
 }

I leave to you cells printing details


问:
What is dispose of null in Angular 4
I am getting "what is dispose of null" when load the page.
 I am to get list of data but unable to show those record in view.
Here i added code snippet to understand my requirement

Angular JS Service File

```<code>import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class PostsService {
 data: any = null;
 totalDocs: number;
 url: any = 'http://localhost:3000/services/';
 constructor(private _http: Http) { }

 public getPosts() {
  return this._http.get(this.url + 'posts')
              .map((res: Response) => res.json());
 }
}

//End Angular JS Web service*
</code>```

Node JS code to get data from MongoDB

```<code>import { default as Category} from "../models/Category";
import { default as Post} from "../models/Post";
import { Request, Response, NextFunction } from "express";

export let getPostsAPI = (req: Request, res: Response, next: NextFunction) => {
const post: any = req.body;
const cond: any = {};
if (!this.empty(post.kword)) {

 *//$text is full text index*

  cond.$text = {$search : post.kword};
}
if (!this.empty(post.location)) {
  cond.city = {$regex: new RegExp("^" + post.location, "i") };
}

*Counting total number of records and
Here Post is reference of collection, its working fine and generating data as i given bottom of this post.*
Post.count(cond).then(totalDocs => {
  Post.find(cond).sort({created_at: -1}).then(result => {
    const results = {data: result, totalDocs: totalDocs};
    console.log(results);
    res.end("" + JSON.stringify(results));
  });
 });
};
</code>```

End node JS Code

Angular JS home.component.ts where i am calling web serive to render data in angular view

```<code>export class HomeComponent implements OnInit {
  results: any = {};
  model: any = {};
  constructor(private posts: PostsService) {
    posts.getPosts().subscribe(res => {
    console.log(res.totalDocs); // Showing number of records in console.
    this.results = res.data; // this is throwing error.
  *//Error is: TypeError: Cannot read property 'dispose' of null*
  });
 this.model.kword = '';
 this.model.location = '';
}
  ngOnInit() {
  }
}
</code>```

Template Code

```<code><div class="container">
  <app-filter [result]=value (clicked)="searchJob($event)"></app-filter>
  <!-- /.row -->
  <div class="row" >
    <div class="col-sm-10 my-10" *ngFor="let post of results | async">
      <div class="card">
          <div class="card-body">
              <h3 class="mt-1"><a [routerLink]="['/job', post.company, post.title, post._id]">{{ post.title }}</a></h3>
              <p class="mt-1" *ngIf="post.company"><span class="badge badge-primary">{{post.company}}</span></p>
              <p class="mt-1" *ngIf="post.salary_min">Salary up to: ₹{{post.salary_min}} - ₹{{post.salary_max}}</p>
              <p class="mt-1" *ngIf="post.city || post.state">Location: {{post.city}}, <span *ngIf="post.state">{{post.state}}</span></p>
              <p class="mt-1" *ngIf="post.description">{{post.description | slice:0:150}}[...]</p>
          </div>
      </div>
    </div>
  </div>
  <!-- /.row -->
</div>
</code>```

End Template
JSON DATA WHICH COMING FROM API

     {
       "data":
        [
         {
           "title":"test title",
           "description":"test description"
         }
        ],
        "totalRecords":2
     }

i attached a screenshot of error.

答:
The async pipe subscribes to an observable for you, so it needs to be fed an observable, you're feeding it the resulting value of an observable, which is why you're seeing this error.

Do it like this instead:

```<code>results: Observable<any>;
model: any = {};
constructor(private posts: PostsService) {
  this.results = posts.getPosts().map(res => res.data);
  this.model.kword = '';
  this.model.location = '';
}
</code>```

Now you're setting the "results" value to the actual observable, and letting async handle the subscription part.

Title: What is dispose of null in Angular 4

Body:
I am getting "what is dispose of null" when load the page.
 I am to get list of data but unable to show those record in view.
Here i added code snippet to understand my requirement

Angular JS Service File

import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Injectable()
export class PostsService {
 data: any = null;
 totalDocs: number;
 url: any = 'http://localhost:3000/services/';
 constructor(private _http: Http) { }

 public getPosts() {
  return this._http.get(this.url + 'posts')
              .map((res: Response) => res.json());
 }
}

//End Angular JS Web service*

Node JS code to get data from MongoDB

import { default as Category} from "../models/Category";
import { default as Post} from "../models/Post";
import { Request, Response, NextFunction } from "express";

export let getPostsAPI = (req: Request, res: Response, next: NextFunction) => {
const post: any = req.body;
const cond: any = {};
if (!this.empty(post.kword)) {

 *//$text is full text index*

  cond.$text = {$search : post.kword};
}
if (!this.empty(post.location)) {
  cond.city = {$regex: new RegExp("^" + post.location, "i") };
}

*Counting total number of records and
Here Post is reference of collection, its working fine and generating data as i given bottom of this post.*
Post.count(cond).then(totalDocs => {
  Post.find(cond).sort({created_at: -1}).then(result => {
    const results = {data: result, totalDocs: totalDocs};
    console.log(results);
    res.end("" + JSON.stringify(results));
  });
 });
};

End node JS Code

Angular JS home.component.ts where i am calling web serive to render data in angular view

export class HomeComponent implements OnInit {
  results: any = {};
  model: any = {};
  constructor(private posts: PostsService) {
    posts.getPosts().subscribe(res => {
    console.log(res.totalDocs); // Showing number of records in console.
    this.results = res.data; // this is throwing error.
  *//Error is: TypeError: Cannot read property 'dispose' of null*
  });
 this.model.kword = '';
 this.model.location = '';
}
  ngOnInit() {
  }
}

Template Code

  <app-filter [result]=value (clicked)="searchJob($event)"></app-filter>

{{ post.title }}

{{post.company}}

Salary up to: ₹{{post.salary_min}} - ₹{{post.salary_max}}

Location: {{post.city}}, {{post.state}}

{{post.description | slice:0:150}}[...]

End Template
JSON DATA WHICH COMING FROM API

     {
       "data":
        [
         {
           "title":"test title",
           "description":"test description"
         }
        ],
        "totalRecords":2
     }

i attached a screenshot of error.

Body:
The async pipe subscribes to an observable for you, so it needs to be fed an observable, you're feeding it the resulting value of an observable, which is why you're seeing this error.

Do it like this instead:

results: Observable<any>;
model: any = {};
constructor(private posts: PostsService) {
  this.results = posts.getPosts().map(res => res.data);
  this.model.kword = '';
  this.model.location = '';
}

Now you're setting the "results" value to the actual observable, and letting async handle the subscription part.


问:
How to reset a React-Bootstrap Form after submit?
I added React-Bootstrap to my app. So I change a basic form with React-Bootstrap components.

I can't reset a form after a submit.

Here is my simplified code:

```<code>import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap';

class MyForm extends React.Component {

    onSubmit( event ) {
        event.preventDefault();
        const textAreaValue = this.textArea.value;
        console.log("textAreaValue : ", textAreaValue);

        // some code here...

        // ERROR HERE (but it works if I
        // replace bootstrap <Form>
        // component by a simple <form>
        this.messageForm.reset();
    }

    render() {

        return (
            <Form
                className="form"
                ref={ form => this.messageForm = form }
                onSubmit={ this.onSubmit.bind( this ) }
            >

                <FormGroup controlId="formControlsTextarea">
                    <ControlLabel>My Control Label</ControlLabel>
                    <FormControl
                        required
                        inputRef={ input => this.textArea = input }
                        componentClass="textarea" />
                </FormGroup>

                <Button type="submit">ok</Button>
            </Form>
        );

    }

}
export default MyForm;
</code>```

I could continue to use a normal  then it works but I wonder how to use that one component of React-Boostrap.

Has someone an idea?

The error:

```<code>× TypeError: this.messageForm.reset is not a function
</code>```

When I log this.messageForm it's a React-Bootstrap component. I also tested with inputRef instead of ref but it doesn't work

答:
By the way I suggest the simplest is to just use simple <form> instead of React-Bootstrap <Form>. And then this.messageForm.reset() works well.

But if for some reasons you need to use Bootstrap Form component, add an id to the form as follows:

```<code>        <Form
            id='myForm'
            className="form"
            ref={ form => this.messageForm = form }
            onSubmit={ this.onSubmit.bind( this ) }>
            ...
        </Form>
</code>```

And in the onSubmit method, access the form element created by React-Bootstrap as follows:

```<code>ReactDOM.findDOMNode(this.messageForm).reset();
</code>```

Body:
I added React-Bootstrap to my app. So I change a basic form with React-Bootstrap components.

I can't reset a form after a submit.

Here is my simplified code:

import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap';

class MyForm extends React.Component {

    onSubmit( event ) {
        event.preventDefault();
        const textAreaValue = this.textArea.value;
        console.log("textAreaValue : ", textAreaValue);

        // some code here...

        // ERROR HERE (but it works if I
        // replace bootstrap <Form>
        // component by a simple <form>
        this.messageForm.reset();
    }

    render() {

        return (
            <Form
                className="form"
                ref={ form => this.messageForm = form }
                onSubmit={ this.onSubmit.bind( this ) }
            >

                <FormGroup controlId="formControlsTextarea">
                    <ControlLabel>My Control Label</ControlLabel>
                    <FormControl
                        required
                        inputRef={ input => this.textArea = input }
                        componentClass="textarea" />
                </FormGroup>

                <Button type="submit">ok</Button>
            </Form>
        );

    }

}
export default MyForm;

I could continue to use a normal  then it works but I wonder how to use that one component of React-Boostrap.

Has someone an idea?

The error:

× TypeError: this.messageForm.reset is not a function

When I log this.messageForm it's a React-Bootstrap component. I also tested with inputRef instead of ref but it doesn't work

Body:
By the way I suggest the simplest is to just use simple <form> instead of React-Bootstrap <Form>. And then this.messageForm.reset() works well.

But if for some reasons you need to use Bootstrap Form component, add an id to the form as follows:

        <Form
            id='myForm'
            className="form"
            ref={ form => this.messageForm = form }
            onSubmit={ this.onSubmit.bind( this ) }>
            ...
        </Form>

And in the onSubmit method, access the form element created by React-Bootstrap as follows:

ReactDOM.findDOMNode(this.messageForm).reset();


问:
Django apps on Heroku: how to access a shared database
On Heroku, it is possible to share a database among apps using the following command:

```<code>$ heroku addons:attach <databaseName> -a <appName>
</code>```

where <databaseName> is the shared database (belonging to another app) and it is attached to the app <appName> (a Django application).

I googled around for a long time but couldn't find anything describing how to access the attached database in the app. Do I need to add or modify something to Django's settings.py and what? How do I access the attached database in Django's views.py?

The following is the setting for Heroku databases and database accessing is just via ORM.

```<code># Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default':dj_database_url.config()}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
</code>```

Thanks.

答:
Heroku always supplies configuration details as environment variables. When you do addons:attach it will print the name of the variable it has created for your attached add-on; alternatively you can specify it with the --as flag.

```<code>heroku addons:attach <databaseName> -a <appName> --as MY_ATTACHED_DB_URL
</code>```

Now you can pass that variable name to the config call:

```<code>DATABASES = {
    'default':dj_database_url.config(),
    'course': dj_database_url.config('MY_ATTACHED_DB_URL')
}
</code>```

Body:
On Heroku, it is possible to share a database among apps using the following command:

$ heroku addons:attach <databaseName> -a <appName>

where <databaseName> is the shared database (belonging to another app) and it is attached to the app <appName> (a Django application).

I googled around for a long time but couldn't find anything describing how to access the attached database in the app. Do I need to add or modify something to Django's settings.py and what? How do I access the attached database in Django's views.py?

The following is the setting for Heroku databases and database accessing is just via ORM.

# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES = {'default':dj_database_url.config()}
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

Thanks.

Body:
Heroku always supplies configuration details as environment variables. When you do addons:attach it will print the name of the variable it has created for your attached add-on; alternatively you can specify it with the --as flag.

heroku addons:attach <databaseName> -a <appName> --as MY_ATTACHED_DB_URL

Now you can pass that variable name to the config call:

DATABASES = {
    'default':dj_database_url.config(),
    'course': dj_database_url.config('MY_ATTACHED_DB_URL')
}


问:
Formatting strings from a text file
I'm trying to format my text line by line read from a .txt file. Firstly I'm just trying to figure out how to print just one line, then attempt multiple lines after. I've managed to print the text of one line, but when I try to format it they way I want it to look, a new line is created after I attempt to print the last word of the line (using index of -1). The last word is creating a new line, so I think I need to find a way to read the lines as seperate strings but I'm not sure.

This is the code for my program:

```<code>def makeTuple (employee):

    myTuple = employee.split(" ")
    payroll, salary, job_title, *othernames, surname = myTuple
    myTuple = tuple(myTuple)
    return(myTuple)

def printTuple (data):

    employee_str = "{}, {} {:>8} {} {:>5}"
    print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    text_file = open(path, "r")
except IOError:
    print('The file could not be opened.')
    exit()

record = text_file.readline()

myTuple = makeTuple(record)
printTuple(myTuple)
</code>```

This is the text file I'm reading from:

```<code>12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
</code>```

The output I get at the moment is:

```<code>Simpson
, Bart    12345 Consultant 55000
</code>```

Whereas I want it to look like:

```<code>Simpson, Bart    12345 Consultant 55000
</code>```

答:
You are getting a newline after "Simpson" because that's what's in the text file.

Use the function strip() (Documentation) to remove the newlines when you read the line.

Change the following one line of code and your program should work.

```<code>record = text_file.readline().strip()
</code>```

Title: Formatting strings from a text file

Body:
I'm trying to format my text line by line read from a .txt file. Firstly I'm just trying to figure out how to print just one line, then attempt multiple lines after. I've managed to print the text of one line, but when I try to format it they way I want it to look, a new line is created after I attempt to print the last word of the line (using index of -1). The last word is creating a new line, so I think I need to find a way to read the lines as seperate strings but I'm not sure.

This is the code for my program:

def makeTuple (employee):

    myTuple = employee.split(" ")
    payroll, salary, job_title, *othernames, surname = myTuple
    myTuple = tuple(myTuple)
    return(myTuple)

def printTuple (data):

    employee_str = "{}, {} {:>8} {} {:>5}"
    print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    text_file = open(path, "r")
except IOError:
    print('The file could not be opened.')
    exit()

record = text_file.readline()

myTuple = makeTuple(record)
printTuple(myTuple)

This is the text file I'm reading from:

12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger

The output I get at the moment is:

Simpson
, Bart    12345 Consultant 55000

Whereas I want it to look like:

Simpson, Bart    12345 Consultant 55000

Body:
You are getting a newline after "Simpson" because that's what's in the text file.

Use the function strip() (Documentation) to remove the newlines when you read the line.

Change the following one line of code and your program should work.

record = text_file.readline().strip()


问:
Expand dataframe but retain variables in R
I would like to expand a dataframe based on all pairwise combinations of one variable while keeping the associate value of a second variable. For example:

```<code>V1 <- letters[1:2]
V2 <- 1:2
df <- data.frame(V1, V2)
</code>```

I would like to return:

```<code>Var1 Var2 Var3 Var4
a    a    1    1
b    a    2    1
a    b    1    2
b    b    2    2
</code>```

I can use expand.grid(df$V1, df$V1) to get all of the pairs, but I'm not sure how to include the second variable without having its values expanded also.

答:
If we need to expand each column separately, then we can do this with Map where the arguments are two 'df' objects

```<code>do.call(cbind, Map(expand.grid, df, df))
</code>```

Body:
I would like to expand a dataframe based on all pairwise combinations of one variable while keeping the associate value of a second variable. For example:

V1 <- letters[1:2]
V2 <- 1:2
df <- data.frame(V1, V2)

I would like to return:

Var1 Var2 Var3 Var4
a    a    1    1
b    a    2    1
a    b    1    2
b    b    2    2

I can use expand.grid(df$V1, df$V1) to get all of the pairs, but I'm not sure how to include the second variable without having its values expanded also.

Body:
If we need to expand each column separately, then we can do this with Map where the arguments are two 'df' objects

do.call(cbind, Map(expand.grid, df, df))


问:
Saving and retrieving date in Firebase
I have a model with the following structure

```<code>public class OfferModel {
    private String mImageUrl;
    private String mOfferCode;
    private String mOfferTitle;
    private String mOfferDescription;
    private boolean mIsRunning;
    private String mCreatorUid;
    private Date mStartDate;
}
</code>```

Everything else works fine on saving. It saves in Firebase Realtime database as

```<code>startDate
    date: 22
    day: 3
    hours: 23
    minutes: 20
    month: 5
    seconds: 50
    time: 1466617850476
    timezoneOffset: -330
    year: 116
</code>```

But when I try to retrieve it, the date gives the following error -

```<code>java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Date
at com.localvine.models.OfferModel.<init>(OfferModel.java:37)
at com.localvine.managers.OfferManager$1.onDataChange(OfferManager.java:62)
at com.google.android.gms.internal.zzafp.zza(Unknown Source)
at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
at com.google.android.gms.internal.zzags$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:615)
</code>```

I understand that Firebase doesn't support Java Date object, but since it's saving them in a map, how can I get back the date from that map? Is there any proper way of saving and retrieving dates in Firebase Android?

答:
Although firebase does support Date format datatype, I would prefer to save date-time in a string format, because by storing it as a string it becomes quite easy to retrieve it.

To store current system date-time in a string format just below code will do.

```<code>        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String strDate = dateFormat.format(date).toString();
        myRef.child("datetime").setValue(strDate);
</code>```

Now one can use the strDate to store in the firebase or do whatever one want to do with that string.

Title: Saving and retrieving date in Firebase

Body:
I have a model with the following structure

public class OfferModel {
    private String mImageUrl;
    private String mOfferCode;
    private String mOfferTitle;
    private String mOfferDescription;
    private boolean mIsRunning;
    private String mCreatorUid;
    private Date mStartDate;
}

Everything else works fine on saving. It saves in Firebase Realtime database as

startDate
    date: 22
    day: 3
    hours: 23
    minutes: 20
    month: 5
    seconds: 50
    time: 1466617850476
    timezoneOffset: -330
    year: 116

But when I try to retrieve it, the date gives the following error -

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Date
at com.localvine.models.OfferModel.<init>(OfferModel.java:37)
at com.localvine.managers.OfferManager$1.onDataChange(OfferManager.java:62)
at com.google.android.gms.internal.zzafp.zza(Unknown Source)
at com.google.android.gms.internal.zzagp.zzSu(Unknown Source)
at com.google.android.gms.internal.zzags$1.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:615)

I understand that Firebase doesn't support Java Date object, but since it's saving them in a map, how can I get back the date from that map? Is there any proper way of saving and retrieving dates in Firebase Android?

Body:
Although firebase does support Date format datatype, I would prefer to save date-time in a string format, because by storing it as a string it becomes quite easy to retrieve it.

To store current system date-time in a string format just below code will do.

        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        String strDate = dateFormat.format(date).toString();
        myRef.child("datetime").setValue(strDate);

Now one can use the strDate to store in the firebase or do whatever one want to do with that string.


问:
C++ Structure Initialization
Is it possible to initialize structs in C++ as indicated below:

```<code>struct address {
    int street_no;
    char *street_name;
    char *city;
    char *prov;
    char *postal_code;
};

address temp_address = { .city = "Hamilton", .prov = "Ontario" };
</code>```

The links here and here mention that it is possible to use this style only in C.  If so why is this not possible in C++?  Is there any underlying technical reason why it is not implemented in C++, or is it bad practice to use this style.  I like using this way of initializing because my struct is big and this style gives me clear readability of what value is assigned to which member.

Please share with me if there are other ways through which we can achieve the same readability.

I have referred the following links before posting this question:

C/C++ for AIX

C Structure Initialization with Variable

Static structure initialization with tags in C++

C++11 Proper Structure Initialization

答:
As others have mentioned this is designated initializer.

This feature is part of C++20

Title: C++ Structure Initialization

Body:
Is it possible to initialize structs in C++ as indicated below:

struct address {
    int street_no;
    char *street_name;
    char *city;
    char *prov;
    char *postal_code;
};

address temp_address = { .city = "Hamilton", .prov = "Ontario" };

The links here and here mention that it is possible to use this style only in C.  If so why is this not possible in C++?  Is there any underlying technical reason why it is not implemented in C++, or is it bad practice to use this style.  I like using this way of initializing because my struct is big and this style gives me clear readability of what value is assigned to which member.

Please share with me if there are other ways through which we can achieve the same readability.

I have referred the following links before posting this question:

C/C++ for AIX

C Structure Initialization with Variable

Static structure initialization with tags in C++

C++11 Proper Structure Initialization


问:
Subset columns in R dataframe issue?
I have a dataframe df that I want to subset in the following way:

Columns 1-7 and a vector of columns cols:

```<code>cols = c("rs1057079", "rs1057079.1", "rs4845882", "rs4845882.1", "rs1891932", "rs1891932.1", "rs530296", "rs530296.1", "rs10497340", "rs10497340.1")
</code>```

So what I did is df[, c(1:7, cols)] but R throws an error:

```<code>Error in `[.data.frame`(df, , c(seq(1:7), SNPs_dup)) :
  undefined columns selected
</code>```

What is wrong here?? I can subset on 1:7 and cols but why not on both of them?

答:
c(1:7, cols) coerces the sequence 1:7 to characters which are further treated as columns names '1', '2' ... instead of column positions, you can extract the 1-7 column names and then concatenate with cols and subset:

```<code>df[,c(names(df)[1:7], cols)]
</code>```

Or convert cols to positions:

```<code>df[,c(1:7, match(cols, names(df)))]
</code>```

Title: Subset columns in R dataframe issue?

Body:
I have a dataframe df that I want to subset in the following way:

Columns 1-7 and a vector of columns cols:

cols = c("rs1057079", "rs1057079.1", "rs4845882", "rs4845882.1", "rs1891932", "rs1891932.1", "rs530296", "rs530296.1", "rs10497340", "rs10497340.1")

So what I did is df[, c(1:7, cols)] but R throws an error:

Error in `[.data.frame`(df, , c(seq(1:7), SNPs_dup)) :
  undefined columns selected

What is wrong here?? I can subset on 1:7 and cols but why not on both of them?

Body:
c(1:7, cols) coerces the sequence 1:7 to characters which are further treated as columns names '1', '2' ... instead of column positions, you can extract the 1-7 column names and then concatenate with cols and subset:

df[,c(names(df)[1:7], cols)]

Or convert cols to positions:

df[,c(1:7, match(cols, names(df)))]


问:
Git get line edit time
Good evening.
How to get line edit time in epoch in git?
I used command

```<code>git blame -t -L line_num,line_num -- file
</code>```

But it brings a lot not needed info
I just want to get one number

答:
Use -p (porcelain) to output in a more computer-friendly format.

You can then pipe into awk to find the parts of the output that you need

```<code>git blame -p -t -L line_num,line_num -- file | awk '/author-time/ {print $2}'
</code>```

Optionally pipe out to uniq if you want to remove duplicates entries.

Source: https://www.git-scm.com/docs/git-blame

Title: Git get line edit time

Body:
Good evening.
How to get line edit time in epoch in git?
I used command

git blame -t -L line_num,line_num -- file

But it brings a lot not needed info
I just want to get one number

Body:
Use -p (porcelain) to output in a more computer-friendly format.

You can then pipe into awk to find the parts of the output that you need

git blame -p -t -L line_num,line_num -- file | awk '/author-time/ {print $2}'

Optionally pipe out to uniq if you want to remove duplicates entries.

Source: https://www.git-scm.com/docs/git-blame