问:
Angular Service not a global singleton
I was under the impression that a Angular Service is a Singleton, but have recently discovered, or atleast it seems, that the service is only a singleton to the instance of the component and the component's children.

Consider the following code:

```<code>const CACHE_REFRESH_INTERVAL = 1800000; //30 minutes
const CACHE_SIZE = 1;

const COMPANY_CACHE_KEY = 'company_cache_key';

@Injectable({
  providedIn: "root"
})
export class CompanyService {

  private companyCache: Map<string, Observable<any>> = new Map();

  constructor(private httpClient: HttpClient) { }

  public getAllCompanies(): Observable<CompanyViewModel[]> {
    if (!this.companyCache[COMPANY_CACHE_KEY]) {
      const timer$ = timer(0, CACHE_REFRESH_INTERVAL);
      this.companyCache[COMPANY_CACHE_KEY] = timer$.pipe(
        switchMap(_ => this.getAllCompaniesHttpRequest()),
        shareReplay(CACHE_SIZE),
        refCount(),
        catchError(err => this.companyCache[COMPANY_CACHE_KEY] = undefined) //prevents storing error in cache
      );
    }
    return this.companyCache[COMPANY_CACHE_KEY];
  }

  private getAllCompaniesHttpRequest(): Observable<CompanyViewModel[]> {
    return this.httpClient.get<CompanyViewModel[]>(environment.endpoints.company.getAllCompanies());
  }
}
</code>```

Let's say, ComponentA gets this service injected through the component's instructor.  When ComponentA calls the CompanyService.getAllCompanies() method, the results will be stored in companyCache.  Now the user navigates to a new URL, ComponentA get destroyed, as well as the instance of the service.  Navigate back to ComponentA, and a new instance of the service is injected, and companyCache is once again empty.

Is my assumption correct?  Can I make a service a singleton accross the entire application?

答:
I was under the impression that a Angular Service is a Singleton, but have recently discovered, or atleast it seems, that the service is only a singleton to the instance of the component and the component's children.

That shall happen when you put your CompanyService inside the component's providers array. Services are singletons by default, but you can override that.

Take a trivial service:

```<code>import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SomeService {
  public someRandomValue = Math.random();

  constructor() {
    console.log("I've just got instantiated.");
  }
}
</code>```

and two components that have SomeService in their providers array. For both of them, someRandomValue will be different, and "I've just got instantiated." will be logged twice:

https://stackblitz.com/edit/angular-oua1nf?file=src%2Fapp%2Fsome.service.ts

Title: Angular Service not a global singleton

Body:
I was under the impression that a Angular Service is a Singleton, but have recently discovered, or atleast it seems, that the service is only a singleton to the instance of the component and the component's children.

Consider the following code:

const CACHE_REFRESH_INTERVAL = 1800000; //30 minutes
const CACHE_SIZE = 1;

const COMPANY_CACHE_KEY = 'company_cache_key';

@Injectable({
  providedIn: "root"
})
export class CompanyService {

  private companyCache: Map<string, Observable<any>> = new Map();

  constructor(private httpClient: HttpClient) { }

  public getAllCompanies(): Observable<CompanyViewModel[]> {
    if (!this.companyCache[COMPANY_CACHE_KEY]) {
      const timer$ = timer(0, CACHE_REFRESH_INTERVAL);
      this.companyCache[COMPANY_CACHE_KEY] = timer$.pipe(
        switchMap(_ => this.getAllCompaniesHttpRequest()),
        shareReplay(CACHE_SIZE),
        refCount(),
        catchError(err => this.companyCache[COMPANY_CACHE_KEY] = undefined) //prevents storing error in cache
      );
    }
    return this.companyCache[COMPANY_CACHE_KEY];
  }

  private getAllCompaniesHttpRequest(): Observable<CompanyViewModel[]> {
    return this.httpClient.get<CompanyViewModel[]>(environment.endpoints.company.getAllCompanies());
  }
}

Let's say, ComponentA gets this service injected through the component's instructor.  When ComponentA calls the CompanyService.getAllCompanies() method, the results will be stored in companyCache.  Now the user navigates to a new URL, ComponentA get destroyed, as well as the instance of the service.  Navigate back to ComponentA, and a new instance of the service is injected, and companyCache is once again empty.

Is my assumption correct?  Can I make a service a singleton accross the entire application?

Body:
I was under the impression that a Angular Service is a Singleton, but have recently discovered, or atleast it seems, that the service is only a singleton to the instance of the component and the component's children.

That shall happen when you put your CompanyService inside the component's providers array. Services are singletons by default, but you can override that.

Take a trivial service:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class SomeService {
  public someRandomValue = Math.random();

  constructor() {
    console.log("I've just got instantiated.");
  }
}

and two components that have SomeService in their providers array. For both of them, someRandomValue will be different, and "I've just got instantiated." will be logged twice:

https://stackblitz.com/edit/angular-oua1nf?file=src%2Fapp%2Fsome.service.ts


来源: stackexchange

问:
How define relative path to file?
I have a project with cucumber and maven, work from Intellij IDEA.

I need to use a relative file path. Now I am working on mac os, but then the project will also be used on windows.

How do I determine the relative path from RunnerTest.java to application.properties file for mac os?

Will there be any differences in defining the same path for Windows?

Here is my RunnerTest.Java Class

public class RunnerTest {

    public static void main(String[] args) throws Throwable {
        System.setProperty("TagConfigFile", "../../config/application.properties");

        //...

        String sConfigFile = System.getProperty("TagConfigFile", "null");

        try (InputStream streamFromResources = Props.class.getClassLoader().getResourceAsStream(sConfigFile)) {
            /* work wiht  streamFromResources */
        } catch (IOException | NullPointerException ee) {
            throw new PropsRuntimeException("Failed to access properties file", ee);
        }
    }
}
```

<p>Here is the image of my project structure (for clarity, added highlighting):</p>

<p><img src="https://i.stack.imgur.com/T7GBw.png" alt="enter image description here"></p>

<p>I tried to use such ways. But it did not help</p>

<pre class="lang-java prettyprint-override"><code> 1. "../../config/application.properties"
 2. "src/resources/config/application.properties"
 3. "../../resources/config/application.properties"
</code>```

答:
I do not pretend to be correct, but it worked:

I created the folder resources in src -> main and moved the folder config there. I created the folder resources in src -> test and moved the all other folders there. The result is such a structure:

src
 |----main
 |      |
 |      |----java
 |      |----resources
 |      |        |----config
 |      |        |       |----application.properties
 |
 |----test
 |      |----resources
 |      |        |----features
 |      |        |----pipes
 |      |        |----testdata
 |      |        |----webdrivers
```

Instead System.setProperty("TagConfigFile", "../../config/application.properties");
I wrote System.setProperty("TagConfigFile", "./config/application.properties"); in RunnerTest.java class

If someone offers a more beautiful working solution, I will be very glad

ContentLicense: CC BY-SA 4.0

Title: How define relative path to file?

Body:
I have a project with cucumber and maven, work from Intellij IDEA.

I need to use a relative file path. Now I am working on mac os, but then the project will also be used on windows.

How do I determine the relative path from RunnerTest.java to application.properties file for mac os?

Will there be any differences in defining the same path for Windows?

Here is my RunnerTest.Java Class

public class RunnerTest {

    public static void main(String[] args) throws Throwable {
        System.setProperty("TagConfigFile", "../../config/application.properties");

        //...

        String sConfigFile = System.getProperty("TagConfigFile", "null");

        try (InputStream streamFromResources = Props.class.getClassLoader().getResourceAsStream(sConfigFile)) {
            /* work wiht  streamFromResources */
        } catch (IOException | NullPointerException ee) {
            throw new PropsRuntimeException("Failed to access properties file", ee);
        }
    }
}

Here is the image of my project structure (for clarity, added highlighting):

I tried to use such ways. But it did not help

 1. "../../config/application.properties"
 2. "src/resources/config/application.properties"
 3. "../../resources/config/application.properties"

Body:
I do not pretend to be correct, but it worked:

I created the folder resources in src -> main and moved the folder config there. I created the folder resources in src -> test and moved the all other folders there. The result is such a structure:

src
 |----main
 |      |
 |      |----java
 |      |----resources
 |      |        |----config
 |      |        |       |----application.properties
 |
 |----test
 |      |----resources
 |      |        |----features
 |      |        |----pipes
 |      |        |----testdata
 |      |        |----webdrivers

Instead System.setProperty("TagConfigFile", "../../config/application.properties");
I wrote System.setProperty("TagConfigFile", "./config/application.properties"); in RunnerTest.java class

If someone offers a more beautiful working solution, I will be very glad


问:
Tarjan algorithm - Python to scala
I'm trying to translate the recursive python code for tarjan algorithm to scala and especially this part :

```<code>def tarjan_recursive(g):
        S = []
        S_set = set()
        index = {}
        lowlink = {}
        ret = []
        def visit(v):
                index[v] = len(index)
                lowlink[v] = index[v]
                S.append(v)
                S_set.add(v)

                for w in g.get(v,()):
                        print(w)
                        if w not in index:
                                visit(w)
                                lowlink[v] = min(lowlink[w], lowlink[v])
                        elif w in S_set:
                                lowlink[v] = min(lowlink[v], index[w])
                if lowlink[v] == index[v]:
                        scc = []
                        w = None
                        while v != w:
                                w = S.pop()
                                scc.append(w)
                                S_set.remove(w)
                        ret.append(scc)

        for v in g:
                print(index)
                if not v in index:
                        visit(v)
        return ret
</code>```

I know that there's tarjan algorithm in scala here  or here but it doesn't return good result and translate it from python help me understand it.

Here's what I have :

```<code>def tj_recursive(g: Map[Int,List[Int]])= {
        var s : mutable.ListBuffer[Int] = new mutable.ListBuffer()
        var s_set : mutable.Set[Int] = mutable.Set()
        var index : mutable.Map[Int,Int] =  mutable.Map()
        var lowlink : mutable.Map[Int,Int]=  mutable.Map()
        var ret : mutable.Map[Int,mutable.ListBuffer[Int]]= mutable.Map()

        def visit(v: Int):Int = {
                 index(v) = index.size
               lowlink(v) = index(v)
               var zz :List[Int]= gg.get(v).toList(0)
                            for( w <- zz) {
                  if( !(index.contains(w)) ){
                     visit(w)
                     lowlink(v) = List(lowlink(w),lowlink(v)).min
                   }else if(s_set.contains(w)){
                     lowlink(v)=List(lowlink(v),index(w)).min
                   }
               }

               if(lowlink(v)==index(v)){
                  var scc:mutable.ListBuffer[Int] = new mutable.ListBuffer()
                  var w:Int=null.asInstanceOf[Int]
                  while(v!=w){
                    w= s.last
                    scc+=w
                    s_set-=w
                  }
           ret+=scc
        }
        }

   for( v <- g) {if( !(index.contains(v)) ){visit(v)}}
   ret
}
</code>```

I know this isn't the scala way at all (and not clean ...) but I'm planning to slowly change it to a more functional style when I get the first version working.

For now, I got this error :

```<code>type mismatch;  found   : Unit  required: Int
</code>```

at this line

```<code>if(lowlink(v)==index(v)){
</code>```

I think it's coming from this line but I'm not sure :

```<code>if( !(index.contains(w))
</code>```

But it's really hard to debug it since I can't just println my mistakes ...

Thanks !

答:
I know this post is old, but I have lately been working with the implementation of Tarjans algorithm in Scala. In the implementation of the code, I was looking at this post and it occurred to me, that it could be done in a simpler way:</p>

```<code>case class Edge[A](from: A, to: Set[A])

class TarjanGraph[A](src: Iterable[Edge[A]]) {
  lazy val trajan: mutable.Buffer[mutable.Buffer[A]] = {
    var s = mutable.Buffer.empty[A] //Stack to keep track of nodes reachable from current node
    val index = mutable.Map.empty[A, Int] //index of each node
    val lowLink = mutable.Map.empty[A, Int] //The smallest index reachable from the node
    val ret = mutable.Buffer.empty[mutable.Buffer[A]] //Keep track of SCC in graph
def visit(v: A): Unit = {
  //Set index and lowlink of node on first visit
  index(v) = index.size
  lowLink(v) = index(v)
  //Add to stack
  s += v
  if (src.exists(_.from == v)) {
    for (w <- src.find(e => e.from == v).head.to) {
      if (!index.contains(w)) { //Node is not explored yet
        //Perform DFS from node W
        visit(w)
        //Update the lowlink value of v so it has the value of the lowest node reachable from itself and from node w
        lowLink(v) = math.min(lowLink(w), lowLink(v))
      } else if (s.contains(w)) {
        // Node w is on the stack meaning - it means there is a path from w to v
        // and since node w is a neighbor to node v there is also a path from v to w
        lowLink(v) = math.min(lowLink(v), index(w))
      }
    }
  }
  //The lowlink value haven't been updated meaning it is the root of a cycle/SCC
  if (lowLink(v) == index(v)) {
    //Add the elements to the cycle that has been added to the stack and whose lowlink has been updated by node v's lowlink
    //This is the elements on the stack that is placed behind v
    val n = s.length - s.indexOf(v)
    ret += s.takeRight(n)
    //Remove these elements from the stack
    s.dropRightInPlace(n)
  }
}

//Perform a DFS from  all no nodes that hasn't been explored
src.foreach(v => if (!index.contains(v.from)) visit(v.from))
ret
  }

  // A cycle exist if there is a SCC with at least two components
  lazy val hasCycle: Boolean = trajan.exists(_.size >= 2)
  lazy val trajanCycle: Iterable[Seq[A]] = trajan.filter(_.size >= 2).distinct.map(_.toSeq).toSeq
  lazy val topologicalSortedEdges: Seq[Edge[A]] =
    if (hasCycle) Seq[Edge[A]]()
    else trajan.flatten.reverse.flatMap(x => src.find(_.from == x)).toSeq
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Tarjan algorithm - Python to scala

Body:
I'm trying to translate the recursive python code for tarjan algorithm to scala and especially this part :

def tarjan_recursive(g):
        S = []
        S_set = set()
        index = {}
        lowlink = {}
        ret = []
        def visit(v):
                index[v] = len(index)
                lowlink[v] = index[v]
                S.append(v)
                S_set.add(v)

                for w in g.get(v,()):
                        print(w)
                        if w not in index:
                                visit(w)
                                lowlink[v] = min(lowlink[w], lowlink[v])
                        elif w in S_set:
                                lowlink[v] = min(lowlink[v], index[w])
                if lowlink[v] == index[v]:
                        scc = []
                        w = None
                        while v != w:
                                w = S.pop()
                                scc.append(w)
                                S_set.remove(w)
                        ret.append(scc)

        for v in g:
                print(index)
                if not v in index:
                        visit(v)
        return ret

I know that there's tarjan algorithm in scala here  or here but it doesn't return good result and translate it from python help me understand it.

Here's what I have :

def tj_recursive(g: Map[Int,List[Int]])= {
        var s : mutable.ListBuffer[Int] = new mutable.ListBuffer()
        var s_set : mutable.Set[Int] = mutable.Set()
        var index : mutable.Map[Int,Int] =  mutable.Map()
        var lowlink : mutable.Map[Int,Int]=  mutable.Map()
        var ret : mutable.Map[Int,mutable.ListBuffer[Int]]= mutable.Map()

        def visit(v: Int):Int = {
                 index(v) = index.size
               lowlink(v) = index(v)
               var zz :List[Int]= gg.get(v).toList(0)
                            for( w <- zz) {
                  if( !(index.contains(w)) ){
                     visit(w)
                     lowlink(v) = List(lowlink(w),lowlink(v)).min
                   }else if(s_set.contains(w)){
                     lowlink(v)=List(lowlink(v),index(w)).min
                   }
               }

               if(lowlink(v)==index(v)){
                  var scc:mutable.ListBuffer[Int] = new mutable.ListBuffer()
                  var w:Int=null.asInstanceOf[Int]
                  while(v!=w){
                    w= s.last
                    scc+=w
                    s_set-=w
                  }
           ret+=scc
        }
        }

   for( v <- g) {if( !(index.contains(v)) ){visit(v)}}
   ret
}

I know this isn't the scala way at all (and not clean ...) but I'm planning to slowly change it to a more functional style when I get the first version working.

For now, I got this error :

type mismatch;  found   : Unit  required: Int

at this line

if(lowlink(v)==index(v)){

I think it's coming from this line but I'm not sure :

if( !(index.contains(w))

But it's really hard to debug it since I can't just println my mistakes ...

Thanks !

Body:
I know this post is old, but I have lately been working with the implementation of Tarjans algorithm in Scala. In the implementation of the code, I was looking at this post and it occurred to me, that it could be done in a simpler way:

case class Edge[A](from: A, to: Set[A])

class TarjanGraph[A](src: Iterable[Edge[A]]) {
  lazy val trajan: mutable.Buffer[mutable.Buffer[A]] = {
    var s = mutable.Buffer.empty[A] //Stack to keep track of nodes reachable from current node
    val index = mutable.Map.empty[A, Int] //index of each node
    val lowLink = mutable.Map.empty[A, Int] //The smallest index reachable from the node
    val ret = mutable.Buffer.empty[mutable.Buffer[A]] //Keep track of SCC in graph
def visit(v: A): Unit = {
  //Set index and lowlink of node on first visit
  index(v) = index.size
  lowLink(v) = index(v)
  //Add to stack
  s += v
  if (src.exists(_.from == v)) {
    for (w <- src.find(e => e.from == v).head.to) {
      if (!index.contains(w)) { //Node is not explored yet
        //Perform DFS from node W
        visit(w)
        //Update the lowlink value of v so it has the value of the lowest node reachable from itself and from node w
        lowLink(v) = math.min(lowLink(w), lowLink(v))
      } else if (s.contains(w)) {
        // Node w is on the stack meaning - it means there is a path from w to v
        // and since node w is a neighbor to node v there is also a path from v to w
        lowLink(v) = math.min(lowLink(v), index(w))
      }
    }
  }
  //The lowlink value haven't been updated meaning it is the root of a cycle/SCC
  if (lowLink(v) == index(v)) {
    //Add the elements to the cycle that has been added to the stack and whose lowlink has been updated by node v's lowlink
    //This is the elements on the stack that is placed behind v
    val n = s.length - s.indexOf(v)
    ret += s.takeRight(n)
    //Remove these elements from the stack
    s.dropRightInPlace(n)
  }
}

//Perform a DFS from  all no nodes that hasn't been explored
src.foreach(v => if (!index.contains(v.from)) visit(v.from))
ret
  }

  // A cycle exist if there is a SCC with at least two components
  lazy val hasCycle: Boolean = trajan.exists(_.size >= 2)
  lazy val trajanCycle: Iterable[Seq[A]] = trajan.filter(_.size >= 2).distinct.map(_.toSeq).toSeq
  lazy val topologicalSortedEdges: Seq[Edge[A]] =
    if (hasCycle) Seq[Edge[A]]()
    else trajan.flatten.reverse.flatMap(x => src.find(_.from == x)).toSeq
}


问:
Finding user information in different databases and tables in SQL Server
I have a lot of different databases and tables that contain user information. I would like to write a query, that would find all the necessary information. So when I use "where" clause (e.g. where Email = 'Example@example.com', or where Name = 'Mister Holmes' etc), it should bring up the results I'm looking for and search from all the related databases and tables.

My idea is to make a new view, bring all the related tables in there, and then join the necessary columns somehow. Is that possible?

Can anyone please help?

答:
I had the same problem. I just describe my way - Because I have many different databases with different storaged infos about users, I collect all of them with INSERT and every time I am looking for WHERE SOMETHING, I am running this:

truncate target table (which is already prepared with necessary colls like NAME, LOGIN, RIGHTS, APPS, NOTES, ...)

filling target table with data from VIEWs, which are specific for each db / apps / or user groups

This two points I stored in procedure. Maybe it is not quickest way, but searching and filtering above one static table is much more safe and less consuming then searching in twenty views.
But, be aware, I you are not alone DBA and you have collegues which are playing the role of administrating sql in your area, I think, this solution is not lucky.

Or do you have standard user informations in server_principals, server_role_members, database_principals, database_permissions, schemas, ... ?


问:
Why do I need an intermediate global to get CUDA device-side function addresses?
I've been pondering the answers to this question:

How to pass device function as an input argument to host-side function?

and especially Robert Crovella's answer. I don't quite understand why the intermediate global symbol is necessary. That is, why does this work:

```<code>#include <stdio.h>

__device__ int f1(){ printf("dev f1\n"); return 0;}

__device__ void *fptrf1 = (void*) f1;

__global__ void mykernel(int (*fptr)()) {
  fptr();
  printf("executed\n");
}

int main() {
  void *hf1;
  cudaMemcpyFromSymbol(&hf1, fptrf1, sizeof(int *));
  mykernel<<<1,1>>>((int (*)())hf1);
  cudaDeviceSynchronize();
}
</code>```

but this doesn't work:

```<code>#include <stdio.h>

__device__ int f1(){ printf("dev f1\n"); return 0;}

__global__ void mykernel(int (*fptr)()) {
  fptr();
  printf("executed\n");
}

int main() {
  void *hf1;
  cudaMemcpyFromSymbol(&hf1, f1, sizeof(int *));
  mykernel<<<1,1>>>((int (*)())hf1);
  cudaDeviceSynchronize();
}
</code>```

? I mean, isn't a function a symbol? And if the global pointer's device-side address can be "known" to my host-side code, why can't the function itself?
 And if it doesn't work - why does it compile and not complain?

答:
I mean, isn't a function a symbol?

No, it isn't.

I have no special insight here, but no doubt that part of the reason for this is historical: when the CUDA APIs were invented, __device__ functions were merely a programming aid. There was no ABI, no function pointer support, and all device functions were inline expanded by the compiler. The only static device symbols which were emitted were __global__ functions, texture references, and __device__ variables. So there was absolutely no way that sort of usage was envisaged, or possible, when the language and APIs were put together 15 years ago.

Even with today's post ABI and post ELF format device toolchain (originally everything was plain text with embedded strings), you won't find __device__ functions exposed by the device object file ELF interface. It is not possible to retrieve an arbitrary __device__ function via any of the host APIs, unlike __global__ functions and other device symbols.

And if the global pointer's device-side address can be "known" to my host-side code, why can't the function itself?

See above. The APIs have never exposed this.

And if it doesn't work - why does it compile and not complain?

Because of the compilation trajectory. The CUDA front end does this to your __device__ function in host code (and there is no discrimination here, it does it to every __device__ function, including the internal toolchain functions and device libraries):

```<code># 3 "unobtainium.cu"
__attribute__((unused)) int f1() {int volatile ___ = 1;::exit(___);}
#if 0
# 3
{ printf("dev f1\n"); return 0; }
#endif
</code>```

i.e. it creates a dummy host stub so that everything compiles. Kernels and device symbols also get stubs, but with different boilerplate. Those boilerplate stubs match up with the tags which the internal runtime functions use to make the host side runtime API work. But device functions don't, because they are not exposed by the CUDA device code APIs.

And finally your original question:

Why does this work:

```<code>#include <stdio.h>

__device__ int f1(){ printf("dev f1\n"); return 0;}

__device__ void *fptrf1 = (void*) f1;

__global__ void mykernel(int (*fptr)()) {
  fptr();
  printf("executed\n");
}

int main() {
  void *hf1;
  cudaMemcpyFromSymbol(&hf1, fptrf1, sizeof(int *));
  mykernel<<<1,1>>>((int (*)())hf1);
  cudaDeviceSynchronize();
}
</code>```

The interesting thing here is that it didn't always work. Once upon a time you would have had to run a setup kernel to initialize the device side function pointer. Somewhere around  CUDA 5 it started working this way. Why is relatively straightforward -- a compilation unit scope __device__ variable is a valid device symbol, so exposed by the host APIs, and the device side linker can (now) statically assign the correct value during linkage so that when the runtime initializes, the value is correct. But note that it is static assignment, no anything which happens at runtime.

Body:
I've been pondering the answers to this question:

How to pass device function as an input argument to host-side function?

and especially Robert Crovella's answer. I don't quite understand why the intermediate global symbol is necessary. That is, why does this work:

#include <stdio.h>

__device__ int f1(){ printf("dev f1\n"); return 0;}

__device__ void *fptrf1 = (void*) f1;

__global__ void mykernel(int (*fptr)()) {
  fptr();
  printf("executed\n");
}

int main() {
  void *hf1;
  cudaMemcpyFromSymbol(&hf1, fptrf1, sizeof(int *));
  mykernel<<<1,1>>>((int (*)())hf1);
  cudaDeviceSynchronize();
}

but this doesn't work:

#include <stdio.h>

__device__ int f1(){ printf("dev f1\n"); return 0;}

__global__ void mykernel(int (*fptr)()) {
  fptr();
  printf("executed\n");
}

int main() {
  void *hf1;
  cudaMemcpyFromSymbol(&hf1, f1, sizeof(int *));
  mykernel<<<1,1>>>((int (*)())hf1);
  cudaDeviceSynchronize();
}

? I mean, isn't a function a symbol? And if the global pointer's device-side address can be "known" to my host-side code, why can't the function itself?
 And if it doesn't work - why does it compile and not complain?

Body:
I mean, isn't a function a symbol?

No, it isn't.

I have no special insight here, but no doubt that part of the reason for this is historical: when the CUDA APIs were invented, __device__ functions were merely a programming aid. There was no ABI, no function pointer support, and all device functions were inline expanded by the compiler. The only static device symbols which were emitted were __global__ functions, texture references, and __device__ variables. So there was absolutely no way that sort of usage was envisaged, or possible, when the language and APIs were put together 15 years ago.

Even with today's post ABI and post ELF format device toolchain (originally everything was plain text with embedded strings), you won't find __device__ functions exposed by the device object file ELF interface. It is not possible to retrieve an arbitrary __device__ function via any of the host APIs, unlike __global__ functions and other device symbols.

And if the global pointer's device-side address can be "known" to my host-side code, why can't the function itself?

See above. The APIs have never exposed this.

And if it doesn't work - why does it compile and not complain?

Because of the compilation trajectory. The CUDA front end does this to your __device__ function in host code (and there is no discrimination here, it does it to every __device__ function, including the internal toolchain functions and device libraries):

# 3 "unobtainium.cu"
__attribute__((unused)) int f1() {int volatile ___ = 1;::exit(___);}
#if 0
# 3
{ printf("dev f1\n"); return 0; }
#endif

i.e. it creates a dummy host stub so that everything compiles. Kernels and device symbols also get stubs, but with different boilerplate. Those boilerplate stubs match up with the tags which the internal runtime functions use to make the host side runtime API work. But device functions don't, because they are not exposed by the CUDA device code APIs.

And finally your original question:

Why does this work:

#include <stdio.h>

__device__ int f1(){ printf("dev f1\n"); return 0;}

__device__ void *fptrf1 = (void*) f1;

__global__ void mykernel(int (*fptr)()) {
  fptr();
  printf("executed\n");
}

int main() {
  void *hf1;
  cudaMemcpyFromSymbol(&hf1, fptrf1, sizeof(int *));
  mykernel<<<1,1>>>((int (*)())hf1);
  cudaDeviceSynchronize();
}

The interesting thing here is that it didn't always work. Once upon a time you would have had to run a setup kernel to initialize the device side function pointer. Somewhere around  CUDA 5 it started working this way. Why is relatively straightforward -- a compilation unit scope __device__ variable is a valid device symbol, so exposed by the host APIs, and the device side linker can (now) statically assign the correct value during linkage so that when the runtime initializes, the value is correct. But note that it is static assignment, no anything which happens at runtime.


问:
Javascript array search filter
I have the scenario, with provided example JSON data:

```<code>[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]
</code>```

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

```<code>filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});
</code>```

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

答:
```<code>ageFilters = ['23-26','>27']
selectedFilter = '23-26';

filteredPersons = this.state.persons.filter(({age}) => {
 const _age = parseInt(age);
 if(selectedFilter === '23-26') {             // "23-26"
  return (_age>=23) && (_age<=26);
 } else if(selectedFilter === '>27') {                          // "27"
  return (_age>27);
 } else {
  return true;
 }
})
</code>```

Title: Javascript array search filter

Body:
I have the scenario, with provided example JSON data:

[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.


问:
I want to stop click event
<input type="button" (click)="test()" testButton>

```<code>test() {
    console.log('test()');
}
</code>```

```<code>@Directive({
    selector: '[testButton]'
})
export class TestButtonDirective {
    constructor(private el: ElementRef) {
    }

    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('clickkkkkkkkkkkkkk');
        event.stopPropagation();
        event.preventDefault();
        event.stopImmediatePropagation();
    }
}
</code>```

▼ Current Result

clickkkkkkkkkkkkkk

test()

▼ Desired Result

clickkkkkkkkkkkkkk

event.stopPropagation();

event.preventDefault();

event.stopImmediatePropagation();

is not working

What Should I Do?

I want to control many button events at once.

答:
I think it's pretty straight forward. Just remove your click event listener (click)="test()"

```<code><input type="button" testButton>
</code>```

Other than that, if you want to handle the click events anywhere in the application before they are handled by Angular, you can add a click event listener to the window and specify that the event will be processed in the capture phase. In the following code snippet, addEventListener("click", fn, useCapture) is called with useCapture set to true (see the MDN documentation).

```<code>window.addEventListener("click", () => {
  console.log("Global click handler");
}, true);
</code>```

Title: I want to stop click event

Body:
<input type="button" (click)="test()" testButton>

test() {
    console.log('test()');
}

@Directive({
    selector: '[testButton]'
})
export class TestButtonDirective {
    constructor(private el: ElementRef) {
    }

    @HostListener('click', ['$event'])
    onClick(event: Event) {
        console.log('clickkkkkkkkkkkkkk');
        event.stopPropagation();
        event.preventDefault();
        event.stopImmediatePropagation();
    }
}

▼ Current Result

clickkkkkkkkkkkkkk

test()

▼ Desired Result

clickkkkkkkkkkkkkk

event.stopPropagation();

event.preventDefault();

event.stopImmediatePropagation();

is not working

What Should I Do?

I want to control many button events at once.

Body:
I think it's pretty straight forward. Just remove your click event listener (click)="test()"

<input type="button" testButton>

Other than that, if you want to handle the click events anywhere in the application before they are handled by Angular, you can add a click event listener to the window and specify that the event will be processed in the capture phase. In the following code snippet, addEventListener("click", fn, useCapture) is called with useCapture set to true (see the MDN documentation).

window.addEventListener("click", () => {
  console.log("Global click handler");
}, true);


问:
Displaying DateTime in Xamarin.Forms with SQLite
I am creating a Xamarin.Forms application for a school project. This project displays a list of school terms (6-month blocks of time) with the start and end dates. The list of the terms displays without issues, but the dates do not appear as expected: all dates are 01/01/0001. The terms table is:

```<code>    Id          TermName    StartDate   EndDate
----------  ----------  ----------  ----------
1           Term 1      2020-01-01  2020-06-30
2           Term 2      2020-07-01  2020-12-31
3           Term 3      2021-01-01  2021-06-30
4           Term 4      2021-07-01  2021-12-31
5           Term 5      2022-01-01  2022-06-30
6           Term 6      2022-07-01  2022-12-31
</code>```

Since SQLite doesn't have a specific DATETIME data type, I'm storing the StartDate and EndDate as a TEXT data type, but the terms.cs model file uses the DateTime datatype. Placing a breakpoint at the loading of the list of terms shows:
Breakpoint data.

Terms.cs file:

```<code>[Table("Terms")]
    public class Terms
    {
        public int Term { get; set; }
        public string TermName { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }
</code>```

MainPage.xaml.cs file:

```<code>protected override void OnAppearing()
        {
            base.OnAppearing();
            using (SQLiteConnection conn = new SQLiteConnection(App.DBLocation))
            {
                conn.CreateTable<Terms>();
                var terms = conn.Table<Terms>().ToList();
                TermsListView.ItemsSource = terms;
                TermsListView.SelectedItem = null;
            }
        }
</code>```

How do I get the StartDate and EndDate from my table to show up in my ListView correctly?

答:
Because you store it as a string the value cannot be assigned to the DateTime properties (no automatic conversion). So they keep their default date.
Change the properties to:

```<code> public class Terms
    {
        public int Term { get; set; }
        public string TermName { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
    }
</code>```

Then display these properties or convert the value to a real DateTime type:

```<code>public class Terms
        {
            public int Term { get; set; }
            public string TermName { get; set; }
            public string StartDate { get; set; }
            public string EndDate { get; set; }
            public DateTime RealStartDate => DateTime.Parse(StartDate);
            public DateTime RealEndDate => DateTime.Parse(EndDate);
        }
</code>```

The Parse method is not tested by me but you can look up the correct syntax if the result is not what you need.

In you View you should then use the  RealStartDate and RealEndDate properties

Body:
I am creating a Xamarin.Forms application for a school project. This project displays a list of school terms (6-month blocks of time) with the start and end dates. The list of the terms displays without issues, but the dates do not appear as expected: all dates are 01/01/0001. The terms table is:

    Id          TermName    StartDate   EndDate
----------  ----------  ----------  ----------
1           Term 1      2020-01-01  2020-06-30
2           Term 2      2020-07-01  2020-12-31
3           Term 3      2021-01-01  2021-06-30
4           Term 4      2021-07-01  2021-12-31
5           Term 5      2022-01-01  2022-06-30
6           Term 6      2022-07-01  2022-12-31

Since SQLite doesn't have a specific DATETIME data type, I'm storing the StartDate and EndDate as a TEXT data type, but the terms.cs model file uses the DateTime datatype. Placing a breakpoint at the loading of the list of terms shows:
Breakpoint data.

Terms.cs file:

[Table("Terms")]
    public class Terms
    {
        public int Term { get; set; }
        public string TermName { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
    }

MainPage.xaml.cs file:

protected override void OnAppearing()
        {
            base.OnAppearing();
            using (SQLiteConnection conn = new SQLiteConnection(App.DBLocation))
            {
                conn.CreateTable<Terms>();
                var terms = conn.Table<Terms>().ToList();
                TermsListView.ItemsSource = terms;
                TermsListView.SelectedItem = null;
            }
        }

How do I get the StartDate and EndDate from my table to show up in my ListView correctly?

Body:
Because you store it as a string the value cannot be assigned to the DateTime properties (no automatic conversion). So they keep their default date.
Change the properties to:

 public class Terms
    {
        public int Term { get; set; }
        public string TermName { get; set; }
        public string StartDate { get; set; }
        public string EndDate { get; set; }
    }

Then display these properties or convert the value to a real DateTime type:

public class Terms
        {
            public int Term { get; set; }
            public string TermName { get; set; }
            public string StartDate { get; set; }
            public string EndDate { get; set; }
            public DateTime RealStartDate => DateTime.Parse(StartDate);
            public DateTime RealEndDate => DateTime.Parse(EndDate);
        }

The Parse method is not tested by me but you can look up the correct syntax if the result is not what you need.

In you View you should then use the  RealStartDate and RealEndDate properties


问:
Trying to convert a string/char to an integer yielded an unexpected result
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?</p>

```<code>using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}
</code>```

答: binary[0] is '1', which has an ASCII value of 49.

Body:
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?

using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}


问:
Pass function as template argument to a class
I want to pass functions as template arguments but somehow I can't get it to work. I've written a lot of template classes in the past but only using "normal" types as arguments. I've already searched for that issue but nothing seems to fit here. So I'm stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

```<code>MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);
</code>```

Maybe also using typedefs:

```<code>typedef MyType<int> MyIntType;
</code>```

What I did so far:

```<code>template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);
</code>```

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don't set any default functions but I couldn't get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing "normal" types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

答:
GetFunction<T> and SetFunction<T> is a functor so you need an instance of it to call its call operator.

Could you replace these parts

```<code>  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function{ /*Functor constructed*/ }(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function{ /*Functor constructed*/ }(someArgs, &_value) == E_Success;
  }

  if(T_get_function{ /*Functor constructed*/ }(someArgs, &_value) == E_Fail)
  {
    throw someting;
  }
</code>```

as @Swift-FridayPie said, you also need to re-arrange template parameters part.

Body:
I want to pass functions as template arguments but somehow I can't get it to work. I've written a lot of template classes in the past but only using "normal" types as arguments. I've already searched for that issue but nothing seems to fit here. So I'm stuck.

Here is what I want to achieve:
I have a couple of type specific library functions which I want to encapsulate. I know that there are other ways of doing it as well (e.g. inheritance) but since I also want to learn a little bit here, I want to get it done with the template approach.

What I want to achieve:

MyType<int> myIntObject(...);
...
int writeVal = 10;
myIntObject.Write(writeVal);
...
int readVal;
myIntObject.Read(&readVal);

Maybe also using typedefs:

typedef MyType<int> MyIntType;

What I did so far:

template<typename T>
struct SetFunction
{
  inline ret_code operator()(someArgs, T value) const {return E_Fail;}
}

template<typename T>
struct GetFunction
{
  inline ret_code operator()(someArgs, T& value) const {return E_Fail;}
}

//template specialization:
template<>
struct SetFunction<int>
{
  inline ret_code operator()(someArgs, T value) const
  {
    //some other code
    return libraryFunctionWriteInt(someArgs, value);
  }
}

template<>
struct GetFunction<int>
{
  inline ret_code operator()(someArgs, T& value) const
  {
    //some other code
    return libraryFunctionReadInt(someArgs, &value);
  }
}
//do the specialization for all other types as well

template<class T, typename T_get_function = GetFunction<T>(), typename T_set_function = SetFunction<T>()>
MyType
{
public:
  MyType(someArgs)
  {
    if(T_get_function(someArgs, &_value) == E_Fail)
    {
      throw someting;
    }
  }

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function(someArgs, &_value) == E_Success;
  }

private:
  T _value;
}

//and then eventually using it (maybe using some typedefs as well)
MyType<int> myIntObject(someArgs);
...
int writeVal = 10;
myIntObject.SetValue(writeValue);
...
int readVal;
myIntObject.GetValue(&readValue);

Now I get compile errors: expression list treated as compound expression in functional cast on those two lines where I call the T_set_function / T_get_function. I also tried passing the library functions directly as template arguments and don't set any default functions but I couldn't get it to work that way as well.

Almost all of the books, articles and examples I read so far are only dealing with passing "normal" types as template arguments but since stl makes use of passing functions as well I really want to know how to do this.

Body:
GetFunction<T> and SetFunction<T> is a functor so you need an instance of it to call its call operator.

Could you replace these parts

  bool SetValue(T value)
  {
    _value = value;
    //maybe some other code
    return T_set_function{ /*Functor constructed*/ }(someArgs, _value) == E_Success;
  }

  bool GetValue(T &value)
  {
    //maybe some other code
    return T_get_function{ /*Functor constructed*/ }(someArgs, &_value) == E_Success;
  }

  if(T_get_function{ /*Functor constructed*/ }(someArgs, &_value) == E_Fail)
  {
    throw someting;
  }

as @Swift-FridayPie said, you also need to re-arrange template parameters part.


答:
You are missing $event:

```<code><input type="button" (click)="test($event)">

test(event): void {
  event.stopPropagation();
}
</code>```

Or just remove (click)="test()" from button

Title: I want to stop click event

Body:
You are missing $event:

<input type="button" (click)="test($event)">

test(event): void {
  event.stopPropagation();
}

Or just remove (click)="test()" from button


问:
How to fail a python unittest if the setUpClass throws exception
I am having little trouble using the python setUpClass.

For example consider the following case

```<code>class MyTest(unittest.case.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Test setup"
        try:
            1/0
        except:
            raise

    @classmethod
    def tearDownClass(cls):
        print "Test teardown"
</code>```

A couple of questions

Is the above code the right way to handle test setUpClass exceptions (by raising it so that the python unittest can take care of it), there are fail(), skip() methods, but those can only be used by test instances and not the test classes.

When there is a setUpClass exception, how can we ensure that tearDownClass runs (unittest doesn't run it, should we manualy call it).

答: use tearDownModule. It should be called after setUpClass runs.</p>

Body:
I am having little trouble using the python setUpClass.

For example consider the following case

class MyTest(unittest.case.TestCase):

    @classmethod
    def setUpClass(cls):
        print "Test setup"
        try:
            1/0
        except:
            raise

    @classmethod
    def tearDownClass(cls):
        print "Test teardown"

A couple of questions

Is the above code the right way to handle test setUpClass exceptions (by raising it so that the python unittest can take care of it), there are fail(), skip() methods, but those can only be used by test instances and not the test classes.

When there is a setUpClass exception, how can we ensure that tearDownClass runs (unittest doesn't run it, should we manualy call it).


问:
How do I discover which messages a delegate can / should implement?
In Objective-C / Cocoa how do I discover the messages I can implement in a delegate class?

From what I have read in the documentation a class will only allow certain chosen messages to be handled via a delegate but so far have found difficulty finding a list of messages for a class.

To ask the question another way, if I created a delegate for NSApplication, which messages are available for me to handle?

The documentation for NSApplication states a delegate

responds to certain messages on behalf of NSApp.

The documentation then goes onto say

NSApplication defines over twenty delegate methods that offer opportunities for modifying specific aspects of application behavior.

but as far as I can see it fails to list these methods / messages so how do I know which ones will be called from my delegate?

答:
One quick note that is that it is useful to understand the difference between formal and informal protocols. Also formal protocols have optional methods, which needn't be called.
When you write your own protocol you will want to check -respondsToSelector: before sending optional/informal methods.

formal protocols are defined like...

```<code>@protocol SomeProtocol <NSObject>
-(void)someMethod:(id)sender;
-(void)someOtherMethod:(NSString*)aString;
@property(nonatomic,retain) someProperty;

@optional
-(BOOL)someOptionalMethod;

@end
</code>```

and are adopted like...

```<code>@interface SomeClass : NSObject <SomeProtocol> {

}
@end
</code>```

this tells the compiler that you are adopting SomeProtocol, and you wont be required to declare you methods for the protocol in the .h file, it also tell the compiler to warn you if you haven't implemented all of the required methods.

for informal protocols you don't adopt them syntactically, but you will need to declare your methods in the .h file.

Body:
One quick note that is that it is useful to understand the difference between formal and informal protocols. Also formal protocols have optional methods, which needn't be called.
When you write your own protocol you will want to check -respondsToSelector: before sending optional/informal methods.

formal protocols are defined like...

@protocol SomeProtocol <NSObject>
-(void)someMethod:(id)sender;
-(void)someOtherMethod:(NSString*)aString;
@property(nonatomic,retain) someProperty;

@optional
-(BOOL)someOptionalMethod;

@end

and are adopted like...

@interface SomeClass : NSObject <SomeProtocol> {

}
@end

this tells the compiler that you are adopting SomeProtocol, and you wont be required to declare you methods for the protocol in the .h file, it also tell the compiler to warn you if you haven't implemented all of the required methods.

for informal protocols you don't adopt them syntactically, but you will need to declare your methods in the .h file.


问:
How do I import data from Google Analysis into a local database and how much data the free version of Google Analysis can hold?
Questions about Google Analysis:
How do I import data from Google Analysis into a local database?
How much data does the free version of Google Analysis hold?</p>

答:
Regarding question one: There's an API (via this and especially this answers)

Regarding question two: You'll find information about the limitations here.


问:
Function doesn't return right array's values
I've started learning functions in C.

I have a task to convert numbers from imperial to metric, which are contained in the 2d Array.

Array:

```<code>{1300, 0}  [0][0] [0][1]

{2198, 0}  [1][0] [1][1]

{4199, 1}  [2][0] [2][1]

{2103, 0}  [3][0] [3][1]

{3104, 1}  [4][0] [4][1]

{1093, 1}  [5][0] [5][1]

{3204, 0}  [6][0] [6][1]
</code>```

So I am calling function with double return SortedArray[DATA_ROWS] = find_function(MixedData);

find_function logic:

0 is an indicator of the metric system  value and 1 is an indicator of imperial system value,
i is a row indexer and j is a column indexer.

So when for cycles find out that column value is 0 or 1 they save [j-1](an actual value that we need) into SortedArray.

It also converts value if finds out that column value is 1 SortedArray[i] = MixedData[i][j-1]*CONSTANT;

Just for a check, I did printf to see if values are correct and correctly converted if needed.
I got this output:

```<code>1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00
</code>```

So, seems like correct, but in Task I have another task - use 2 functions to solve this task.
I've decided to make another function, which will sum all values in SortedArray[DATA_ROWS] and then calculate avg - average.
Then print them out.
And here comes the problem.

Calling function with no return total_AVG(SortedArray); with copied array SortedArray[DATA_ROWS]

Just to check made a printf and got this:

```<code>-1.#R
0.00
0.00
0.00
0.00
0.00
0.00
</code>```

It seems like my SortedArray[DATA_ROWS] did not copy into the second function total_AVG

Pointers are coming in the next task, so according to task's timeline I can't use them
*
(and even if I could, I have no idea how to use them still)*

Can you please tell me, what I am doing wrong.

NB:
Some comments and variables, which are not used just old ones, when I tried to correct my code.
And also I only need to understand why SortedArray[DATA_ROWS] did not copy into second function total_AVG. All further logic will be corrected after solving this problem.

Thank you! And sorry for broken English!

CODE:

```<code>#include <stdio.h>
#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function(int MixedData[DATA_ROWS][DATA_COLS]);
void total_AVG(double SortedArray[DATA_ROWS]);

int main(void)
{
    int i;
    double SortedArray[DATA_ROWS];

    int MixedData[DATA_ROWS][DATA_COLS] = {
        {1300, 0},//[0][0] [0][1]
        {2198, 0},//[1][0] [1][1]
        {4199, 1},//[2][0] [2][1]
        {2103, 0},//[3][0] [3][1]
        {3104, 1},//[4][0] [4][1]
        {1093, 1},//[5][0] [5][1]
        {3204, 0}};//[6][0] [6][1]

    SortedArray[DATA_ROWS] = find_function(MixedData);
    total_AVG(SortedArray);

    return 0;
}

double find_function(int MixedData[DATA_ROWS][DATA_COLS])
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j; // indexers
    double SortedArray[DATA_ROWS];

    // 7 rows, each row suppose to contain only metric values
    // That means, if second for cycle with j indexer finds 0, it will contain j-1 value for example 1300 in SortedArray
    // If it finds in second for cycle with j indexer 1, it will converte the value from imperial to metric for example 4199*0.31
        /*  {1300, 0}  [0][0] [0][1]
            {2198, 0}  [1][0] [1][1]
            {4199, 1}  [2][0] [2][1]
            {2103, 0}  [3][0] [3][1]
            {3104, 1}  [4][0] [4][1]
            {1093, 1}  [5][0] [5][1]
            {3204, 0}  [6][0] [6][1] */

    // Probably problem in "double SortedArray and int MixedData"
    for(i=0;i<DATA_ROWS;i++)
    {
        for(j=0;j<DATA_COLS;j++)
        {
            if(MixedData[i][j]==0)
            {
                SortedArray[i] = MixedData[i][j-1];
            }
            else if(MixedData[i][j]==1)
            {
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

            }
        }
    }
    for(i=0;i<DATA_ROWS;i++)
    {
        //total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return SortedArray[DATA_ROWS];
}

void total_AVG(double SortedArray[DATA_ROWS])
{
    double avg,total;
    int i;

    for(i=0;i<DATA_ROWS;i++)
    {
        printf("%.2lf\n", SortedArray[i]);
    }
    //avg = total/DATA_ROWS;
    //printf("Total by every worker: %.2lf\n",total);
    //printf("In average by every worker: %.2lf", avg);

    return;
}

</code>```

答:
You cant use arrays like this

```<code>return SortedArray[DATA_ROWS];
SortedArray[DATA_ROWS] = find_function(MixedData);
</code>```

You can pass it as parameter to function. like below.

```<code>find_function(MixedData, SortedArray);

void find_function(int MixedData[DATA_ROWS][DATA_COLS], double SortedArray[DATA_ROWS])
{
// Dont define, use itt from parameter
// double SortedArray[DATA_ROWS];

// ...

// Dont need to return.
// return SortedArray[DATA_ROWS];
}
</code>```

Body:
I've started learning functions in C.

I have a task to convert numbers from imperial to metric, which are contained in the 2d Array.

Array:

{1300, 0}  [0][0] [0][1]

{2198, 0}  [1][0] [1][1]

{4199, 1}  [2][0] [2][1]

{2103, 0}  [3][0] [3][1]

{3104, 1}  [4][0] [4][1]

{1093, 1}  [5][0] [5][1]

{3204, 0}  [6][0] [6][1]

So I am calling function with double return SortedArray[DATA_ROWS] = find_function(MixedData);

find_function logic:

0 is an indicator of the metric system  value and 1 is an indicator of imperial system value,
i is a row indexer and j is a column indexer.

So when for cycles find out that column value is 0 or 1 they save [j-1](an actual value that we need) into SortedArray.

It also converts value if finds out that column value is 1 SortedArray[i] = MixedData[i][j-1]*CONSTANT;

Just for a check, I did printf to see if values are correct and correctly converted if needed.
I got this output:

1300.00
2198.00
1301.69
2103.00
962.24
338.83
3204.00

So, seems like correct, but in Task I have another task - use 2 functions to solve this task.
I've decided to make another function, which will sum all values in SortedArray[DATA_ROWS] and then calculate avg - average.
Then print them out.
And here comes the problem.

Calling function with no return total_AVG(SortedArray); with copied array SortedArray[DATA_ROWS]

Just to check made a printf and got this:

-1.#R
0.00
0.00
0.00
0.00
0.00
0.00

It seems like my SortedArray[DATA_ROWS] did not copy into the second function total_AVG

Pointers are coming in the next task, so according to task's timeline I can't use them
*
(and even if I could, I have no idea how to use them still)*

Can you please tell me, what I am doing wrong.

NB:
Some comments and variables, which are not used just old ones, when I tried to correct my code.
And also I only need to understand why SortedArray[DATA_ROWS] did not copy into second function total_AVG. All further logic will be corrected after solving this problem.

Thank you! And sorry for broken English!

CODE:

#include <stdio.h>
#define DATA_ROWS 7
#define DATA_COLS 2
#define CONSTANT 0.31
#define MAX 3

double find_function(int MixedData[DATA_ROWS][DATA_COLS]);
void total_AVG(double SortedArray[DATA_ROWS]);

int main(void)
{
    int i;
    double SortedArray[DATA_ROWS];

    int MixedData[DATA_ROWS][DATA_COLS] = {
        {1300, 0},//[0][0] [0][1]
        {2198, 0},//[1][0] [1][1]
        {4199, 1},//[2][0] [2][1]
        {2103, 0},//[3][0] [3][1]
        {3104, 1},//[4][0] [4][1]
        {1093, 1},//[5][0] [5][1]
        {3204, 0}};//[6][0] [6][1]

    SortedArray[DATA_ROWS] = find_function(MixedData);
    total_AVG(SortedArray);

    return 0;
}

double find_function(int MixedData[DATA_ROWS][DATA_COLS])
{
    // imperial numbers from source array "mixedData" are 4199,3104,1093;

    int i,j; // indexers
    double SortedArray[DATA_ROWS];

    // 7 rows, each row suppose to contain only metric values
    // That means, if second for cycle with j indexer finds 0, it will contain j-1 value for example 1300 in SortedArray
    // If it finds in second for cycle with j indexer 1, it will converte the value from imperial to metric for example 4199*0.31
        /*  {1300, 0}  [0][0] [0][1]
            {2198, 0}  [1][0] [1][1]
            {4199, 1}  [2][0] [2][1]
            {2103, 0}  [3][0] [3][1]
            {3104, 1}  [4][0] [4][1]
            {1093, 1}  [5][0] [5][1]
            {3204, 0}  [6][0] [6][1] */

    // Probably problem in "double SortedArray and int MixedData"
    for(i=0;i<DATA_ROWS;i++)
    {
        for(j=0;j<DATA_COLS;j++)
        {
            if(MixedData[i][j]==0)
            {
                SortedArray[i] = MixedData[i][j-1];
            }
            else if(MixedData[i][j]==1)
            {
                SortedArray[i] = MixedData[i][j-1]*CONSTANT;

            }
        }
    }
    for(i=0;i<DATA_ROWS;i++)
    {
        //total += SortedArray[i];
        printf("%.2lf\n", SortedArray[i]);
    }

    return SortedArray[DATA_ROWS];
}

void total_AVG(double SortedArray[DATA_ROWS])
{
    double avg,total;
    int i;

    for(i=0;i<DATA_ROWS;i++)
    {
        printf("%.2lf\n", SortedArray[i]);
    }
    //avg = total/DATA_ROWS;
    //printf("Total by every worker: %.2lf\n",total);
    //printf("In average by every worker: %.2lf", avg);

    return;
}

Body:
You cant use arrays like this

return SortedArray[DATA_ROWS];
SortedArray[DATA_ROWS] = find_function(MixedData);

You can pass it as parameter to function. like below.

find_function(MixedData, SortedArray);

void find_function(int MixedData[DATA_ROWS][DATA_COLS], double SortedArray[DATA_ROWS])
{
// Dont define, use itt from parameter
// double SortedArray[DATA_ROWS];

// ...

// Dont need to return.
// return SortedArray[DATA_ROWS];
}


问:
prestashop - show js notification in front controller
I override CartController in my custom module. But i have problem with notification, this is my code:

```<code><?php

    use PrestaShop\PrestaShop\Adapter\Presenter\Cart\CartPresenter;

    class CartController extends CartControllerCore
    {
        public $php_self = 'cart';

        public function init()
        {
            parent::init();
            $this->qty = abs(Tools::getValue('qty', 1));
            var_dump(1);

            if ($this->qty >= 2) {
                #How can i show notification?
            }
        }

    }
</code>```

if i say problem i mean, how can i show for example js message or modal dialog when $this->qty >= 2 ?

Screen from front page, i see error i network, but i don't see notification on page

答:
You can look into how the core cart controller shows notifications:

It should be enough to use $this->errors[] to make some error message.

```<code>            $this->errors[] = $this->trans(
                'Add your message her with possible variables like this: %product% and %quantity%.',
                array('%product%' => $product->name, '%quantity%' => $product->minimal_quantity),
                'Shop.Notifications.Error'
            );
</code>```

Also look at FrontController other similar arrays to set notifications:

```<code>/** @var array Controller errors */
public $errors = array();

/** @var array Controller warning notifications */
public $warning = array();

/** @var array Controller success notifications */
public $success = array();

/** @var array Controller info notifications */
public $info = array();
</code>```

Body:
I override CartController in my custom module. But i have problem with notification, this is my code:

<?php

    use PrestaShop\PrestaShop\Adapter\Presenter\Cart\CartPresenter;

    class CartController extends CartControllerCore
    {
        public $php_self = 'cart';

        public function init()
        {
            parent::init();
            $this->qty = abs(Tools::getValue('qty', 1));
            var_dump(1);

            if ($this->qty >= 2) {
                #How can i show notification?
            }
        }

    }

if i say problem i mean, how can i show for example js message or modal dialog when $this->qty >= 2 ?

Screen from front page, i see error i network, but i don't see notification on page

Body:
You can look into how the core cart controller shows notifications:

It should be enough to use $this->errors[] to make some error message.

            $this->errors[] = $this->trans(
                'Add your message her with possible variables like this: %product% and %quantity%.',
                array('%product%' => $product->name, '%quantity%' => $product->minimal_quantity),
                'Shop.Notifications.Error'
            );

Also look at FrontController other similar arrays to set notifications:

/** @var array Controller errors */
public $errors = array();

/** @var array Controller warning notifications */
public $warning = array();

/** @var array Controller success notifications */
public $success = array();

/** @var array Controller info notifications */
public $info = array();


问:
Distance Among Guide Lines in Figma?
so I am using Figma for now because Adobe XD will no more free. I am curious if there is a configuration to show distance among guide lines in Figma like Adobe XD has?

Above is the illustration. Thanks in advance

答:
You can Press Alt and hover over any element with your mouse.
Works in both XD and Figma.

Title: Distance Among Guide Lines in Figma?


问:
Dropdown click background
I want to remove click color

I want to remove click color (is not a hover) in a bootstrap dropdown but i dont know how to change that color, i tried with DevTools but i didnt find the solution, thank you

Acción #1

Acción #4

```

答:
Add pseudo style to your button.

There are more pseudo events than hover you can check them here

```
<p>with the styles</p>
<pre class="lang-css prettyprint-override"><code>.customButton:link, .customButton:focus, .customButton:active, .customButton:visited{
  //whatever you want
}
</code>```

I've added a customButton class to the button, add whatever proprietry you need in the CSS

Title: Dropdown click background

Body:
Add pseudo style to your button.

There are more pseudo events than hover you can check them here

<a type="button" data-toggle="dropdown" class="customButton" data-placement="bottom">
   <span class="glyphicon glyphicon-alert"></span>
</a>

with the styles

.customButton:link, .customButton:focus, .customButton:active, .customButton:visited{
  //whatever you want
}

I've added a customButton class to the button, add whatever proprietry you need in the CSS


问:
Change the system display size programmatically Android N
Background: Android N comes with a feature to change system Display Size from settings, in addition to the previously present feature of changing Font Size.

Change Display Size:

Image Source: pcmag.com

Question:

If an app has android.permission.WRITE_SETTINGS permission to change the settings, there are ways to change the system font size programatically as mentioned in How to programmatically change font settings of Device: font style and font size?. However I couldn't find a way to change the display size programmatically. Is it possible?

What I've tried?

I've checked the possible options in the list of Settings.System convenience functions provided for changing settings programmatically.

Update:

I've opened a feature request for the same here: https://code.google.com/p/android/issues/detail?id=214124 . If you feel it would be useful please star it.

答:
Just share my approach to tackle this requirement. I achieve this function by using the dirty Java reflection method - although it's not that elegant.

The main reference source code files are:

ScreenZoomSettings.java (https://github.com/aosp-mirror/platform_packages_apps_settings/blob/master/src/com/android/settings/display/ScreenZoomSettings.java)

DisplayDensityUtils.java (http://androidxref.com/9.0.0_r3/xref/frameworks/base/packages/SettingsLib/src/com/android/settingslib/display/DisplayDensityUtils.java)

WindowManagerGlobal.java (http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/view/WindowManagerGlobal.java)

And, follow the below steps, then you can get the required control:

Read ZoomScreenSettings.java's onCreate() and commit(). They demonstrate how to correctly get and set the density value into the framework.

Read DisplayDensityUtils.java. It shows how to use WindowManagerService to control the system density. Because we can't get the instance of DisplayDensityUtils via reflection, we need to understand which WindowManagerService methods are utilized.

Use reflection to get WindowManagerService's instance, and write a  DisplayDensityUtils-like class into your project.

```<code>// Where wm is short for window manager
val wmGlobalClz = Class.forName("android.view.WindowManagerGlobal")
val getWmServiceMethod = wmGlobalClz.getDeclaredMethod("getWindowManagerService")
val wmService = getWmServiceMethod.invoke(wmGlobalClz)

val wmInterfaceClz = Class.forName("android.view.IWindowManager")

// Now, we already have the ability to do many things we want.
// For instance, to get the default density value.
val getInitialDisplayDensityMethod = wmInterfaceClz.getDeclaredMethod(
        "getInitialDisplayDensity",
        Integer.TYPE
)
val defaultDensity = getInitialDisplayDensityMethod.invoke(
        wmService,
        Display.DEFAULT_DISPLAY
) as Int

</code>```

Set or get the density value with your DisplayDensityUtils-like class. One thing just to mention is that, if you want to pass an index value (e.g., 2 for large display size), please feed it to your DisplayDensityUtils-like class's mValues array to get the actual density value which is the right one to pass to the framework. Getting the current density index also applies the same concept.

Body:
Just share my approach to tackle this requirement. I achieve this function by using the dirty Java reflection method - although it's not that elegant.

The main reference source code files are:

ScreenZoomSettings.java (https://github.com/aosp-mirror/platform_packages_apps_settings/blob/master/src/com/android/settings/display/ScreenZoomSettings.java)

DisplayDensityUtils.java (http://androidxref.com/9.0.0_r3/xref/frameworks/base/packages/SettingsLib/src/com/android/settingslib/display/DisplayDensityUtils.java)

WindowManagerGlobal.java (http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/view/WindowManagerGlobal.java)

And, follow the below steps, then you can get the required control:

Read ZoomScreenSettings.java's onCreate() and commit(). They demonstrate how to correctly get and set the density value into the framework.

Read DisplayDensityUtils.java. It shows how to use WindowManagerService to control the system density. Because we can't get the instance of DisplayDensityUtils via reflection, we need to understand which WindowManagerService methods are utilized.

Use reflection to get WindowManagerService's instance, and write a  DisplayDensityUtils-like class into your project.

// Where wm is short for window manager
val wmGlobalClz = Class.forName("android.view.WindowManagerGlobal")
val getWmServiceMethod = wmGlobalClz.getDeclaredMethod("getWindowManagerService")
val wmService = getWmServiceMethod.invoke(wmGlobalClz)

val wmInterfaceClz = Class.forName("android.view.IWindowManager")

// Now, we already have the ability to do many things we want.
// For instance, to get the default density value.
val getInitialDisplayDensityMethod = wmInterfaceClz.getDeclaredMethod(
        "getInitialDisplayDensity",
        Integer.TYPE
)
val defaultDensity = getInitialDisplayDensityMethod.invoke(
        wmService,
        Display.DEFAULT_DISPLAY
) as Int

Set or get the density value with your DisplayDensityUtils-like class. One thing just to mention is that, if you want to pass an index value (e.g., 2 for large display size), please feed it to your DisplayDensityUtils-like class's mValues array to get the actual density value which is the right one to pass to the framework. Getting the current density index also applies the same concept.


问:
Is there any C++ function to sort a Map?
I want to know that how can I sort an ordered_map in C++ on the basis of values. Is there any function to do it?

答:
You can not really change the elements of a std::map. However, you can use std::vector to first copy the elements in the vector and then use std::sort().
Sort elements of std::map.

```<code>#include<iostream>
#include <map>
#include <vector>
#include <algorithm>

typedef std::pair<std::string,int> pair;

int main()
{
    // input map
    std::map<std::string,int> map = {
        {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3}
    };

    // create an empty vector of pairs
    std::vector<pair> vec;

    // copy key-value pairs from the map to the vector
    std::copy(map.begin(),
            map.end(),
            std::back_inserter<std::vector<pair>>(vec));

    // sort the vector by increasing order of its pair's second value
    // if second value are equal, order by the pair's first value
    std::sort(vec.begin(), vec.end(),
            [](const pair& l, const pair& r) {
                if (l.second != r.second)
                    return l.second < r.second;

                return l.first < r.first;
            });

    // print the vector
    for (auto const &pair: vec) {
        std::cout << '{' << pair.first << "," << pair.second << '}' << '\n';
    }

    return 0;
}
</code>```

Body:
You can not really change the elements of a std::map. However, you can use std::vector to first copy the elements in the vector and then use std::sort().
Sort elements of std::map.

#include<iostream>
#include <map>
#include <vector>
#include <algorithm>

typedef std::pair<std::string,int> pair;

int main()
{
    // input map
    std::map<std::string,int> map = {
        {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3}
    };

    // create an empty vector of pairs
    std::vector<pair> vec;

    // copy key-value pairs from the map to the vector
    std::copy(map.begin(),
            map.end(),
            std::back_inserter<std::vector<pair>>(vec));

    // sort the vector by increasing order of its pair's second value
    // if second value are equal, order by the pair's first value
    std::sort(vec.begin(), vec.end(),
            [](const pair& l, const pair& r) {
                if (l.second != r.second)
                    return l.second < r.second;

                return l.first < r.first;
            });

    // print the vector
    for (auto const &pair: vec) {
        std::cout << '{' << pair.first << "," << pair.second << '}' << '\n';
    }

    return 0;
}


问:
Select subfield returns empty string when looped by wc_get_related_products
On my single product page, I am trying to get the related products using woocommerce's built in wc_get_related_products() function, which returns an array of product IDs.

So I loop through the related product IDs and runs a get_field( 'workshop_details', $product_id ) inside it. The workshop_details field is a group field, which has the following subfields: workshop_type (select field), workshop_date (date field), and workshop_row (text field).

Problem is, the return value of workshop_type subfield is always an empty string, but the other subfields are returning fine. I tried to change the return value of the select field to value, label, and both, but nothing changes.

Another problem is, when I loop through all the products by just using get_posts(), and running the get_field( 'workshop_details', $product_id ), it returns the workshop_type properly.

But I can't just use get_posts() instead of wc_get_related_products() because it would ignore the upsells/custom related products on the product.

答: Closing this question now, apparently it was a data problem. ♀</p>


问:
Opening file in an app from URL
I'm trying to create a link that, if clicked on a mobile device (ios), will open a PDF in a FileExplorer mobile app (or the App store if they don't have one installed). I've tried finding apps with their own URL scheme (similar to Facebook's "fb://" or YouTube's "youtube://"), but I'm not having any luck.

I've reviewed the content in the following pages and still have not found an answer:

iPhone apps: Can I open an app from a link in a website?

How to open ios app using url?

Opening an app from URL schema

答: There is the option to open the Files app at a specific location using the shareddocuments:// URL scheme, as described in this article.

Title: Opening file in an app from URL


问:
Laravel data mismatch error while using \PDO::ATTR_EMULATE_PREPARES => true
We have application build in Php Laravel and for the database we use postgres sql. And also on top of postgres we have configure pgBouncer to limit the maximum number of connections on server side by managing a pool of idle connections that can be used by any applications.

Now, we face the issue with the boolean values (True(0),False(1)) used in the application (Php Laravel). It gives below error when any CRUD operation is performed. In the below error column "revoked" is boolean type.

column \"revoked\" is of type boolean but expression is of type integer
You will need to rewrite or cast the expression. (SQL: \"revoked\", \"created_at\") values (0, 2020-02-07 06:09:06)

Now after exploring, I came to know that boolean values needs to be consider to be string with the pgBouncer. So I have made changes in the connection.php file, located in "\vendor\laravel\framework\src\Illuminate\Database". I have change the code to consider the boolean value as mentioned below.

```<code>public function bindValues($statement, $bindings)
{
    foreach ($bindings as $key => $value) {
        //if(is_bool($value))
        $statement->bindValue(
            is_string($key) ? $key : $key + 1, $value,
            //is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR
            is_int($value) ? PDO::PARAM_INT : is_bool($value) ? PDO::PARAM_STR : PDO::PARAM_STR
        );
    }
}
</code>```

After the above changes the error with the boolean values was solved.

But, now I am facing strange issues on the server, when I check the database log error I consistently get the below error.

ERROR:  prepared statement "pdo_stmt_00000001" already exists
STATEMENT:  set names 'utf8'
ERROR:  prepared statement "pdo_stmt_00000001" does not exist
STATEMENT:  DEALLOCATE pdo_stmt_00000001

It really was strange, and after exploring the internet I have done the below changes in my database.php file, to disable the prepare statements.

```<code>'pgsql' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'schema' => 'public',
        'sslmode' => 'prefer',
        'options' => [
            \PDO::ATTR_EMULATE_PREPARES => true
        ]
]
</code>```

The reason behind seeting ATTR_EMULATE_PREPARES => true is becasue I have set "Transaction" mode in "pgbouncer.ini" file.

Now, to make prepared statements work in Transaction mode would need PgBouncer to keep track of them internally, which it does not do. So only way to keep using PgBouncer in this mode is to disable prepared statements in the client, which in my case is PHP Laravel and I have already handle it in the "database.php" file when the connection is made as shown in above code.

I have tried all the options, which are given in http://www.pgbouncer.org/faq.html#how-to-use-prepared-statements-with-transaction-pooling but it doesnot solve the prepare statment error shown in the database log.

ERROR:  prepared statement "pdo_stmt_00000001" already exists
STATEMENT:  set names 'utf8'
ERROR:  prepared statement "pdo_stmt_00000001" does not exist
STATEMENT:  DEALLOCATE pdo_stmt_00000001

Please guide me on the same and what further settings are required for the error. Those errors are on the client production server and we cannot go ahead with those errors in production server.

Please give me your valuable feedback at the earliest as I am facing the issue since 5 days and try with all the options that come across.

Thanks!

答:
First you never need to modify the vendor code, instead you can use attribute casting from your model.

From laravel.com/docs/master/eloquent-mutators#attribute-casting

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, and timestamp. When casting to decimal, you must define the number of digits (decimal:2).

To demonstrate attribute casting, let's cast the is_admin attribute,
  which is stored in our database as an integer (0 or 1) to a boolean
  value:

So in your case you will need to cast revoked to bool by adding to your Eloquent model the $casts property as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'revoked' => 'boolean',
    ];
}
```

And for your pgBouncer issue it seems that pgBouncer have an internal issue with transaction pooling and prepared statements,

From: stackoverflow.com/a/7612639/7047493

This turned out to be a pgBouncer issue that occurs when using anything other than session pooling. We were using transaction pooling, which apparently can't support prepared statements. By switching to session pooling, we got around the issue.

Body:
We have application build in Php Laravel and for the database we use postgres sql. And also on top of postgres we have configure pgBouncer to limit the maximum number of connections on server side by managing a pool of idle connections that can be used by any applications.

Now, we face the issue with the boolean values (True(0),False(1)) used in the application (Php Laravel). It gives below error when any CRUD operation is performed. In the below error column "revoked" is boolean type.

column \"revoked\" is of type boolean but expression is of type integer
You will need to rewrite or cast the expression. (SQL: \"revoked\", \"created_at\") values (0, 2020-02-07 06:09:06)

Now after exploring, I came to know that boolean values needs to be consider to be string with the pgBouncer. So I have made changes in the connection.php file, located in "\vendor\laravel\framework\src\Illuminate\Database". I have change the code to consider the boolean value as mentioned below.

public function bindValues($statement, $bindings)
{
    foreach ($bindings as $key => $value) {
        //if(is_bool($value))
        $statement->bindValue(
            is_string($key) ? $key : $key + 1, $value,
            //is_int($value) ? PDO::PARAM_INT : PDO::PARAM_STR
            is_int($value) ? PDO::PARAM_INT : is_bool($value) ? PDO::PARAM_STR : PDO::PARAM_STR
        );
    }
}

After the above changes the error with the boolean values was solved.

But, now I am facing strange issues on the server, when I check the database log error I consistently get the below error.

ERROR:  prepared statement "pdo_stmt_00000001" already exists
STATEMENT:  set names 'utf8'
ERROR:  prepared statement "pdo_stmt_00000001" does not exist
STATEMENT:  DEALLOCATE pdo_stmt_00000001

It really was strange, and after exploring the internet I have done the below changes in my database.php file, to disable the prepare statements.

'pgsql' => [
        'driver' => 'pgsql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '5432'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'schema' => 'public',
        'sslmode' => 'prefer',
        'options' => [
            \PDO::ATTR_EMULATE_PREPARES => true
        ]
]

The reason behind seeting ATTR_EMULATE_PREPARES => true is becasue I have set "Transaction" mode in "pgbouncer.ini" file.

Now, to make prepared statements work in Transaction mode would need PgBouncer to keep track of them internally, which it does not do. So only way to keep using PgBouncer in this mode is to disable prepared statements in the client, which in my case is PHP Laravel and I have already handle it in the "database.php" file when the connection is made as shown in above code.

I have tried all the options, which are given in http://www.pgbouncer.org/faq.html#how-to-use-prepared-statements-with-transaction-pooling but it doesnot solve the prepare statment error shown in the database log.

ERROR:  prepared statement "pdo_stmt_00000001" already exists
STATEMENT:  set names 'utf8'
ERROR:  prepared statement "pdo_stmt_00000001" does not exist
STATEMENT:  DEALLOCATE pdo_stmt_00000001

Please guide me on the same and what further settings are required for the error. Those errors are on the client production server and we cannot go ahead with those errors in production server.

Please give me your valuable feedback at the earliest as I am facing the issue since 5 days and try with all the options that come across.

Thanks!

Body:
First you never need to modify the vendor code, instead you can use attribute casting from your model.

From laravel.com/docs/master/eloquent-mutators#attribute-casting

The $casts property on your model provides a convenient method of converting attributes to common data types. The $casts property should be an array where the key is the name of the attribute being cast and the value is the type you wish to cast the column to. The supported cast types are: integer, real, float, double, decimal:, string, boolean, object, array, collection, date, datetime, and timestamp. When casting to decimal, you must define the number of digits (decimal:2).

To demonstrate attribute casting, let's cast the is_admin attribute,
  which is stored in our database as an integer (0 or 1) to a boolean
  value:

So in your case you will need to cast revoked to bool by adding to your Eloquent model the $casts property as follows:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model
{
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'revoked' => 'boolean',
    ];
}

And for your pgBouncer issue it seems that pgBouncer have an internal issue with transaction pooling and prepared statements,

From: stackoverflow.com/a/7612639/7047493

This turned out to be a pgBouncer issue that occurs when using anything other than session pooling. We were using transaction pooling, which apparently can't support prepared statements. By switching to session pooling, we got around the issue.