问:
How can I fix this Combinations calculating(nCr) program?
I have created this simple program using c to calculate combinations. But whenever I enter large value like 20,30,40.. for variable 'n' and for 'r' program output is not true. But this program works fine with small numbers like 5,7,10... How can i fix this problem to find combinations even input big numbers for n and r ?

Also I wanna use nCr = n-1Cr + n-1Cr-1 rule in this program and I am using C language

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

int fact(int i){

    if(i <= 1){
        return 1;
    }
    return i * fact(i-1);
}

int nCr(int n,int r){

    int nCr;

    if(r == 0 || n == r){
        nCr = 1;
    }else{

        nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));

    }
    return nCr;
}

int main(){

    int n,r;

    printf("Enter n : ");
    scanf("%d",&n);
    printf("Enter r : ");
    scanf("%d",&r);

    printf("nCr value : %d\n",nCr(n,r));
    return 0;
}
</code>```

Thank you so much for your answers.

答:
How can i fix this problem to find combinations even input big numbers for n and r ?

Use a wider integer type.  32-bit int good only to fact(12).

Compute nCr(int n,int r) without using fact().  Form the product/quotient in steps.

Use floating point math and tolerate inexactness.

Let us go for door # 2.  The idea to use * and / in each step.

Example, with 52 cards there are 2,598,960 different power hands.

```<code>uintmax_t nCr(unsigned n, unsigned r) {
  uintmax_t y = 1;
  if (r <= n) {
    if (n - r + r < r + r) {
      r = n - r;
    }
    for (unsigned i = 1; i <= r; i++) {
      y = y * (n - r + i) / i;
    }
  }
  return y;
}

int main(void) {
  printf("%ju\n", nCr(52, 5));  // 2598960
  return 0;
}
</code>```

Body:
I have created this simple program using c to calculate combinations. But whenever I enter large value like 20,30,40.. for variable 'n' and for 'r' program output is not true. But this program works fine with small numbers like 5,7,10... How can i fix this problem to find combinations even input big numbers for n and r ?

Also I wanna use nCr = n-1Cr + n-1Cr-1 rule in this program and I am using C language

#include <stdio.h>

int fact(int i){

    if(i <= 1){
        return 1;
    }
    return i * fact(i-1);
}

int nCr(int n,int r){

    int nCr;

    if(r == 0 || n == r){
        nCr = 1;
    }else{

        nCr = (fact(n-1)/(fact(r) * fact(n-1-r))) + (fact(n-1)/(fact(r-1) * fact(n-r)));

    }
    return nCr;
}

int main(){

    int n,r;

    printf("Enter n : ");
    scanf("%d",&n);
    printf("Enter r : ");
    scanf("%d",&r);

    printf("nCr value : %d\n",nCr(n,r));
    return 0;
}

Thank you so much for your answers.

Body:
How can i fix this problem to find combinations even input big numbers for n and r ?

Use a wider integer type.  32-bit int good only to fact(12).

Compute nCr(int n,int r) without using fact().  Form the product/quotient in steps.

Use floating point math and tolerate inexactness.

Let us go for door # 2.  The idea to use * and / in each step.

Example, with 52 cards there are 2,598,960 different power hands.

uintmax_t nCr(unsigned n, unsigned r) {
  uintmax_t y = 1;
  if (r <= n) {
    if (n - r + r < r + r) {
      r = n - r;
    }
    for (unsigned i = 1; i <= r; i++) {
      y = y * (n - r + i) / i;
    }
  }
  return y;
}

int main(void) {
  printf("%ju\n", nCr(52, 5));  // 2598960
  return 0;
}


来源: stackexchange

问:
Octave Functions
I've downloaded the "Data smoothing functions" from Octave forge and I think it was a great help but I need to make sure of something.
 does this function  "rgdtsmcore" does smoothing by taking the backward two-point average ?
if not ,how do I modify it to make it so ?

Code :

```<code>function out = rgdtsmcorewrap (log10lambda, x, y, d, mincell, varargin)

  if (nargin < 5)
    print_usage;
  endif

  lambda = 10^(log10lambda);

  if ( length(mincell) == 2 ) # using stdev to find optimal lambda
    stdev = mincell{2};
    yhat  = rgdtsmcore (x, y, d, lambda, varargin{:});

    xhatprov = 0;
    relative = 0;
    for i = 1:length(varargin)
      if strcmp(varargin{i},"relative")
        relative = 1;
      elseif strcmp(varargin{i},"xhat")
        xhatprov = 1;
        xhat = varargin{i+1};
      endif
    endfor

    if (xhatprov)
      idx = interp1(xhat,1:length(xhat),x,"nearest");
      if relative
        stdevd = std((y-yhat(idx))./y);
      else
        stdevd = std(y-yhat(idx));
      endif
    else
      if (relative)
        stdevd = std((y-yhat)./y);
      else
        stdevd = std(y-yhat);
      endif
    endif

    out = (stdevd - stdev)^2;

  else # use gcv to find optimal lambda
    [yhat, out] = rgdtsmcore (x, y, d, lambda, varargin{:});
  endif

endfunction
</code>```

Thank you in advance...

答:
I assume you mean averaging between the current point and one point before

```<code>t=pi*[0:.01:1];
x=sin(t)+rand(size(t))*.1; # data
y=zeros(size(x));
y(2:end)=(x(1:end-1)+x(2:end))/2; # 2 points average

subplot(3,1,1)
plot(t,x)
subplot(3,1,2)
plot(t,y)
subplot(3,1,3)
plot(t,x,t,y)
</code>```

Of course there is no average for the first point

ContentLicense: CC BY-SA 4.0

Title: Octave Functions

Body:
I've downloaded the "Data smoothing functions" from Octave forge and I think it was a great help but I need to make sure of something.
 does this function  "rgdtsmcore" does smoothing by taking the backward two-point average ?
if not ,how do I modify it to make it so ?

Code :

function out = rgdtsmcorewrap (log10lambda, x, y, d, mincell, varargin)

  if (nargin < 5)
    print_usage;
  endif

  lambda = 10^(log10lambda);

  if ( length(mincell) == 2 ) # using stdev to find optimal lambda
    stdev = mincell{2};
    yhat  = rgdtsmcore (x, y, d, lambda, varargin{:});

    xhatprov = 0;
    relative = 0;
    for i = 1:length(varargin)
      if strcmp(varargin{i},"relative")
        relative = 1;
      elseif strcmp(varargin{i},"xhat")
        xhatprov = 1;
        xhat = varargin{i+1};
      endif
    endfor

    if (xhatprov)
      idx = interp1(xhat,1:length(xhat),x,"nearest");
      if relative
        stdevd = std((y-yhat(idx))./y);
      else
        stdevd = std(y-yhat(idx));
      endif
    else
      if (relative)
        stdevd = std((y-yhat)./y);
      else
        stdevd = std(y-yhat);
      endif
    endif

    out = (stdevd - stdev)^2;

  else # use gcv to find optimal lambda
    [yhat, out] = rgdtsmcore (x, y, d, lambda, varargin{:});
  endif

endfunction

Thank you in advance...

Body:
I assume you mean averaging between the current point and one point before

t=pi*[0:.01:1];
x=sin(t)+rand(size(t))*.1; # data
y=zeros(size(x));
y(2:end)=(x(1:end-1)+x(2:end))/2; # 2 points average

subplot(3,1,1)
plot(t,x)
subplot(3,1,2)
plot(t,y)
subplot(3,1,3)
plot(t,x,t,y)

Of course there is no average for the first point


问:
I need to split .txt file's content to a new line when it sees a backslash
I have a .txt file named "new.txt" and its content is;

```<code>nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273
</code>```

I need to format that .txt file, to be more specific i need to go to the next line when backslash is detected like one number for each line and i need to remove the letters aswell.

Formatted .txt file needs to look like this;

```<code>15
995
823
721
1
1872
...
</code>```

So far, because of my little Java knowledge, i managed to just read the file and output it. Here it is;

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNextLine()) {
                String obj2 = read.nextLine();
                System.out.println(obj2);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}
</code>```

I need to solve this so i can move on to the next question but i'm stuck with this question and can't solve it and i'm trying for three hours.

Any help or clues are highly appreciated, thanks.

答:
Just put this to your string:

```<code>String obj2 = read.nextLine().replace("\\", "\n");
</code>```

It will print a new line each time it finds \

Body:
I have a .txt file named "new.txt" and its content is;

nxy15\nxy995\nxy823\nxy721\nxy1\nxy1872\nxy3482\nxy878\nxy123\nxy8753\nxy1284\nxy4495\nxy4323\nxy812\nxy7123\nxy1273

I need to format that .txt file, to be more specific i need to go to the next line when backslash is detected like one number for each line and i need to remove the letters aswell.

Formatted .txt file needs to look like this;

15
995
823
721
1
1872
...

So far, because of my little Java knowledge, i managed to just read the file and output it. Here it is;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNextLine()) {
                String obj2 = read.nextLine();
                System.out.println(obj2);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

I need to solve this so i can move on to the next question but i'm stuck with this question and can't solve it and i'm trying for three hours.

Any help or clues are highly appreciated, thanks.

Body:
Just put this to your string:

String obj2 = read.nextLine().replace("\\", "\n");

It will print a new line each time it finds \


问:
how to add xaxis and yaxis label with python-pptx
I am learning python-pptx. I have simple below example which generate line chart and is working fine. How can I add xaxis label i.e."Quarters" and yaxis label as "Sales" to this chart ? </p>

```<code>from pptx import Presentation
from pptx.util import Inches
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE

# create presentation with 1 slide ------
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])

# define chart data ---------------------
chart_data = ChartData()
chart_data.categories = ['Q1 Sales', 'Q2 Sales', 'Q3 Sales']
chart_data.add_series('West',    (32.2, 28.4, 34.7))
chart_data.add_series('East',    (24.3, 30.6, 20.2))
chart_data.add_series('Midwest', (20.4, 18.3, 26.2))

x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
    XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data
).chart

chart.has_legend = True
chart.legend.include_in_layout = False
chart.series[0].smooth = True
prs.save('test1.pptx')
</code>```

答:
Such a label is known as an axis title in PowerPoint parlance.

You can access the axis-title object for an axis using the axis.axis_title property described in the documentation here:

https://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.axis._BaseAxis.axis_title

So something like this should do the trick in your case:

```<code>category_axis_title = chart.category_axis.axis_title
category_axis_title.text_frame.text = "Quarter"
value_axis_title = chart.value_axis.axis_title
value_axis_title.text_frame.text = "Sales"
</code>```

Between the TextFrame object and ChartFormat object associated with the axis-title you have control over the color, size, font, etc. of the axis-title text.

Body:
I am learning python-pptx. I have simple below example which generate line chart and is working fine. How can I add xaxis label i.e."Quarters" and yaxis label as "Sales" to this chart ?

from pptx import Presentation
from pptx.util import Inches
from pptx.chart.data import ChartData
from pptx.enum.chart import XL_CHART_TYPE

# create presentation with 1 slide ------
prs = Presentation()
slide = prs.slides.add_slide(prs.slide_layouts[5])

# define chart data ---------------------
chart_data = ChartData()
chart_data.categories = ['Q1 Sales', 'Q2 Sales', 'Q3 Sales']
chart_data.add_series('West',    (32.2, 28.4, 34.7))
chart_data.add_series('East',    (24.3, 30.6, 20.2))
chart_data.add_series('Midwest', (20.4, 18.3, 26.2))

x, y, cx, cy = Inches(2), Inches(2), Inches(6), Inches(4.5)
chart = slide.shapes.add_chart(
    XL_CHART_TYPE.LINE, x, y, cx, cy, chart_data
).chart

chart.has_legend = True
chart.legend.include_in_layout = False
chart.series[0].smooth = True
prs.save('test1.pptx')

Body:
Such a label is known as an axis title in PowerPoint parlance.

You can access the axis-title object for an axis using the axis.axis_title property described in the documentation here:

https://python-pptx.readthedocs.io/en/latest/api/chart.html#pptx.chart.axis._BaseAxis.axis_title

So something like this should do the trick in your case:

category_axis_title = chart.category_axis.axis_title
category_axis_title.text_frame.text = "Quarter"
value_axis_title = chart.value_axis.axis_title
value_axis_title.text_frame.text = "Sales"

Between the TextFrame object and ChartFormat object associated with the axis-title you have control over the color, size, font, etc. of the axis-title text.


问:
Implementing events in C++
After some research on internet for an efficient way to implement events in C++, I found the following methods

Interface class - Applications can override the virtual functions in the derived class

Normal Callback mechanism using function pointers

Delegates using Boost.function

Signals and slots (as used in Qt)

I am confused on advantages and disadvantages of each of these and when to use anyone of this.
Which is the best method and why?
Is there any other solutions which are better than the ones listed?

答:
FWIW, my vote would be for Boost Signals any day.

Boost ensures portability. Of course it integrates nicely with e.g. Boost Asio, Functional, Bind, etc.

Update:

Signals2

This documentation describes a thread-safe variant of the original Boost.Signals library. There have been some changes to the interface to support thread-safety, mostly with respect to automatic connection management. [....]

Boost ensures portability. Of course it integrates nicely with e.g. Boost Asio, Functional, Bind, etc.

boost::signals2::signal sig;

```<code>sig.connect(&print_sum);
sig.connect(&print_product);
sig.connect(&print_difference);
sig.connect(&print_quotient);

sig(5., 3.);
</code>```

This program will print out the following:

```<code>The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667
</code>```

sample actions:

```<code>void print_sum(float x, float y)
{
  std::cout << "The sum is " << x+y << std::endl;
}

void print_product(float x, float y)
{
  std::cout << "The product is " << x*y << std::endl;
}

void print_difference(float x, float y)
{
  std::cout << "The difference is " << x-y << std::endl;
}

void print_quotient(float x, float y)
{
  std::cout << "The quotient is " << x/y << std::endl;
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Implementing events in C++

Body:
FWIW, my vote would be for Boost Signals any day.

Boost ensures portability. Of course it integrates nicely with e.g. Boost Asio, Functional, Bind, etc.

Update:

Signals2

This documentation describes a thread-safe variant of the original Boost.Signals library. There have been some changes to the interface to support thread-safety, mostly with respect to automatic connection management. [....]

Boost ensures portability. Of course it integrates nicely with e.g. Boost Asio, Functional, Bind, etc.

boost::signals2::signal sig;

sig.connect(&print_sum);
sig.connect(&print_product);
sig.connect(&print_difference);
sig.connect(&print_quotient);

sig(5., 3.);

This program will print out the following:

The sum is 8
The product is 15
The difference is 2
The quotient is 1.66667

sample actions:

void print_sum(float x, float y)
{
  std::cout << "The sum is " << x+y << std::endl;
}

void print_product(float x, float y)
{
  std::cout << "The product is " << x*y << std::endl;
}

void print_difference(float x, float y)
{
  std::cout << "The difference is " << x-y << std::endl;
}

void print_quotient(float x, float y)
{
  std::cout << "The quotient is " << x/y << std::endl;
}


问:
When autorelease pool release object in background thread?
I know autorelease pool will release objects when the runloop in the state kCFRunLoopBeforeWaiting.

So I create a background thread which runloop doesn't run by default.

If I use an autorelease pool in this background thread, when does it release objects.

答:
https://developer.apple.com/documentation/foundation/nsautoreleasepool?language=objc

autorelease pool is just a unlimited stack for keeping autorelease object.
when you create a autorelease pool, pool stack push a watcher.
when you call autorelease on object, the object is pushed into the pool stack.
when you release autorelease pool, it release all pushed object after watcher, and then remove the watcher.

@autorelease in objc or autorelease in swift, is just a wrapper for create a autorelease pool, call block and then release pool.

runloop will automatically wrapper task into a autorelease pool.

but when you use autorelease pool with a custom thread, which haven't a runloop, in my observe, object will release when thread exit..

How to observe autorelease timeing

you can create a custom watch class with deinit defined, and manual retain and autorelease it, to observe the deinit timeing. code as below

class A {
    deinit {
        print("a dealloced")
    }
}

var p: pthread_t?
_ = pthread_create(&p, nil, { (p) -> UnsafeMutableRawPointer? in
    do {
        let a = A()
        _ = Unmanaged.passRetained(a).autorelease()
    }
    print("will exit pthread")
    return nil
}, nil)
pthread_join(p!, nil)
print("finish")
```

<p>this script will print </p>

```will exit pthread
a dealloced
finish
```

also you can breakpoint at deinit to see the backtrace of autorelease

Body:
https://developer.apple.com/documentation/foundation/nsautoreleasepool?language=objc

autorelease pool is just a unlimited stack for keeping autorelease object.
when you create a autorelease pool, pool stack push a watcher.
when you call autorelease on object, the object is pushed into the pool stack.
when you release autorelease pool, it release all pushed object after watcher, and then remove the watcher.

@autorelease in objc or autorelease in swift, is just a wrapper for create a autorelease pool, call block and then release pool.

runloop will automatically wrapper task into a autorelease pool.

but when you use autorelease pool with a custom thread, which haven't a runloop, in my observe, object will release when thread exit..

How to observe autorelease timeing

you can create a custom watch class with deinit defined, and manual retain and autorelease it, to observe the deinit timeing. code as below

class A {
    deinit {
        print("a dealloced")
    }
}

var p: pthread_t?
_ = pthread_create(&p, nil, { (p) -> UnsafeMutableRawPointer? in
    do {
        let a = A()
        _ = Unmanaged.passRetained(a).autorelease()
    }
    print("will exit pthread")
    return nil
}, nil)
pthread_join(p!, nil)
print("finish")

this script will print

will exit pthread
a dealloced
finish

also you can breakpoint at deinit to see the backtrace of autorelease


问:
Why won't must flexDirection: 'column' push space between?
I have:

```<code>        <Grid item xs={12} md={6} className={classes.heroGrid}>
          <Typography variant='h3' >
Some stuff
          </Typography>
          <div style={{ display: 'flex' }}>
            here
          </div>

        </Grid>
</code>```

And heroGrid is:

```<code>    heroGrid: {
      flexDirection: 'column',
      justifyContent: 'space-between',
      alignContent: 'space-between',
      alignItems: 'space-between'
    }
</code>```

But it doesn't push my content to be apart.

答:
The height of the top level <Grid> component is probably being calculated to be exactly the height of the elements it contains.

So, it's pushing all the extra space between the two elements—it just so happens there's 0px of extra space!

You could test this temporarily by setting a fixed height to the <Grid> element with something like:

```<code><Grid item xs={12} md={6} className={classes.heroGrid} style={{height: 500}}>
</code>```

If you're elements are then pushed apart as desired, you then need to figure out how you want to actually set the height of the Grid element. If it should fill the parent, you could make the height 100%. If it should be a fixed height, you could set it to the specific fixed height.

Body:
I have:

        <Grid item xs={12} md={6} className={classes.heroGrid}>
          <Typography variant='h3' >
Some stuff
          </Typography>

            here

        </Grid>

And heroGrid is:

    heroGrid: {
      flexDirection: 'column',
      justifyContent: 'space-between',
      alignContent: 'space-between',
      alignItems: 'space-between'
    }

But it doesn't push my content to be apart.

Body:
The height of the top level <Grid> component is probably being calculated to be exactly the height of the elements it contains.

So, it's pushing all the extra space between the two elements—it just so happens there's 0px of extra space!

You could test this temporarily by setting a fixed height to the <Grid> element with something like:

<Grid item xs={12} md={6} className={classes.heroGrid} style={{height: 500}}>

If you're elements are then pushed apart as desired, you then need to figure out how you want to actually set the height of the Grid element. If it should fill the parent, you could make the height 100%. If it should be a fixed height, you could set it to the specific fixed height.


问:
How can I optimize my array filtering by date times?
I wrote this simple filter array per data time, but not sure if it's good way.

Example data:

```<code>[
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]
</code>```

And i want to convert it like this:

```<code> {
      "Fri May 29 2020": [
        {
          "content": "test1",
          "createdAt": "2020-05-29T13:46:14.000Z"
        },
        {
          "content": "test2",
          "createdAt": "2020-05-29T13:46:14.000Z"
        }
      ],
      "Wed May 27 2020": [
        {
          "content": "test3",
          "createdAt": "2020-05-27T13:46:14.000Z"
        }
      ]
    }
</code>```

And there is my code:

```<code>let usedDates = new Set();
let logs = {};

for(let log of data) {
    const date = new Date(log.createdAt).toDateString();
    if(usedDates.has(date)) continue;

    logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
    usedDates.add(date);
}
</code>```

yeah it works, but not sure if it's good way.

答:
This one simple reduce trick can help you

const data = [
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]

const result = data.reduce((acc, value) => {
  const date = new Date(value.createdAt);
  const dateFormatted = date.toDateString();

  acc[dateFormatted] = [...(acc[dateFormatted] || []), value];

  return acc;

}, {})

console.log(result);```

Body:
I wrote this simple filter array per data time, but not sure if it's good way.

Example data:

[
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]

And i want to convert it like this:

 {
      "Fri May 29 2020": [
        {
          "content": "test1",
          "createdAt": "2020-05-29T13:46:14.000Z"
        },
        {
          "content": "test2",
          "createdAt": "2020-05-29T13:46:14.000Z"
        }
      ],
      "Wed May 27 2020": [
        {
          "content": "test3",
          "createdAt": "2020-05-27T13:46:14.000Z"
        }
      ]
    }

And there is my code:

let usedDates = new Set();
let logs = {};

for(let log of data) {
    const date = new Date(log.createdAt).toDateString();
    if(usedDates.has(date)) continue;

    logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
    usedDates.add(date);
}

yeah it works, but not sure if it's good way.


问:
Swift: Creating a button that shuffles an array
I am trying to create an UIAlertAction that is displayed after clicking on a sort button, that would shuffle the array. I tried this:

```<code>let action4 = UIAlertAction(title: "Shuffle", style: .default) { ( action: UIAlertAction) in self.array.sort { self.array.shuffle() }
    self.tableView.reloadData() }
</code>```

I used that to sort by names:

```<code>let action = UIAlertAction(title: "By name", style: .default) { ( action: UIAlertAction) in self.array.sort { $1.first_name > $0.first_name }
        self.tableView.reloadData() }
</code>```

Error: Cannot convert value of type '[Person]' to expected argument type 'Bool'

答:
Just remove sort, you don't want sorting, you want shuffling only.

```<code>let action4 = UIAlertAction(title: "Shuffle", style: .default) { _ in self.array.shuffle() }
</code>```

Body:
I am trying to create an UIAlertAction that is displayed after clicking on a sort button, that would shuffle the array. I tried this:

let action4 = UIAlertAction(title: "Shuffle", style: .default) { ( action: UIAlertAction) in self.array.sort { self.array.shuffle() }
    self.tableView.reloadData() }

I used that to sort by names:

let action = UIAlertAction(title: "By name", style: .default) { ( action: UIAlertAction) in self.array.sort { $1.first_name > $0.first_name }
        self.tableView.reloadData() }

Error: Cannot convert value of type '[Person]' to expected argument type 'Bool'

Body:
Just remove sort, you don't want sorting, you want shuffling only.

let action4 = UIAlertAction(title: "Shuffle", style: .default) { _ in self.array.shuffle() }


问:
ESLint throws an error when trying to assign multiple variables to the same value
Why does ESLint throw a Parsing error: Unexpected token , after a variable declaration on this line of code?

const a, b, c = 1;

My .eslintrc.json looks like this;

```<code>{

    "env": {
        "browser": true,
        "es6": true,
        "jquery": true,
        "commonjs": true
    },
    "extends": [
        "airbnb-base",
        "prettier"
    ],
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "script"
    },
    "plugins": ["prettier"],
    "rules": {
        "prettier/prettier": "error",
        "semi": ["error", "always"],
        "quotes": ["error", "double"]
    }

}
</code>```

答:
You cannot do that in JS.

If multiple variables listed in a variable declaration (either var, let or const), each value has its own initializer, so it's impossible to assign a single value to multiple variables in a single declaration statement, without repetition.

If an initializer is missing (no = value part present), the variable will be set to undefined.

So if you used let, then c would become 1, while a and b would be undefined:

let a, b, c = 1;

console.log(a, b, c) //undefined undefined 1```
</div>
</div>
</p>

<p>However, omitting the initializer in a <code>const</code> declaration throws an error (it doesn't make too much sense to assign <code>undefined</code> to a constant, right?)</p>

<p>Therefore, your code fails (not just in ESLint, but in any JS runtime that correctly implements the ECMAScript standard):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a, b, c = 1; //SyntaxError</code>```

To assign the same value to multiple variables, you have to either:

Repeat the value (this won't work if the value is an object literal (including array literals and function expressions) or returned by a constructor, a factory, or non-pure function):

const a = 1, b = 1, c = 1;

console.log(a, b, c) //1 1 1```
</div>
</div>
</p></li>
<li><p>Assign the variables from each other (tip: put the one with the shortest name first and repeat that one):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const a = 1, b = a, c = a;

console.log(a, b, c) //1 1 1</code>```

Use let:

let a, b, c;
a = b = c = 1

console.log(a, b, c) //1 1 1```
</div>
</div>
</p></li>
<li><p>Destructure an infinite iterator (that seems useful in case of a very large number of variables):
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const [a, b, c] = (function*(v){while(true) yield v})(1);
                                                   // ^--- Value

console.log(a, b, c) //1 1 1</code>```

Body:
Why does ESLint throw a Parsing error: Unexpected token , after a variable declaration on this line of code?

const a, b, c = 1;

My .eslintrc.json looks like this;

{

    "env": {
        "browser": true,
        "es6": true,
        "jquery": true,
        "commonjs": true
    },
    "extends": [
        "airbnb-base",
        "prettier"
    ],
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "script"
    },
    "plugins": ["prettier"],
    "rules": {
        "prettier/prettier": "error",
        "semi": ["error", "always"],
        "quotes": ["error", "double"]
    }

}

Body:
You cannot do that in JS.

If multiple variables listed in a variable declaration (either var, let or const), each value has its own initializer, so it's impossible to assign a single value to multiple variables in a single declaration statement, without repetition.

If an initializer is missing (no = value part present), the variable will be set to undefined.

So if you used let, then c would become 1, while a and b would be undefined:

let a, b, c = 1;

console.log(a, b, c) //undefined undefined 1

However, omitting the initializer in a const declaration throws an error (it doesn't make too much sense to assign undefined to a constant, right?)

Therefore, your code fails (not just in ESLint, but in any JS runtime that correctly implements the ECMAScript standard):

const a, b, c = 1; //SyntaxError

To assign the same value to multiple variables, you have to either:

Repeat the value (this won't work if the value is an object literal (including array literals and function expressions) or returned by a constructor, a factory, or non-pure function):

const a = 1, b = 1, c = 1;

console.log(a, b, c) //1 1 1

Assign the variables from each other (tip: put the one with the shortest name first and repeat that one):

const a = 1, b = a, c = a;

console.log(a, b, c) //1 1 1

Use let:

let a, b, c;
a = b = c = 1

console.log(a, b, c) //1 1 1

Destructure an infinite iterator (that seems useful in case of a very large number of variables):

const [a, b, c] = (function*(v){while(true) yield v})(1);
                                                   // ^--- Value

console.log(a, b, c) //1 1 1


问:
Why does the singly linked list not insert correctly
I have a single linked list that I can insert up to 4 char values into. My goal is to get the insert to work which I do have working but the problem is that if the head of the Linked List is a greater value than the oters, it only will populate with the head

I have a structure of

```<code>struct listNode {
char data; /
struct listNode *nextPtr;
};
</code>```

I have an insert function of

```<code>    void insert(ListNode *sPtr, char value)
    {
    ListNode *newPtr;
    ListNode *previousPtr;
    ListNode *currentPtr;

    newPtr = malloc(sizeof(ListNode)); // create node

    if (newPtr != NULL) {
        newPtr->data = value;
        newPtr->nextPtr = NULL;
        previousPtr = NULL;
        currentPtr = sPtr;

        while (currentPtr != NULL && value >= currentPtr->data) {
            previousPtr = currentPtr;
            currentPtr = currentPtr->nextPtr;

        } // end while

        // insert new node at beginning of list
        if (previousPtr == NULL) {
            newPtr->nextPtr = sPtr;
            sPtr = newPtr;
        } // end if
        else { // insert new node between previousPtr and currentPtr
            previousPtr->nextPtr = newPtr;
            newPtr->nextPtr = currentPtr;
        } // end else
    } // end if
    else {
        printf("%c not inserted. No memory available.\n", value);
    } // end else
    } // end function insert
</code>```

In my print list

```<code>    void printList(ListNode *currentPtr)
{
    puts("The list is:");

    // while not the end of the list
    while (currentPtr != NULL) {
        printf("%c --> ", currentPtr->data);
        currentPtr = currentPtr->nextPtr;
    } // end while

    puts("NULL\n");
} // end function printList
</code>```

In my main

```<code>int main(void)
{
ListNode *startPtr = NULL;
ListNode *newPtr = NULL;
ListNode *headPtr = NULL;
unsigned int choice = 4;
char item;

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

newPtr = malloc(sizeof(ListNode)); // create node

headPtr = newPtr;

if (newPtr != NULL) { // is space available
    newPtr->data = item;
    newPtr->nextPtr = NULL;
    startPtr = newPtr;
}

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

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

So if I ran the code and entered in K Q L R
you would see

```<code> Input order:   K Q L R
 Output order:  K L Q R
</code>```

But if I entered in R Q L K
I would get

```<code> Input order:   R Q L K
 Output order:     R
</code>```

Why does this happen and how could I fix it?

答:
Try this

#include <stdio.h>
#include <stdlib.h>

struct ListNode {
    char data;
    struct ListNode *next;
};

void insert(struct ListNode *head, char value) {
    // Find tail
    struct ListNode *tail = head;
    while(tail->next != NULL)
        tail = tail->next;

    tail->next = malloc(sizeof(struct ListNode));
    if(tail->next == NULL) {
        // Handle memory allocation error
        abort();
    }

    // Setup value
    tail->next->data = value;
    tail->next->next = NULL;
}

int main() {
    struct ListNode *head = malloc(sizeof(struct ListNode));
    head->data = 0;
    head->next = NULL;

    // Read in data
    for(int i = 0; i < 3; i += 1) {
        fputs("Enter a character: ", stdout); // More efficient than printf in this case

        char c;
        scanf("\n%c", &c);

        if(c == EOF) {
            fputs("Error: Invalid input\n", stderr);
            return 1;
        }

        // First iteration
        if(i == 0) {
            head->data = c;
        } else {
            insert(head, c);
        }
    }

    // Print list
    struct ListNode *current = head;
    while(current != NULL) {
        printf("%c ", current->data);
        current = current->next;
    }

    // Free list
    current = head;
    while(1) {
        if(current->next == NULL) {
            // Last item
            free(current);
            break;
        }

        struct ListNode *next = current->next;
        free(current);
        current = next;
    }

    return 0;
}
```

Body:
I have a single linked list that I can insert up to 4 char values into. My goal is to get the insert to work which I do have working but the problem is that if the head of the Linked List is a greater value than the oters, it only will populate with the head

I have a structure of

struct listNode {
char data; /
struct listNode *nextPtr;
};

I have an insert function of

    void insert(ListNode *sPtr, char value)
    {
    ListNode *newPtr;
    ListNode *previousPtr;
    ListNode *currentPtr;

    newPtr = malloc(sizeof(ListNode)); // create node

    if (newPtr != NULL) {
        newPtr->data = value;
        newPtr->nextPtr = NULL;
        previousPtr = NULL;
        currentPtr = sPtr;

        while (currentPtr != NULL && value >= currentPtr->data) {
            previousPtr = currentPtr;
            currentPtr = currentPtr->nextPtr;

        } // end while

        // insert new node at beginning of list
        if (previousPtr == NULL) {
            newPtr->nextPtr = sPtr;
            sPtr = newPtr;
        } // end if
        else { // insert new node between previousPtr and currentPtr
            previousPtr->nextPtr = newPtr;
            newPtr->nextPtr = currentPtr;
        } // end else
    } // end if
    else {
        printf("%c not inserted. No memory available.\n", value);
    } // end else
    } // end function insert

In my print list

    void printList(ListNode *currentPtr)
{
    puts("The list is:");

    // while not the end of the list
    while (currentPtr != NULL) {
        printf("%c --> ", currentPtr->data);
        currentPtr = currentPtr->nextPtr;
    } // end while

    puts("NULL\n");
} // end function printList

In my main

int main(void)
{
ListNode *startPtr = NULL;
ListNode *newPtr = NULL;
ListNode *headPtr = NULL;
unsigned int choice = 4;
char item;

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

newPtr = malloc(sizeof(ListNode)); // create node

headPtr = newPtr;

if (newPtr != NULL) { // is space available
    newPtr->data = item;
    newPtr->nextPtr = NULL;
    startPtr = newPtr;
}

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);

printf("%s", "Enter a character: ");
scanf("\n%c", &item);

insert(headPtr, item);

printList(headPtr);
}

So if I ran the code and entered in K Q L R
you would see

 Input order:   K Q L R
 Output order:  K L Q R

But if I entered in R Q L K
I would get

 Input order:   R Q L K
 Output order:     R

Why does this happen and how could I fix it?


答:
You should try reading the original text file in, splitting around "/", and then printing each line of the resultant array</p>

```<code>import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        FileWriter myWriter = new FileWriter("filename.txt");
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNext()) {
                String obj2 = read.next();
                String[] arr = obj2.split("\");
                for(String s : arr) {
                    myWriter.write(s);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        myWriter.close()
    }
}
</code>```

Title: I need to split .txt file's content to a new line when it sees a backslash

Body:
You should try reading the original text file in, splitting around "/", and then printing each line of the resultant array

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadingFile{
    public static void main(String[] args) {
        FileWriter myWriter = new FileWriter("filename.txt");
        try {
            File file = new File("C:\\new.txt");
            Scanner read = new Scanner(file);
            while (read.hasNext()) {
                String obj2 = read.next();
                String[] arr = obj2.split("\");
                for(String s : arr) {
                    myWriter.write(s);
            }
            read.close();
        } catch (FileNotFoundException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        myWriter.close()
    }
}


问:
Neo4J ServiceUnavailable always in same place. No idea why
I've got a system that, when it is deployed, runs a lot of scripts to fill a Neo4J database. No CSV import, just regular queries creating tons of nodes and relationships.

Quite regularly, but not quite always, I get an error in one particular script, and I have no idea why. There's nothing unusual happening in that file.

The error:

```<code>| { Neo4jError: Connection was closed by server
|
|     at captureStacktrace (/code/node_modules/neo4j-driver/lib/v1/result.js:200:15)
|     at new Result (/code/node_modules/neo4j-driver/lib/v1/result.js:73:19)
|     at Session._run (/code/node_modules/neo4j-driver/lib/v1/session.js:173:14)
|     at Session.run (/code/node_modules/neo4j-driver/lib/v1/session.js:154:19)
|     at Object.complete (/code/datamigrations/003/0007_yet_another_script.js:34:17)
|     at ReadableStreamStreamer.ChunkStreamer.parseChunk (/code/node_modules/papaparse/papaparse.js:548:18)
|     at ReadableStreamStreamer.<anonymous> (/code/node_modules/papaparse/papaparse.js:857:11)
|     at ReadableStreamStreamer._streamData (/code/node_modules/papaparse/papaparse.js:1817:25)
|     at ReadableStreamStreamer.<anonymous> (/code/node_modules/papaparse/papaparse.js:876:9)
|     at IconvLiteEncoderStream.<anonymous> (/code/node_modules/papaparse/papaparse.js:1817:25) code: 'ServiceUnavailable', name: 'Neo4jError' }
</code>```

The script itself does nothing out of the ordinary. The error occurs at the first session.run of the script:

```<code>    session.run(
      `UNWIND {batch} as row
       MATCH (e:Episode {issueKey: row.issueKey})
       WITH e,row
       UNWIND row.otherIds as otherId
       MATCH (a:OtherElement {id: otherId})
       CREATE (e)-[:ENABLES]->(a)
      `,
      { batch: elements },
</code>```

Admittedly it's a big batch I'm creating here. Over 30k nodes. Could that cause the error? Would it be better to chunk this in batches of 10k or something?

答:
Yes, using smaller batches will probably help.

Also, your query can be simplified:

```<code>   UNWIND $batch as row
   MATCH (e:Episode {issueKey: row.issueKey}), (a:OtherElement)
   WHERE a.id IN row.otherIds
   CREATE (e)-[:ENABLES]->(a)
</code>```

In addition, having indexes on :Episode(issueKey) and :OtherElement(id) should improve performance.

Body:
I've got a system that, when it is deployed, runs a lot of scripts to fill a Neo4J database. No CSV import, just regular queries creating tons of nodes and relationships.

Quite regularly, but not quite always, I get an error in one particular script, and I have no idea why. There's nothing unusual happening in that file.

The error:

| { Neo4jError: Connection was closed by server
|
|     at captureStacktrace (/code/node_modules/neo4j-driver/lib/v1/result.js:200:15)
|     at new Result (/code/node_modules/neo4j-driver/lib/v1/result.js:73:19)
|     at Session._run (/code/node_modules/neo4j-driver/lib/v1/session.js:173:14)
|     at Session.run (/code/node_modules/neo4j-driver/lib/v1/session.js:154:19)
|     at Object.complete (/code/datamigrations/003/0007_yet_another_script.js:34:17)
|     at ReadableStreamStreamer.ChunkStreamer.parseChunk (/code/node_modules/papaparse/papaparse.js:548:18)
|     at ReadableStreamStreamer.<anonymous> (/code/node_modules/papaparse/papaparse.js:857:11)
|     at ReadableStreamStreamer._streamData (/code/node_modules/papaparse/papaparse.js:1817:25)
|     at ReadableStreamStreamer.<anonymous> (/code/node_modules/papaparse/papaparse.js:876:9)
|     at IconvLiteEncoderStream.<anonymous> (/code/node_modules/papaparse/papaparse.js:1817:25) code: 'ServiceUnavailable', name: 'Neo4jError' }

The script itself does nothing out of the ordinary. The error occurs at the first session.run of the script:

    session.run(
      `UNWIND {batch} as row
       MATCH (e:Episode {issueKey: row.issueKey})
       WITH e,row
       UNWIND row.otherIds as otherId
       MATCH (a:OtherElement {id: otherId})
       CREATE (e)-[:ENABLES]->(a)
      `,
      { batch: elements },

Admittedly it's a big batch I'm creating here. Over 30k nodes. Could that cause the error? Would it be better to chunk this in batches of 10k or something?

Body:
Yes, using smaller batches will probably help.

Also, your query can be simplified:

   UNWIND $batch as row
   MATCH (e:Episode {issueKey: row.issueKey}), (a:OtherElement)
   WHERE a.id IN row.otherIds
   CREATE (e)-[:ENABLES]->(a)

In addition, having indexes on :Episode(issueKey) and :OtherElement(id) should improve performance.


问:
ReferenceError: driver is not defined in Protractor
I'm a beginner. Can any one guide me?

Tests.js

```<code>describe("Test the calculator",()=>{

    it("Addition functionality",function test(){
        driver.browser.get("https://juliemr.github.io/protractor-demo/");
        browser.manage().window().maximize();
        //browser.manage().timeouts().implicitlyWait(3000)

    })
})
</code>```

Config.js

```<code>const driver= require("protractor")

exports.config= {
    browserName: 'chrome',
    framework: "mocha",
    directconnect: true,
    specs: ['./tests.js'],
    mochaOpts: {
        timeout: 0
    }
}
</code>```

At run time it display a message as "driver is not defined"

Chrome version: 83.0.4103.61 (Official Build) (64-bit)
Visual Studio code: 1.45.1

答:
I see what's going on...

first of all, don't call protractor a driver. Don't confuse others and most importantly yourself. Protractor is protractor, period.

second, when you do const driver= require("protractor") your driver variable is available in conf.js, but when you call it from the spec, it's not there, because it's a local variable, not global. As simple as that, this is why you get this error

Third, you don't need to define protractor because it is a global variable, and is available anywhere in your project anyways. The same with browser, element, $, $$ they all are available globally in your project.

Fourth, lets assume for whatever GOOD reason you still want to define something that will be globally available just do global.driver = require('protractor') as described here https://stackoverflow.com/a/31208642/9150146, and then you can call by typing the variable name driver

Body:
I'm a beginner. Can any one guide me?

Tests.js

describe("Test the calculator",()=>{

    it("Addition functionality",function test(){
        driver.browser.get("https://juliemr.github.io/protractor-demo/");
        browser.manage().window().maximize();
        //browser.manage().timeouts().implicitlyWait(3000)

    })
})

Config.js

const driver= require("protractor")

exports.config= {
    browserName: 'chrome',
    framework: "mocha",
    directconnect: true,
    specs: ['./tests.js'],
    mochaOpts: {
        timeout: 0
    }
}

At run time it display a message as "driver is not defined"

Chrome version: 83.0.4103.61 (Official Build) (64-bit)
Visual Studio code: 1.45.1


问:
Call async functions in build method flutter
I need to get the text wrote inside a ".txt" file, save it in a variable and give it to a Text, inside a TextField.
The idea is to write the user input in a ".txt" file so he can read what he wrote when needed on the TextField.

All works, when I read the file it takes the right content but when I store it in a variable to use it Text(var_name...) well what I read on the screen is "Instance of 'Future'".

I know this problem comes from a bad handling of async and future but I would like to really understand why this isn't working.

This is my code :

```<code>Future<String> get _localPath async {
 final directory = await getApplicationDocumentsDirectory();
 return directory.path;
}

Future<File> get _localBio async {
 final path = await _localPath;
 print(path);
 return File('$path/bio.txt');
}

Future<File> _write(String text, String filename) async {
final file = await _localBio;

// Write the file.
return file.writeAsString(text);
}

Future<String> _read() async {
  try {
    final file = await _localBio;
     String body = await file.readAsString();
  // Read the file.
    return body;
  } catch (e) {
  // If encountering an error, return 0.
    return "Can't read";
  }
}

Future<String>_MyRead() async {
 String read_ = await _read();
 print(read_);
 return read_;
}
</code>```

Please write a full answer, I tried a lots of video, forums...Don't just tell me to do var str= _MyRead().then((value) => value);
Maybe it can be the answer but please write 2 more lines because I want to understand why this isn't working.
I took the code from dev official documentation.

答:
You are using an asynchronous value in a rendering process (the build function of a stateful/stateless widget) which is synchronous. You can't just put a Future of String into a place of a String. It won't work. Why? Because it is of a different type, and you need special methods to convert a variable from one type to another.

In this case, you might want to transform this Future into a String asynchronously during the build process. You can use a FutureBuilder for that.

return FutureBuilder<String>(
  future: _myRead,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data);
    } else {
      return Text('awaiting the future');
    }
  },
);
```

If you don't transform this Future into a String to be rendered, it will just be an Instance of Future.

Body:
I need to get the text wrote inside a ".txt" file, save it in a variable and give it to a Text, inside a TextField.
The idea is to write the user input in a ".txt" file so he can read what he wrote when needed on the TextField.

All works, when I read the file it takes the right content but when I store it in a variable to use it Text(var_name...) well what I read on the screen is "Instance of 'Future'".

I know this problem comes from a bad handling of async and future but I would like to really understand why this isn't working.

This is my code :

Future<String> get _localPath async {
 final directory = await getApplicationDocumentsDirectory();
 return directory.path;
}

Future<File> get _localBio async {
 final path = await _localPath;
 print(path);
 return File('$path/bio.txt');
}

Future<File> _write(String text, String filename) async {
final file = await _localBio;

// Write the file.
return file.writeAsString(text);
}

Future<String> _read() async {
  try {
    final file = await _localBio;
     String body = await file.readAsString();
  // Read the file.
    return body;
  } catch (e) {
  // If encountering an error, return 0.
    return "Can't read";
  }
}

Future<String>_MyRead() async {
 String read_ = await _read();
 print(read_);
 return read_;
}

Please write a full answer, I tried a lots of video, forums...Don't just tell me to do var str= _MyRead().then((value) => value);
Maybe it can be the answer but please write 2 more lines because I want to understand why this isn't working.
I took the code from dev official documentation.

Body:
You are using an asynchronous value in a rendering process (the build function of a stateful/stateless widget) which is synchronous. You can't just put a Future of String into a place of a String. It won't work. Why? Because it is of a different type, and you need special methods to convert a variable from one type to another.

In this case, you might want to transform this Future into a String asynchronously during the build process. You can use a FutureBuilder for that.

return FutureBuilder<String>(
  future: _myRead,
  builder: (context, snapshot) {
    if (snapshot.hasData) {
      return Text(snapshot.data);
    } else {
      return Text('awaiting the future');
    }
  },
);

If you don't transform this Future into a String to be rendered, it will just be an Instance of Future.


问:
Best way to decorate databound text in a wpf TextBlock
Let's say I have some multiline text that I'd like to format, and let's also say that it's databound.  So, in XAML:

```<code><TextBlock TextWrap="Wrap">
    <TextBlock.Inlines>
        <Run TextWeight="Bold" Text="{Binding Path=FirstName}" />
        <Run TextStyle="Italic Text="{Binding Path=LastName}" />
    </TextBlock.Inlines>
</TextBlock>
</code>```

Now, this doesn't work because Run's Text isn't a dependency property.  So, I'm wondering, what is the best way to style inline databound text like this?

Thanks in advance.

答: There is a workaround posted here. It basically involves subclassing Run to be bindable. Works though.</p>

OwnerDisplayName: barriovolvo

ContentLicense: CC BY-SA 2.5

Body:
Let's say I have some multiline text that I'd like to format, and let's also say that it's databound.  So, in XAML:

<TextBlock TextWrap="Wrap">
    <TextBlock.Inlines>
        <Run TextWeight="Bold" Text="{Binding Path=FirstName}" />
        <Run TextStyle="Italic Text="{Binding Path=LastName}" />
    </TextBlock.Inlines>
</TextBlock>

Now, this doesn't work because Run's Text isn't a dependency property.  So, I'm wondering, what is the best way to style inline databound text like this?

Thanks in advance.

OwnerDisplayName: Andrew Barrett


问:
Component-level controller in Twig with Symfony PHP
I'm using Symfony 4.x and currently including components in Twig templates like this:

my-template.twig

```<code>{%  include '/components/my-component.twig'
    with {
        data1 : some_array,
        data2 : some_string
    }
%}
</code>```

In the above example, my-component.twig needs data1 and data2 to be passed into it. This means that these two data items need to be available to my-template.twig... which means that I need to make it available in the controller that loads my-template.twig.

```<code>class MyController extends Controller {

   // ...

   $data = [
       'data1' = [ /* some array data */ ];
       'data2' = 'a string';
   ];

    $res = $this->renderView('my-template.twig', $data);

    return new Response($res);
}
</code>```

The issue I'm running into is that I might use my-component.twig in dozens of different templates, each with their own separate controllers. I will need include data1 and data2 in each one of those controllers separately just for the sake of my-component.twig.

I have gotten around this somewhat by including common data objects in a service and including that service in all the controllers that need a particular piece of data, but this isnt ideal either.

What would be ideal is if a particular Twig component was completely self-encapsulated - meaning that I can freely include it in a template and it would automatically grab all of it's own data. That is, the component has it's own dedicated "controller" i.e. PHP code that automatically runs anytime a particular Twig template (component) is rendered without having to indicate this explicitely.

Is something like this possible in Symfony?

答:
If I understand correctly you want to use #render() method in twig.

You create a method in your controller, i.e myComponentRender() and then you could do this instead of doing include

```<code>{{ render(controller(
    'App\\Controller\\MyController::myComponentRender',
    { 'foo': 'bar' }
)) }}
</code>```

I have included the foo parameter just to show you it's possible to pass a paremeter if you needed to (if you wanted to distinguish which page is calling it for example), but you likely do not need to pass anything judging by your example

To clarify, in your myComponentRender() method you need to return $this->render(...)

here's a link actually
https://symfony.com/doc/4.1/templating/embedding_controllers.html

Body:
I'm using Symfony 4.x and currently including components in Twig templates like this:

my-template.twig

{%  include '/components/my-component.twig'
    with {
        data1 : some_array,
        data2 : some_string
    }
%}

In the above example, my-component.twig needs data1 and data2 to be passed into it. This means that these two data items need to be available to my-template.twig... which means that I need to make it available in the controller that loads my-template.twig.

class MyController extends Controller {

   // ...

   $data = [
       'data1' = [ /* some array data */ ];
       'data2' = 'a string';
   ];

    $res = $this->renderView('my-template.twig', $data);

    return new Response($res);
}

The issue I'm running into is that I might use my-component.twig in dozens of different templates, each with their own separate controllers. I will need include data1 and data2 in each one of those controllers separately just for the sake of my-component.twig.

I have gotten around this somewhat by including common data objects in a service and including that service in all the controllers that need a particular piece of data, but this isnt ideal either.

What would be ideal is if a particular Twig component was completely self-encapsulated - meaning that I can freely include it in a template and it would automatically grab all of it's own data. That is, the component has it's own dedicated "controller" i.e. PHP code that automatically runs anytime a particular Twig template (component) is rendered without having to indicate this explicitely.

Is something like this possible in Symfony?

Body:
If I understand correctly you want to use #render() method in twig.

You create a method in your controller, i.e myComponentRender() and then you could do this instead of doing include

{{ render(controller(
    'App\\Controller\\MyController::myComponentRender',
    { 'foo': 'bar' }
)) }}

I have included the foo parameter just to show you it's possible to pass a paremeter if you needed to (if you wanted to distinguish which page is calling it for example), but you likely do not need to pass anything judging by your example

To clarify, in your myComponentRender() method you need to return $this->render(...)

here's a link actually
https://symfony.com/doc/4.1/templating/embedding_controllers.html


问:
Are Google scripts attached to a readonly spreadsheet visible to the user?
I'm working in a Google Script that runs on a a Google Spreadsheet and creates an onEdit() trigger on it.

I would like to know if this script is somehow visible (through Google's interface or any kind of source code inspection) to the users that access the table with readonly permissions.

From my understanding users would not be able to access such a script, since they are suppose to run on Google's server side and not on the client browser. I couldn't find anything about that on App Scripts documentation.

答:
Regarding the use of a web browser developers tools (like right click and selecting Inspect) over a spreadsheet they will not the script code if you do right clic over an spreadsheet but it might show the name of functions called by a custom menu or image with an assigned function, not the code of the onEdit function.

User with view access can't view the code but, if you didn't disable disabled make a copy, they see the code if they made a copy of the spreadsheet.

An alternative to limit users to make a copy of the spreadsheet is to publish your script as an add-on.

Related

How to protect the Apps Script code in a Google spreadsheet?


问:
How to map Postgres JSON data type in DTO and Aggentity class using Springboot and Hibernate
I have a ResponseDto class which looks like as below:

```<code>public static class HealthGoalsHighlight {

    @ApiModelProperty(value = "Total number of eligible users")
    private Long totalEligibleUsers;
    @ApiModelProperty(value = "Total number of registered users")
    private Long totalRegisteredUsers;
    @ApiModelProperty(value = "Total number of users with atleast one goal count")
    private Long totalUsersWithGoal;
    @ApiModelProperty(value = "Top goal name selected by user")
    private String topGoal;
    @ApiModelProperty(value = "Bottom goal name selected by user")
    private String bottomGoal;
  }
</code>```

This DTO was made based upon below table structure:

```<code>health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  total_eligible_users bigint not null,
  total_registered_users bigint not null,
  total_users_with_goal bigint not null,
  top_goal_name varchar(255),
  bottom_goal_name varchar(255),
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);
</code>```

Now the table structure has been changed to as below:

```<code>health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  health_goals_metric_value json null,
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);
</code>```

Basically now all these columns like total_eligible_users, total_registered_users, total_users_with_goal, top_goal_name, bottom_goal_name wil be consolidated to single columnhealth_goals_metric_value as a JSON data type.

How can I write the response DTO for JSON data type column. Also what changes needs to be done in my AggMapper class.

答:
If you can add additional library have a look at https://github.com/vladmihalcea/hibernate-types project, it's super easy with that.

With this library you will end up with code as simple as this

```<code>@Entity
@Table(name = "health_goals")
@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonStringType.class),
    @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class HealthGoal {
    // all other columns
    @Type(type = "json")
    private HealthGoalsHighlight healthGoalsHighlight;

    // getters setters

}
</code>```

And if using the maven add dependency

```<code><dependency>
  <groupId>com.vladmihalcea</groupId>
  <artifactId>hibernate-types-52</artifactId>
  <version>2.9.10</version> // or newer version
</dependency>
</code>```

Body:
I have a ResponseDto class which looks like as below:

public static class HealthGoalsHighlight {

    @ApiModelProperty(value = "Total number of eligible users")
    private Long totalEligibleUsers;
    @ApiModelProperty(value = "Total number of registered users")
    private Long totalRegisteredUsers;
    @ApiModelProperty(value = "Total number of users with atleast one goal count")
    private Long totalUsersWithGoal;
    @ApiModelProperty(value = "Top goal name selected by user")
    private String topGoal;
    @ApiModelProperty(value = "Bottom goal name selected by user")
    private String bottomGoal;
  }

This DTO was made based upon below table structure:

health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  total_eligible_users bigint not null,
  total_registered_users bigint not null,
  total_users_with_goal bigint not null,
  top_goal_name varchar(255),
  bottom_goal_name varchar(255),
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);

Now the table structure has been changed to as below:

health_goals
(
  uid BIGSERIAL NOT NULL CONSTRAINT health_goals_pkey primary key,
  employer_key bigint not null,
  health_goals_metric_value json null,
  created_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_ts TIMESTAMP NOT NULL DEFAULT NOW(),
  created_by varchar(255),
  updated_by varchar(255)
);

Basically now all these columns like total_eligible_users, total_registered_users, total_users_with_goal, top_goal_name, bottom_goal_name wil be consolidated to single columnhealth_goals_metric_value as a JSON data type.

How can I write the response DTO for JSON data type column. Also what changes needs to be done in my AggMapper class.

Body:
If you can add additional library have a look at https://github.com/vladmihalcea/hibernate-types project, it's super easy with that.

With this library you will end up with code as simple as this

@Entity
@Table(name = "health_goals")
@TypeDefs({
    @TypeDef(name = "json", typeClass = JsonStringType.class),
    @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class HealthGoal {
    // all other columns
    @Type(type = "json")
    private HealthGoalsHighlight healthGoalsHighlight;

    // getters setters

}

And if using the maven add dependency

<dependency>
  <groupId>com.vladmihalcea</groupId>
  <artifactId>hibernate-types-52</artifactId>
  <version>2.9.10</version> // or newer version
</dependency>


问:
Nothing happens when running python script from cmd
I recently made a program in Python that I need to launch from the command line.
However, when I run it with "python my_script.py", nothing happens, as if the program was ran but it was empty. Here is an illustration

The 'test.py' file is a basic Hello World program. I started it in my editor , and it worked just fine.
I added python in my PATH as follows :

Python version is 3.7.6, I'm running W10x64 updated.
Does anyone know what the problem is ?
Thanks for your help !

答: just had this issue and the solution was very simple. I had just installed vscode and I forgot I didn't have auto-save enabled. If anyone runs into this issue make sure you save your file before running it</p>


问:
MySQL - Pass input parameter into Cursor query
Is it possible to pass input parameter into Cursor SELECT statement WHERE clause?

For some reason I think it isn't working.

I'm trying to pass _TAG and _ITEM_NAME  into where clause.

```<code>DECLARE cursor_test cursor for SELECT itemid  FROM items WHERE  key_ LIKE "sometext_@_TAG_sometext_@_ITEM_NAME" AND STATUS = '0';
</code>```

Here is the the Stored procedure:

```<code>DELIMITER //
CREATE PROCEDURE getSomething(IN _HOSTNAME VARCHAR(20), _TAG VARCHAR(20), _ITEM_NAME VARCHAR(50))
BEGIN
declare FINISHED BOOL default false;

DECLARE cursor_test cursor for SELECT itemid  FROM items WHERE hostid = @_HOSTID AND key_ LIKE "sometext_@_TAG_sometext_@_ITEM_NAME" AND STATUS = '0';

DECLARE CONTINUE HANDLER for not found set FINISHED := true;

SET @HOSTNAME = _HOSTNAME;

PREPARE STMT1 FROM

"SELECT hostid INTO @_HOSTID FROM hosts  WHERE NAME = ?";

EXECUTE STMT1 USING @HOSTNAME;
DEALLOCATE PREPARE STMT1;

open cursor_test;
   SET @TOTAL_VALUE := 0;
   loop_itemid: loop
        fetch cursor_test into _ITEMID;
        SELECT _ITEMID;
        if FINISHED then
            leave loop_itemid;
        end if;
        SET @TOTAL_VALUE := @TOTAL_VALUE + (SELECT value from history_uint WHERE itemid = _ITEMID ORDER BY clock DESC LIMIT 1);

   end loop loop_itemid;
   SELECT @TOTAL_VALUE;
close cursor_test;

END //
</code>```

答:
Thanks to akina's comment. Using CONCAT in where condition worked.</p>

```<code>WHERE key_ LIKE CONCAT('sometext_', _TAG, '_sometext_', _ITEM_NAME)
</code>```

Body:
Is it possible to pass input parameter into Cursor SELECT statement WHERE clause?

For some reason I think it isn't working.

I'm trying to pass _TAG and _ITEM_NAME  into where clause.

DECLARE cursor_test cursor for SELECT itemid  FROM items WHERE  key_ LIKE "sometext_@_TAG_sometext_@_ITEM_NAME" AND STATUS = '0';

Here is the the Stored procedure:

DELIMITER //
CREATE PROCEDURE getSomething(IN _HOSTNAME VARCHAR(20), _TAG VARCHAR(20), _ITEM_NAME VARCHAR(50))
BEGIN
declare FINISHED BOOL default false;

DECLARE cursor_test cursor for SELECT itemid  FROM items WHERE hostid = @_HOSTID AND key_ LIKE "sometext_@_TAG_sometext_@_ITEM_NAME" AND STATUS = '0';

DECLARE CONTINUE HANDLER for not found set FINISHED := true;

SET @HOSTNAME = _HOSTNAME;

PREPARE STMT1 FROM

"SELECT hostid INTO @_HOSTID FROM hosts  WHERE NAME = ?";

EXECUTE STMT1 USING @HOSTNAME;
DEALLOCATE PREPARE STMT1;

open cursor_test;
   SET @TOTAL_VALUE := 0;
   loop_itemid: loop
        fetch cursor_test into _ITEMID;
        SELECT _ITEMID;
        if FINISHED then
            leave loop_itemid;
        end if;
        SET @TOTAL_VALUE := @TOTAL_VALUE + (SELECT value from history_uint WHERE itemid = _ITEMID ORDER BY clock DESC LIMIT 1);

   end loop loop_itemid;
   SELECT @TOTAL_VALUE;
close cursor_test;

END //

Body:
Thanks to akina's comment. Using CONCAT in where condition worked.

WHERE key_ LIKE CONCAT('sometext_', _TAG, '_sometext_', _ITEM_NAME)


问:
Removing dependencies on MySql
We have a project that at one time must have used a MySql server in the backend. We're all Microsoft SQL Server now, but our project still uses MySql.Data references and code like:

```<code>using (MySqlConnection connection = new MySqlConnection(
</code>```

How do I find and replace all these dependencies so I can drop the references to MySql.Data and MySql.Data.Entity.EF6?

These dependencies are wrecking havoc on deploying an upgraded application to a newer server.

答:
Yes, nbk is right. It was tedious but I just had to remove all usages of the MySql library and replace them with System.Data.SqlClient properties/methods.

I was a bit confused because there was a simultaneous unrelated problem with a nuget package another developer had added to the project that was 'veiling' the errors I was seeing with MySql. :-(

Bob

Title: Removing dependencies on MySql

Body:
We have a project that at one time must have used a MySql server in the backend. We're all Microsoft SQL Server now, but our project still uses MySql.Data references and code like:

using (MySqlConnection connection = new MySqlConnection(

How do I find and replace all these dependencies so I can drop the references to MySql.Data and MySql.Data.Entity.EF6?

These dependencies are wrecking havoc on deploying an upgraded application to a newer server.


问:
Why am I getting "undefined symbol" when I link my static library in my C program?
I'm trying to create a static library to allow me to use a C++ API in my C program. To get started, I'm trying to call an API function called APIName::Api_init(); So far, I have created a "wrapper" library which has the following:

c_api.h:

```<code>#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC int apiname_api_init(char const * user_app_name);
EXTERNC void apiname_api_shutdown();

#undef EXTERNC
</code>```

c_api.cpp:

```<code>#include "c_api.h"
#include "../include/apiname/api.h"   // Link to header files from API provider
int apiname_api_init(char const * user_app_name) {
        return to_return_code(APIName::Api_init(user_app_name));
}

void apiname_api_shutdown() {
        return APIName::api_shutdown();
}
</code>```

I then compile this into an object file called apiwrapper.o using the following command:

```<code>g++  -L../include/libs -lapinameapi  -shared -fPIC -c -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  c_api.cpp -o lapiwrapper.o -lrt
</code>```

where apinameapi is the shared library from the API provider.  This works fine.  I then generate the library file using:

```<code>ar rc libapiwrapper.a apiwrapper.o
</code>```

Again, this is fine.

Now I create my C file (mycode.c), which contains:

```<code>#include "mycode.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int connectToApi() {

  // Init API
  rc = apiname_api_init("programname");

}
</code>```

The header file mycode.h contains:

```<code>#include <stdbool.h>
#include <stdint.h>
#include "c_api.h"
</code>```

(obviously there's other stuff as well, but I've left it out for brevity).

So, I compile my main program using:

```<code>gcc  -Linclude/libs -lapiwrapper  -shared -DKXVER=3 -fPIC -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -Iinclude -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  src/mycode.c -o lib/mycode.so -lrt -Wno-discarded-qualifiers -Wno-incompatible-pointer-types
</code>```

which is also fine. Then, I run the program (this particular file gets loaded by another piece of code), and I get

undefined symbol: apiname_api_init

It seems that it's not finding the function in the library file.  Where am I going wrong? This is my first time building a library, so it's probably something fairly basic.

EDIT: I think the issue may be coming from the fact that the final compilation (which creates mycode.so) is producing a shared object file, and I need that to run on its own (without needing my generated library file to be present as well).  I have to run the final object from another program, so it needs to be standalone. Is there a way I can link it to "bundle" everything together into one final so file?

答:
I tried to reproduce the problem using libssl and libcrypto. So in my case, I need to produce an api_wrapper which uses the functions of libssl and libcrypto and it should be standalone. But unfortunately, as you were asking in the EDIT, two or more shared libraries cannot be bundled together. Please refer to this link Merge multiple .so shared libraries. If your so-called different, specialist language is able to load a static library as well, then you can proceed as follows.

My api_wrappers

apiconnect.c

```<code>#include "apiconnect.h"
#include <openssl/ssl.h>

int api_connect()
{
        SSL_library_init();
        OpenSSL_add_all_algorithms();
        SSL_load_error_strings();

        return 0;
}
</code>```

apiconnect.h

```<code>int api_connect();
</code>```

How I produced libapi.a

As my code is dependent on libssl and libcrypto, I started collecting their static versions from /usr/lib/x86_64-linux-gnu/. Then I extracted the contents of libssl.a and libcrypto.a using ar x library. I got around 700 object files. apiconnect.c is compiled to produce apiconnect.o and added to extracted object files. Then I packed all of them together to produce libapi.a. Below shows my terminal session:

```<code>root@kali:/tmp/apiconnect# ls
apiconnect.c  apiconnect.h  libapi
root@kali:/tmp/apiconnect# cd libapi/
root@kali:/tmp/apiconnect/libapi# cp /usr/lib/x86_64-linux-gnu/libssl.a /usr/lib/x86_64-linux-gnu/libcrypto.a .
root@kali:/tmp/apiconnect/libapi# ar x libssl.a
root@kali:/tmp/apiconnect/libapi# ar x libcrypto.a
root@kali:/tmp/apiconnect/libapi# ls | wc -l
702
root@kali:/tmp/apiconnect/libapi# cd ..
root@kali:/tmp/apiconnect# gcc -c apiconnect.c
root@kali:/tmp/apiconnect# ls
apiconnect.c  apiconnect.h  apiconnect.o  libapi
root@kali:/tmp/apiconnect# cp apiconnect.o libapi/
root@kali:/tmp/apiconnect# cd libapi/
root@kali:/tmp/apiconnect/libapi# ls *.a
libcrypto.a  libssl.a
root@kali:/tmp/apiconnect/libapi# rm *.a
root@kali:/tmp/apiconnect/libapi# ar rc libapi.a *
root@kali:/tmp/apiconnect/libapi# ls libapi.a
libapi.a
</code>```

Testing

Since I don't know different, specialist language and I don't have it, for testing purposes I moved libapi.a and apiconnect.h to another system which does not have libssl or libcrypto installed. I tried to compile a test program which calls api_connect().

Test Program:

```<code>#include "apiconnect.h"

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

Compilation:

```<code>jhansi@poseidon:/tmp/apitesting$ ls
apiconnect.h  libapi.a  test.c
jhansi@poseidon:/tmp/apitesting$ cat test.c
#include "apiconnect.h"

int main()
{
api_connect();
return 0;
}
jhansi@poseidon:/tmp/apitesting$ gcc -L./ test.c -lapi
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_lock_new':
(.text+0x46): undefined reference to `pthread_rwlock_init'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_read_lock':
(.text+0x85): undefined reference to `pthread_rwlock_rdlock'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_write_lock':
(.text+0xa5): undefined reference to `pthread_rwlock_wrlock'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_unlock':
(.text+0xc5): undefined reference to `pthread_rwlock_unlock'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_lock_free':
(.text+0xea): undefined reference to `pthread_rwlock_destroy'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_run_once':
(.text+0x115): undefined reference to `pthread_once'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_init_local':
(.text+0x135): undefined reference to `pthread_key_create'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_set_local':
(.text+0x167): undefined reference to `pthread_setspecific'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_cleanup_local':
(.text+0x187): undefined reference to `pthread_key_delete'
.//libapi.a(threads_pthread.o): In function `openssl_init_fork_handlers':
(.text+0x1e3): undefined reference to `pthread_once'
.//libapi.a(threads_pthread.o): In function `fork_once_func':
(.text+0x16): undefined reference to `pthread_atfork'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_get_local':
(.text+0x153): undefined reference to `pthread_getspecific'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_globallookup':
(.text+0x13): undefined reference to `dlopen'
(.text+0x26): undefined reference to `dlsym'
(.text+0x31): undefined reference to `dlclose'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_bind_func':
(.text+0x1a7): undefined reference to `dlsym'
(.text+0x272): undefined reference to `dlerror'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_load':
(.text+0x2e1): undefined reference to `dlopen'
(.text+0x359): undefined reference to `dlclose'
(.text+0x395): undefined reference to `dlerror'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_pathbyaddr':
(.text+0x452): undefined reference to `dladdr'
(.text+0x4c7): undefined reference to `dlerror'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_unload':
(.text+0x6a4): undefined reference to `dlclose'
collect2: error: ld returned 1 exit status
</code>```

But unfortunately, it turns out to be that the object files we included are dependent on libpthread and libdl, and after including them in the compilation, I was successful to compile and run the program without errors.

```<code>jhansi@poseidon:/tmp/apitesting$ ls
apiconnect.h  libapi.a  test.c
jhansi@poseidon:/tmp/apitesting$ gcc -L./ test.c  -lapi -lpthread -ldl
jhansi@poseidon:/tmp/apitesting$ ls
a.out  apiconnect.h  libapi.a  test.c
jhansi@poseidon:/tmp/apitesting$ ldd a.out
        linux-vdso.so.1 (0x00007ffedd2d7000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fd3d0f30000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fd3d0d2c000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd3d093b000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fd3d1633000)
jhansi@poseidon:/tmp/apitesting$ ./a.out
jhansi@poseidon:/tmp/apitesting$
</code>```

From the output of ldd a.out, it is evident that our executable is not dependent on either of libssl and libcrypto, and of course it is not dependent on libapi.a since it is statically linked. But it is dependent libpthread.so and libdl.so, So if I were you, I would be loading libpthread.so and libdl.so along with libapi.a

I know, what is wrote is specific to libssl and libcrypto, but I hope you will find some luck with the libraries you are trying. Cheers :)

Body:
I'm trying to create a static library to allow me to use a C++ API in my C program. To get started, I'm trying to call an API function called APIName::Api_init(); So far, I have created a "wrapper" library which has the following:

c_api.h:

#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
EXTERNC int apiname_api_init(char const * user_app_name);
EXTERNC void apiname_api_shutdown();

#undef EXTERNC

c_api.cpp:

#include "c_api.h"
#include "../include/apiname/api.h"   // Link to header files from API provider
int apiname_api_init(char const * user_app_name) {
        return to_return_code(APIName::Api_init(user_app_name));
}

void apiname_api_shutdown() {
        return APIName::api_shutdown();
}

I then compile this into an object file called apiwrapper.o using the following command:

g++  -L../include/libs -lapinameapi  -shared -fPIC -c -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -I../include -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  c_api.cpp -o lapiwrapper.o -lrt

where apinameapi is the shared library from the API provider.  This works fine.  I then generate the library file using:

ar rc libapiwrapper.a apiwrapper.o

Again, this is fine.

Now I create my C file (mycode.c), which contains:

#include "mycode.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
int connectToApi() {

  // Init API
  rc = apiname_api_init("programname");

}

The header file mycode.h contains:

#include <stdbool.h>
#include <stdint.h>
#include "c_api.h"

(obviously there's other stuff as well, but I've left it out for brevity).

So, I compile my main program using:

gcc  -Linclude/libs -lapiwrapper  -shared -DKXVER=3 -fPIC -D_LINUX_X86_64 -lpthread -lz -lm -lcrypto -lbz2 -Iinclude -DPROVIDE_LOG_UTILITIES -DTARGET_PLATFORM_LINUX  src/mycode.c -o lib/mycode.so -lrt -Wno-discarded-qualifiers -Wno-incompatible-pointer-types

which is also fine. Then, I run the program (this particular file gets loaded by another piece of code), and I get

undefined symbol: apiname_api_init

It seems that it's not finding the function in the library file.  Where am I going wrong? This is my first time building a library, so it's probably something fairly basic.

EDIT: I think the issue may be coming from the fact that the final compilation (which creates mycode.so) is producing a shared object file, and I need that to run on its own (without needing my generated library file to be present as well).  I have to run the final object from another program, so it needs to be standalone. Is there a way I can link it to "bundle" everything together into one final so file?

Body:
I tried to reproduce the problem using libssl and libcrypto. So in my case, I need to produce an api_wrapper which uses the functions of libssl and libcrypto and it should be standalone. But unfortunately, as you were asking in the EDIT, two or more shared libraries cannot be bundled together. Please refer to this link Merge multiple .so shared libraries. If your so-called different, specialist language is able to load a static library as well, then you can proceed as follows.

My api_wrappers

apiconnect.c

#include "apiconnect.h"
#include <openssl/ssl.h>

int api_connect()
{
        SSL_library_init();
        OpenSSL_add_all_algorithms();
        SSL_load_error_strings();

        return 0;
}

apiconnect.h

int api_connect();

How I produced libapi.a

As my code is dependent on libssl and libcrypto, I started collecting their static versions from /usr/lib/x86_64-linux-gnu/. Then I extracted the contents of libssl.a and libcrypto.a using ar x library. I got around 700 object files. apiconnect.c is compiled to produce apiconnect.o and added to extracted object files. Then I packed all of them together to produce libapi.a. Below shows my terminal session:

root@kali:/tmp/apiconnect# ls
apiconnect.c  apiconnect.h  libapi
root@kali:/tmp/apiconnect# cd libapi/
root@kali:/tmp/apiconnect/libapi# cp /usr/lib/x86_64-linux-gnu/libssl.a /usr/lib/x86_64-linux-gnu/libcrypto.a .
root@kali:/tmp/apiconnect/libapi# ar x libssl.a
root@kali:/tmp/apiconnect/libapi# ar x libcrypto.a
root@kali:/tmp/apiconnect/libapi# ls | wc -l
702
root@kali:/tmp/apiconnect/libapi# cd ..
root@kali:/tmp/apiconnect# gcc -c apiconnect.c
root@kali:/tmp/apiconnect# ls
apiconnect.c  apiconnect.h  apiconnect.o  libapi
root@kali:/tmp/apiconnect# cp apiconnect.o libapi/
root@kali:/tmp/apiconnect# cd libapi/
root@kali:/tmp/apiconnect/libapi# ls *.a
libcrypto.a  libssl.a
root@kali:/tmp/apiconnect/libapi# rm *.a
root@kali:/tmp/apiconnect/libapi# ar rc libapi.a *
root@kali:/tmp/apiconnect/libapi# ls libapi.a
libapi.a

Testing

Since I don't know different, specialist language and I don't have it, for testing purposes I moved libapi.a and apiconnect.h to another system which does not have libssl or libcrypto installed. I tried to compile a test program which calls api_connect().

Test Program:

#include "apiconnect.h"

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

Compilation:

jhansi@poseidon:/tmp/apitesting$ ls
apiconnect.h  libapi.a  test.c
jhansi@poseidon:/tmp/apitesting$ cat test.c
#include "apiconnect.h"

int main()
{
api_connect();
return 0;
}
jhansi@poseidon:/tmp/apitesting$ gcc -L./ test.c -lapi
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_lock_new':
(.text+0x46): undefined reference to `pthread_rwlock_init'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_read_lock':
(.text+0x85): undefined reference to `pthread_rwlock_rdlock'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_write_lock':
(.text+0xa5): undefined reference to `pthread_rwlock_wrlock'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_unlock':
(.text+0xc5): undefined reference to `pthread_rwlock_unlock'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_lock_free':
(.text+0xea): undefined reference to `pthread_rwlock_destroy'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_run_once':
(.text+0x115): undefined reference to `pthread_once'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_init_local':
(.text+0x135): undefined reference to `pthread_key_create'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_set_local':
(.text+0x167): undefined reference to `pthread_setspecific'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_cleanup_local':
(.text+0x187): undefined reference to `pthread_key_delete'
.//libapi.a(threads_pthread.o): In function `openssl_init_fork_handlers':
(.text+0x1e3): undefined reference to `pthread_once'
.//libapi.a(threads_pthread.o): In function `fork_once_func':
(.text+0x16): undefined reference to `pthread_atfork'
.//libapi.a(threads_pthread.o): In function `CRYPTO_THREAD_get_local':
(.text+0x153): undefined reference to `pthread_getspecific'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_globallookup':
(.text+0x13): undefined reference to `dlopen'
(.text+0x26): undefined reference to `dlsym'
(.text+0x31): undefined reference to `dlclose'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_bind_func':
(.text+0x1a7): undefined reference to `dlsym'
(.text+0x272): undefined reference to `dlerror'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_load':
(.text+0x2e1): undefined reference to `dlopen'
(.text+0x359): undefined reference to `dlclose'
(.text+0x395): undefined reference to `dlerror'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_pathbyaddr':
(.text+0x452): undefined reference to `dladdr'
(.text+0x4c7): undefined reference to `dlerror'
.//libapi.a(dso_dlfcn.o): In function `dlfcn_unload':
(.text+0x6a4): undefined reference to `dlclose'
collect2: error: ld returned 1 exit status

But unfortunately, it turns out to be that the object files we included are dependent on libpthread and libdl, and after including them in the compilation, I was successful to compile and run the program without errors.

jhansi@poseidon:/tmp/apitesting$ ls
apiconnect.h  libapi.a  test.c
jhansi@poseidon:/tmp/apitesting$ gcc -L./ test.c  -lapi -lpthread -ldl
jhansi@poseidon:/tmp/apitesting$ ls
a.out  apiconnect.h  libapi.a  test.c
jhansi@poseidon:/tmp/apitesting$ ldd a.out
        linux-vdso.so.1 (0x00007ffedd2d7000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fd3d0f30000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fd3d0d2c000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fd3d093b000)
        /lib64/ld-linux-x86-64.so.2 (0x00007fd3d1633000)
jhansi@poseidon:/tmp/apitesting$ ./a.out
jhansi@poseidon:/tmp/apitesting$

From the output of ldd a.out, it is evident that our executable is not dependent on either of libssl and libcrypto, and of course it is not dependent on libapi.a since it is statically linked. But it is dependent libpthread.so and libdl.so, So if I were you, I would be loading libpthread.so and libdl.so along with libapi.a

I know, what is wrote is specific to libssl and libcrypto, but I hope you will find some luck with the libraries you are trying. Cheers :)


问:
How to get storage location URL of uploaded image on Firebase?
I have that code which I get download URL:

```<code>uploadTask.snapshot.ref.getDownloadURL().then(async function(downloadURL) {

});
</code>```

I need also file storage location URL as well.

答: Your uploadTask.snapshot.ref is a Reference type object.  The API documentation for that object suggests that the toString() method will give you a gs:// URL for that reference.

Body:
I have that code which I get download URL:

uploadTask.snapshot.ref.getDownloadURL().then(async function(downloadURL) {

});

I need also file storage location URL as well.


问:
Git as a backup and Version Control System
I want to use Git to backup my home drive, but I also want to use it as a version control system for projects that will be stored in my home drive.

How would I go about doing that? Do I .gitignore all the projects root folders and make new repositories for them?

Edit:

Ok I explained what I wanted wrongly.  I want to have a history of changes made to my home drive like I can get with Git and I also want to back that up.

答:
For the projects that you want to keep a close track or make some rollback, you can use git in a normal way.

If you want to upload projects with large files and you don't want to be able to checkout to previous commits in order to get old files, you can use git lfs. This will make the .git folder much smaller if to make changes on large files:

Git Large File Storage (LFS) replaces large files such as audio samples, videos, datasets, and graphics with text pointers inside Git, while storing the file contents on a remote server like GitHub.com or GitHub Enterprise.

This solution would be an approach to have a Git Project as a backup. Or even you can use both in a same project, tracking and keep changes only with the files you want.


问:
PHP Multidimensional Array - Copy the value to diffrent column key
i have a problem on this Multidimensional, i need to copy the value to different column key..

here's the array.

```
Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] =>

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] =>
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [4] => [Select Color] = Black
            [5] =>
            [6] =>
        )

)
```

Want this output, is this possible in Multidimensional Array?

```
Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] => **product name 1**

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] => **product name 1**
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [3] => [Select Color] = Black
            [4] =>
            [5] => **product name 2**
        )

)
```

Hope's it possible...

答:
The thing you want to do is this?</p>

```<code>$array[5][3] = $array[3][5]
</code>```

Body:
i have a problem on this Multidimensional, i need to copy the value to different column key..

here's the array.

Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] =>

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] =>
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [4] => [Select Color] = Black
            [5] =>
            [6] =>
        )

)

Want this output, is this possible in Multidimensional Array?

Array
(
    [0] => Array
        (
            [0] => item_type
            [1] => product_id
            [2] => sku
            [3] => name
            [4] => baseimage
            [5] => new_name
        )

    [1] => Array
        (
            [0] => product
            [1] => 12629
            [2] => 5102id.22755
            [3] => product name 1
            [4] => CC22755e.jpg
            [5] =>
        )

    [2] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Red
            [3] => [Select Color] = Red
            [4] =>
            [5] => **product name 1**

        )

    [3] => Array
        (
            [0] => option
            [1] => 12629
            [2] => 22755.Orange
            [3] => [Select Color] = Orange
            [4] =>
            [5] => **product name 1**
        )

    [5] => Array
        (
            [0] => product
            [1] => 12631
            [2] => 0829id.23122
            [3] => product name 2
            [4] => CC23122b.jpg
            [5] =>
        )

    [6] => Array
        (
            [0] => option
            [1] => 12631
            [2] => 23122.Black
            [3] => [Select Color] = Black
            [4] =>
            [5] => **product name 2**
        )

)

Hope's it possible...

Body:
The thing you want to do is this?

$array[5][3] = $array[3][5]


问:
ThreeJS camera.lookAt() has no effect, is there something I'm doing wrong?
In Three.js, I want a camera to be pointed at a point in 3D space.

For this purpose, I tried using the camera.lookAt function like so:

```<code>camera.lookAt(new THREE.Vector3(-100,-100,0));
</code>```

However, I found out that the call has no effect whatsoever. It just does nothing at all. I tried changing the numbers in the vector, and I always get the same look on screen, when it should be changing.

I just found now that if I remove the THREE.TrackballControls I have in my code, the camera.lookAt() works as it should. Is there something wrong with how I use THREE.TrackballControls? This is how I initialize them:

```<code>    controls = new THREE.TrackballControls( camera, renderer.domElement );

    controls.rotateSpeed = 10.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.2;

    controls.noZoom = false;
    controls.noPan = false;

    controls.staticMoving = true;
    controls.dynamicDampingFactor = 1.0;

    var radius = 5;
    controls.minDistance = radius * 1.1;
    controls.maxDistance = radius * 100;

    controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]*/
</code>```

And then in my render function I do:

```<code>function render() {
  controls.update();
  renderer.render(scene, camera);
}
</code>```

Documentation on Three.js is pretty scarce, so I thought I'd ask here. Am I doing something wrong?

答:
I ran into the same problem and was able to make it work by using OrbitControls.target. Below is what I did after declaring a controller.</p>

```<code>    controller = new THREE.OrbitControls(camera, renderer.domElement);
    controller.addEventListener('change', renderer.domElement);
    controller.target = new THREE.Vector3(0, 1, 0);
</code>```

Body:
In Three.js, I want a camera to be pointed at a point in 3D space.

For this purpose, I tried using the camera.lookAt function like so:

camera.lookAt(new THREE.Vector3(-100,-100,0));

However, I found out that the call has no effect whatsoever. It just does nothing at all. I tried changing the numbers in the vector, and I always get the same look on screen, when it should be changing.

I just found now that if I remove the THREE.TrackballControls I have in my code, the camera.lookAt() works as it should. Is there something wrong with how I use THREE.TrackballControls? This is how I initialize them:

    controls = new THREE.TrackballControls( camera, renderer.domElement );

    controls.rotateSpeed = 10.0;
    controls.zoomSpeed = 1.2;
    controls.panSpeed = 0.2;

    controls.noZoom = false;
    controls.noPan = false;

    controls.staticMoving = true;
    controls.dynamicDampingFactor = 1.0;

    var radius = 5;
    controls.minDistance = radius * 1.1;
    controls.maxDistance = radius * 100;

    controls.keys = [ 65, 83, 68 ]; // [ rotateKey, zoomKey, panKey ]*/

And then in my render function I do:

function render() {
  controls.update();
  renderer.render(scene, camera);
}

Documentation on Three.js is pretty scarce, so I thought I'd ask here. Am I doing something wrong?

Body:
I ran into the same problem and was able to make it work by using OrbitControls.target. Below is what I did after declaring a controller.

    controller = new THREE.OrbitControls(camera, renderer.domElement);
    controller.addEventListener('change', renderer.domElement);
    controller.target = new THREE.Vector3(0, 1, 0);