问:
How do i convert a textfile to lower case and find the frequencies of the letters?
I am writing a code that reads a text file and outputs the frequency of the letters. I used a FileInputStream method to read the file and I have no idea on how to convert the uppercase to lower case.

The code runs but only lower case letters are being read. How do i rectify the issue?

答:
This solution won't convert uppercase to lowercase, but can help you to fix your problem.

As char values come from the ASCII table you could do a second loop like that:

```<code>char ch = 'A';

for(int i=0; i<26; i++){
    if(d==ch) {
        f[i] += 1;
    }
    ch++;
}
</code>```

or you can modify your condition in your for loop with:

```<code>if(d==ch || d==(ch-32))
</code>```

You can check the ascii table here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Body:
This solution won't convert uppercase to lowercase, but can help you to fix your problem.

As char values come from the ASCII table you could do a second loop like that:

char ch = 'A';

for(int i=0; i<26; i++){
    if(d==ch) {
        f[i] += 1;
    }
    ch++;
}

or you can modify your condition in your for loop with:

if(d==ch || d==(ch-32))

You can check the ascii table here: https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html


来源: stackexchange

问:
How does keyboard.is_pressed() work in Python?
I'm trying to figure out when i press 'u' only 1 times, why is it pressing 'w' infinite times. Print functions don't work neither but if i delet the  keyboard.press('w') and keyboard.release('w'), the print functions start to work correctly ( it's printing out 4 until i press a button  then it prints out the right number and when i release the button it writes out 4 again)

while True:
    if keyboard.is_pressed('u'):
        keyboard.press('w')
        keyboard.release('w')
        print(0)
    elif keyboard.is_pressed('j'):
        #keyboard.press_and_release('s')
        print(1)
    elif keyboard.is_pressed('k'):
         #keyboard.press_and_release('d')
         print(2)
    elif keyboard.is_pressed('h'):
        #keyboard.press_and_release('a')
        print(3)
    else:
        print(4)
        keyboard.release('w')
```

答:
I know that it was a year ago, but I have found this question today.

Sooo, according to the Keyboard API:

keyboard.press(hotkey) emulates pressing a hotkey on keyboard.

keyboard.release(hotkey) emulates releasing a hotkey on keyboard.

A hotkey is an key number, key name, or combination of two or more keys.

keyboard.press_and_release(hotkey) or keyboard.send(hotkey) emulates pressing and releasing a key or hotkey.

Pressing and releasing behaviour depends on values of do_press and do_release when using keyboard.send().

For example:

```<code>keyboard.send('space', do_press=True, do_release=True)
</code>```

will emulate pressing and releasing space key, but:

```<code>keyboard.send('space', do_press=False, do_release=True)
</code>```

will emulate only releasing space key.

keyboard.is_pressed(key) returns True if a specified key has been pressed, and False otherwise

Hope I've helped!

ContentLicense: CC BY-SA 4.0

Body:
I know that it was a year ago, but I have found this question today.

Sooo, according to the Keyboard API:

keyboard.press(hotkey) emulates pressing a hotkey on keyboard.

keyboard.release(hotkey) emulates releasing a hotkey on keyboard.

A hotkey is an key number, key name, or combination of two or more keys.

keyboard.press_and_release(hotkey) or keyboard.send(hotkey) emulates pressing and releasing a key or hotkey.

Pressing and releasing behaviour depends on values of do_press and do_release when using keyboard.send().

For example:

keyboard.send('space', do_press=True, do_release=True)

will emulate pressing and releasing space key, but:

keyboard.send('space', do_press=False, do_release=True)

will emulate only releasing space key.

keyboard.is_pressed(key) returns True if a specified key has been pressed, and False otherwise

Hope I've helped!


问:
Template function to return containers of unrelated types
I have several containers of unrelated types. I would like to write a templated function to process input values and insert them into the corresponding containers. This is my best try so far:

```<code>#include <iostream>
#include <set>

struct A {
  // Must have operator< or std::less to insert into a std::set
  // Probably a bad idea to do it by memory address
  bool operator<(A const& other) const { return this < &other; }
};
struct B {
  bool operator<(B const& other) const { return this < &other; }
};
struct C {
  bool operator<(C const& other) const { return this < &other; }
};

std::set<A> aSet;
std::set<B> bSet;
std::set<C> cSet;

template
<typename T>
std::set<T>& getSet();

template
<>
std::set<A>& getSet<A>() { return aSet; }

template
<>
std::set<B>& getSet<B>() { return bSet; }

template
<>
std::set<C>& getSet<C>() { return cSet; }

template
<typename T>
void process(T const& value) {
  std::set<T>& specializedSet(getSet<T>());
  specializedSet.insert(value);
}

int main()
{
  // do stuff
  process(A()); process(A()); process(A());
  process(B()); process(B());
  process(C());

  std::cout<<"Set has "<<getSet<A>().size()<<" element(s)\n"
           <<"Set has "<<getSet<B>().size()<<" element(s)\n"
           <<"Set has "<<getSet<C>().size()<<" element(s)"<<std::endl;
}
</code>```

It produces the expected output:

```<code>Set has 3 element(s)
Set has 2 element(s)
Set has 1 element(s)
</code>```

I would strongly prefer not to have to specialize getSet() for every type (I actually have 10), though it's worth it to be able to templatize process(). Ideally I wouldn't even need to declare separate containers aSet, bSet, etc. I could make all these types pointers if that's helpful, though I'd like to stay away from set::set<void*> or similar opaque coding if possible. If this is a duplicate, I apologize, it's a bit tricky to search for.

答:
With C++14, you might use template variable:

```<code>template <typename T>
std::set<T> mySet{};
</code>```

Previously, you might wrap it in template function:

```<code>template <typename T>
std::set<T>& getSet() { static std::set<T> instance; return instance; }
</code>```

Body:
I have several containers of unrelated types. I would like to write a templated function to process input values and insert them into the corresponding containers. This is my best try so far:

#include <iostream>
#include <set>

struct A {
  // Must have operator< or std::less to insert into a std::set
  // Probably a bad idea to do it by memory address
  bool operator<(A const& other) const { return this < &other; }
};
struct B {
  bool operator<(B const& other) const { return this < &other; }
};
struct C {
  bool operator<(C const& other) const { return this < &other; }
};

std::set aSet;
std::set bSet;
std::set<C> cSet;

template
<typename T>
std::set<T>& getSet();

template
<>
std::set& getSet() { return aSet; }

template
<>
std::set& getSet() { return bSet; }

template
<>
std::set<C>& getSet<C>() { return cSet; }

template
<typename T>
void process(T const& value) {
  std::set<T>& specializedSet(getSet<T>());
  specializedSet.insert(value);
}

int main()
{
  // do stuff
  process(A()); process(A()); process(A());
  process(B()); process(B());
  process(C());

  std::cout<<"Set has "<<getSet().size()<<" element(s)\n"
           <<"Set has "<<getSet().size()<<" element(s)\n"
           <<"Set has "<<getSet<C>().size()<<" element(s)"<<std::endl;
}

It produces the expected output:

Set has 3 element(s)
Set has 2 element(s)
Set has 1 element(s)

I would strongly prefer not to have to specialize getSet() for every type (I actually have 10), though it's worth it to be able to templatize process(). Ideally I wouldn't even need to declare separate containers aSet, bSet, etc. I could make all these types pointers if that's helpful, though I'd like to stay away from set::set<void*> or similar opaque coding if possible. If this is a duplicate, I apologize, it's a bit tricky to search for.

Body:
With C++14, you might use template variable:

template <typename T>
std::set<T> mySet{};

Previously, you might wrap it in template function:

template <typename T>
std::set<T>& getSet() { static std::set<T> instance; return instance; }


问:
No Process Is on the Other End of the Pipe
I receive this error when I try to connect to SQL Server 2005. I have enabled TCP/IP, Named Pipes, and restarted the server but that is not working.</p>

答:
in my case :

it was blocked by Symantec AV and firewall

just for trial I have to disable symantec n firewall

i think i'll have further checking

OwnerDisplayName: syalam

ContentLicense: CC BY-SA 2.5


问:
csv file visualization program
I would like to write a program that will open a csv file and create its visualization in a txt file.

I mean:

input:
(this is csv file)

```<code>apple;orange;strawberry
car;warsaw;ansi
</code>```

output in txt file

```<code>apple|orange|strawberry
car  |warsaw|      ansi
</code>```

The idea is that the width of the whole column should be adjusted to the longest expression in it

output in my program

apple|orange|strawberry

|car|warsaw|ansi

|

I have too many separators, and they're not in line

My code:

```<code>#include <stdio.h>
#include <string.h>
#include <string.h>
#define MAXLINE 1000

int how_many_delimiter(char array[]);

int main(void)
{

    FILE *f,*f_2;
    int *size_of_column, counter, hmd, min;
    char corrector[] = ";", rows[MAXLINE], *clipboard;

    f = fopen("ex-5.csv", "r");
    f_2 = fopen("wynik.txt", "w");

    fgets(rows, MAXLINE, f);
    hmd = how_many_delimiter(rows);
    size_of_column = (int*)calloc(hmd,sizeof(int));
    min=10;

    while(fgets(rows, MAXLINE, f))
    {

        clipboard = strtok(rows, corrector);
        counter=0;

        if(strlen(clipboard)>size_of_column[counter])
        {
            size_of_column[counter] = strlen(clipboard);
        }

        while(clipboard!=NULL)
        {
             if(strlen(clipboard)>size_of_column[counter])
             {
                 size_of_column[counter] = strlen(clipboard);
             }
            clipboard = strtok(NULL,corrector);
            counter++;
        }

    }

    fclose(f);
     f = fopen("ex-5.csv", "r");

    while(fgets(rows, MAXLINE, f))
       {

           clipboard = strtok(rows, corrector);
           counter=0;

           while(clipboard!=NULL)
           {
                fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
               clipboard = strtok(NULL,corrector);
               counter++;
           }

       }

    fclose(f);
    fclose(f_2);

    return 0;
}

int how_many_delimiter(char array[])
{
    int counter, i;

    i = 0;
    counter = 1;

    while(array[i]!='\n'&& array[i]!=EOF)
    {
        if(array[i]==';') counter++;
        i++;

    }
    return counter;
}

</code>```

答:
Steps to do this (using an alternate to the "%*s", width method):

Loop to get length of longest word in all categories

int len = strlen(longestWord);

Create format string container char formatStr[80];

Populate formatStr:  sprintf(formatStr, "%s%d%s", "%", len+5, "s");

+5 is arbitrary, change as needed for space between columns.

Use formatStr in the printf() statements for each word.

So for example the longest word shown in your example is strawberry.  My suggestion was to programmatically parse all of the words into buffers, and loop on them, performing strlen() on each to determine longest.  Once you've found, in this case, strawberry, len will be 10, so the format specifier would be "%15s" (if you use my recommended +5).  But the value 15 will be in an int variable by then (say for example int longest.   Since inserting it directly into the normal format string: ( "%longests" ) will not compile, it will need to be packaged up into a format string, formatStr as shown in bullets above, and here:

```<code>sprintf(formatStr, "%s%d%s", "%", longest + 5, "s|");
</code>```

( Will look like:  "%s15s|" )

Once this is done, you can use the format string in the printf statements

This then:

```<code>fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
</code>```

Becomes:

```<code>fprintf(f_2,formatStr, clipboard);
</code>```

(either method will work.)

Title: csv file visualization program

Body:
I would like to write a program that will open a csv file and create its visualization in a txt file.

I mean:

input:
(this is csv file)

apple;orange;strawberry
car;warsaw;ansi

output in txt file

apple|orange|strawberry
car  |warsaw|      ansi

The idea is that the width of the whole column should be adjusted to the longest expression in it

output in my program

apple|orange|strawberry

|car|warsaw|ansi

|

I have too many separators, and they're not in line

My code:

#include <stdio.h>
#include <string.h>
#include <string.h>
#define MAXLINE 1000

int how_many_delimiter(char array[]);

int main(void)
{

    FILE *f,*f_2;
    int *size_of_column, counter, hmd, min;
    char corrector[] = ";", rows[MAXLINE], *clipboard;

    f = fopen("ex-5.csv", "r");
    f_2 = fopen("wynik.txt", "w");

    fgets(rows, MAXLINE, f);
    hmd = how_many_delimiter(rows);
    size_of_column = (int*)calloc(hmd,sizeof(int));
    min=10;

    while(fgets(rows, MAXLINE, f))
    {

        clipboard = strtok(rows, corrector);
        counter=0;

        if(strlen(clipboard)>size_of_column[counter])
        {
            size_of_column[counter] = strlen(clipboard);
        }

        while(clipboard!=NULL)
        {
             if(strlen(clipboard)>size_of_column[counter])
             {
                 size_of_column[counter] = strlen(clipboard);
             }
            clipboard = strtok(NULL,corrector);
            counter++;
        }

    }

    fclose(f);
     f = fopen("ex-5.csv", "r");

    while(fgets(rows, MAXLINE, f))
       {

           clipboard = strtok(rows, corrector);
           counter=0;

           while(clipboard!=NULL)
           {
                fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);
               clipboard = strtok(NULL,corrector);
               counter++;
           }

       }

    fclose(f);
    fclose(f_2);

    return 0;
}

int how_many_delimiter(char array[])
{
    int counter, i;

    i = 0;
    counter = 1;

    while(array[i]!='\n'&& array[i]!=EOF)
    {
        if(array[i]==';') counter++;
        i++;

    }
    return counter;
}

Body:
Steps to do this (using an alternate to the "%*s", width method):

Loop to get length of longest word in all categories

int len = strlen(longestWord);

Create format string container char formatStr[80];

Populate formatStr:  sprintf(formatStr, "%s%d%s", "%", len+5, "s");

+5 is arbitrary, change as needed for space between columns.

Use formatStr in the printf() statements for each word.

So for example the longest word shown in your example is strawberry.  My suggestion was to programmatically parse all of the words into buffers, and loop on them, performing strlen() on each to determine longest.  Once you've found, in this case, strawberry, len will be 10, so the format specifier would be "%15s" (if you use my recommended +5).  But the value 15 will be in an int variable by then (say for example int longest.   Since inserting it directly into the normal format string: ( "%longests" ) will not compile, it will need to be packaged up into a format string, formatStr as shown in bullets above, and here:

sprintf(formatStr, "%s%d%s", "%", longest + 5, "s|");

( Will look like:  "%s15s|" )

Once this is done, you can use the format string in the printf statements

This then:

fprintf(f_2,"%-*s|",size_of_column[counter], clipboard);

Becomes:

fprintf(f_2,formatStr, clipboard);

(either method will work.)


问:
IllegalArgumentException: width and height must be > 0 - error when loading an image using Imgcodecs.imread
I'm using Imgcodecs.imread to upload an image from the phone's gallery to perform a segmentation on this image. However, when creating a bitmap to display it on the screen, I was receiving the error: IllegalArgumentException: width and height must be> 0. I soon realized that Imgcodecs.imread is not opening the image correctly, because I used the log to see the outputs of variable. As below.

```<code>// Load the image
   val srcOriginal = Imgcodecs.imread(currentPhotoPath)
    val src: Mat = srcOriginal.clone()
    Log.i("teste", src.toString())
    Log.i("teste", srcOriginal.toString())
    Log.i("teste", src.rows().toString()+"\n"+ src.cols())
    // Create a blank image of zeros (same dimension as img)
    // It should be grayscale (1 color channel)
    val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

    // This step is manual. The goal is to find the points
    // which create the result we want. I suggest using a
    // tool to get the pixel coordinates.

    // Dictate the area of interest
    for(x in my_canvas.pointsToDrawX.indices) {
            markers.put(
                my_canvas.pointsToDrawX.get(x).toInt(),
                my_canvas.pointsToDrawY.get(x).toInt(),
                255.0
            )
    }

    val src1 = srcOriginal.clone()
    val bmpOut = Bitmap.createBitmap(src1.cols(), src1.rows(), Bitmap.Config.RGB_565)
    //Create Bitmap
    Utils.matToBitmap(src1, bmpOut)
    image.setImageBitmap(bmpOut)
</code>```

Output Log:

Output error:

why is Imgcodecs.imread not opening the image correctly?

答:
You need to add file read and write permissions. For that, you can use the libs: implementation 'com.tbruyelle.rxpermissions2: rxpermissions: 0.9.4@aar' and implementation "io.reactivex.rxjava2: rxandroid: 2.0.1". With this, when opening the image you will check if you have permission to write and read using the code below:

```<code>private fun tryOpenFile() {

    rxPermissions
        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        .subscribe({ granted ->
            if (granted) {
                val getPictureIntent = Intent(Intent.ACTION_GET_CONTENT).apply {
                    type = "image/*"}
                val pickPictureIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                val chooserIntent = Intent.createChooser(getPictureIntent, "Select Image")
                    .apply { putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(pickPictureIntent)) }
                startActivityForResult(chooserIntent, PICK_IMAGE_INTENT)
            } else {
                Toast.makeText(this@MainActivity, "App needs permission to read/write external storage", Toast.LENGTH_SHORT).show()
            }
        })
        .addTo(disposables)

}
</code>```

I hope it works.

Body:
I'm using Imgcodecs.imread to upload an image from the phone's gallery to perform a segmentation on this image. However, when creating a bitmap to display it on the screen, I was receiving the error: IllegalArgumentException: width and height must be> 0. I soon realized that Imgcodecs.imread is not opening the image correctly, because I used the log to see the outputs of variable. As below.

// Load the image
   val srcOriginal = Imgcodecs.imread(currentPhotoPath)
    val src: Mat = srcOriginal.clone()
    Log.i("teste", src.toString())
    Log.i("teste", srcOriginal.toString())
    Log.i("teste", src.rows().toString()+"\n"+ src.cols())
    // Create a blank image of zeros (same dimension as img)
    // It should be grayscale (1 color channel)
    val markers = Mat.zeros(srcOriginal.rows(), srcOriginal.cols(), CvType.CV_32F)

    // This step is manual. The goal is to find the points
    // which create the result we want. I suggest using a
    // tool to get the pixel coordinates.

    // Dictate the area of interest
    for(x in my_canvas.pointsToDrawX.indices) {
            markers.put(
                my_canvas.pointsToDrawX.get(x).toInt(),
                my_canvas.pointsToDrawY.get(x).toInt(),
                255.0
            )
    }

    val src1 = srcOriginal.clone()
    val bmpOut = Bitmap.createBitmap(src1.cols(), src1.rows(), Bitmap.Config.RGB_565)
    //Create Bitmap
    Utils.matToBitmap(src1, bmpOut)
    image.setImageBitmap(bmpOut)

Output Log:

Output error:

why is Imgcodecs.imread not opening the image correctly?

Body:
You need to add file read and write permissions. For that, you can use the libs: implementation 'com.tbruyelle.rxpermissions2: rxpermissions: 0.9.4@aar' and implementation "io.reactivex.rxjava2: rxandroid: 2.0.1". With this, when opening the image you will check if you have permission to write and read using the code below:

private fun tryOpenFile() {

    rxPermissions
        .request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
        .subscribe({ granted ->
            if (granted) {
                val getPictureIntent = Intent(Intent.ACTION_GET_CONTENT).apply {
                    type = "image/*"}
                val pickPictureIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                val chooserIntent = Intent.createChooser(getPictureIntent, "Select Image")
                    .apply { putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(pickPictureIntent)) }
                startActivityForResult(chooserIntent, PICK_IMAGE_INTENT)
            } else {
                Toast.makeText(this@MainActivity, "App needs permission to read/write external storage", Toast.LENGTH_SHORT).show()
            }
        })
        .addTo(disposables)

}

I hope it works.


问:
Display information according to the <selected> location
I'm trying to make like a simple printer manager so i will be able to see all of my printers statuses so far i have managed to display all the data now i want to organize it by location and the error i'm getting is: Cannot read property 'Location' of undefined maybe the reason is that  [(ngModel)] that it is not working properly i think
thank you.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';
import { Values } from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><H2>Print Manager</H2>

<div id="selectCompanyDiv">

  <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
    <label for="">Select location</label>
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each">{{each.location}}</option>
    </select>

  </div>

  <br>
  <br>

  <div>
    <div *ngFor="let value of values" id="mainDiv">
      <!-- <p>{{value.id}},{{value.hostName}},{{value.location}},{{value.manufacturer}},{{value.ip}}</p> -->

      <span>Hostname: {{value.hostName}}</span>
      <br>
      <span>Location: {{value.location}}</span>
      <br>
      <span>Manufacturer: {{value.manufacturer}}</span>
      <br>
      <span>IP: {{value.ip}}</span>
      <br>
      <h2>{{value.location}}</h2>

      <div>

        <div *ngIf="value.hostName==='BROTHERJ480'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframej480" scrolling="no"></iframe>
        </div>

        <div *ngIf="value.hostName==='Brother6530DW'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
        </div>

      </div>

    </div></code>```

答:
You need if condition to show hide related to selected value

in component change

```<code>selectedPrinter: string="Bed Room";
</code>```

then in html

```<code><H2>Print Manager</H2>
<div id="selectCompanyDiv">
  <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
    <label for="">Select location</label>
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " value="{{each.location}}">{{each.location}}</option>
    </select>
  </div>
  <br>
  <br>
<div>
<div *ngFor="let value of values" id="mainDiv">
    <div *ngIf="value.location===selectedPrinter">
      <span>Hostname: {{value.hostName}}</span>
      <br>
      <span>Location: {{value.location}}</span>
      <br>
      <span>Manufacturer: {{value.manufacturer}}</span>
      <br>
      <span>IP: {{value.ip}}</span>
      <br>
      <h2>{{value.location}}</h2>
      <div>
        <div *ngIf="value.hostName==='BROTHERJ480'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframej480" scrolling="no"></iframe>
        </div>
        <div *ngIf="value.hostName==='Brother6530DW'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
        </div>
      </div>
    </div>
</div>
</code>```

Body:
I'm trying to make like a simple printer manager so i will be able to see all of my printers statuses so far i have managed to display all the data now i want to organize it by location and the error i'm getting is: Cannot read property 'Location' of undefined maybe the reason is that  [(ngModel)] that it is not working properly i think
thank you.

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { DomSanitizer } from '@angular/platform-browser';
import { Values } from '../Models/Values';

@Component({
  selector: 'app-value',
  templateUrl: './value.component.html',
  styleUrls: ['./value.component.css']
})

export class ValueComponent implements OnInit {
  selectedPrinter: Values;
  values: any;

  constructor(private http: HttpClient, public sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.getValues();

  }

  getValues() {
    this.http.get('http://localhost:5000/api/values/').subscribe(response => {
      this.values = response;
    }, error => {
      console.log(error);
    })
  }

}

Print Manager

    Select location
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " [ngValue]="each">{{each.location}}</option>
    </select>

      Hostname: {{value.hostName}}

      Location: {{value.location}}

      Manufacturer: {{value.manufacturer}}

      IP: {{value.ip}}

{{value.location}}

Body:
You need if condition to show hide related to selected value

in component change

selectedPrinter: string="Bed Room";

then in html

<H2>Print Manager</H2>
<div id="selectCompanyDiv">
  <div class="col-12 col-md-3 col-xl-2 mt-5 bd-sidebar">
    <label for="">Select location</label>
    <select class="form-control" [(ngModel)]="selectedPrinter">
      <option *ngFor="let each of values " value="{{each.location}}">{{each.location}}</option>
    </select>
  </div>
  <br>
  <br>
<div>
<div *ngFor="let value of values" id="mainDiv">
    <div *ngIf="value.location===selectedPrinter">
      <span>Hostname: {{value.hostName}}</span>
      <br>
      <span>Location: {{value.location}}</span>
      <br>
      <span>Manufacturer: {{value.manufacturer}}</span>
      <br>
      <span>IP: {{value.ip}}</span>
      <br>
      <h2>{{value.location}}</h2>
      <div>
        <div *ngIf="value.hostName==='BROTHERJ480'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframej480" scrolling="no"></iframe>
        </div>
        <div *ngIf="value.hostName==='Brother6530DW'" class="outerFrame">
          <iframe [src]="sanitizer.bypassSecurityTrustResourceUrl('http://'+value.ip+'/general/status.html')" id="inneriframeBrother6530DW" scrolling="no"></iframe>
        </div>
      </div>
    </div>
</div>


问:
Inserting Node at a specific location python
This question is a hackerrank challenge. link here: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list

```<code>"""
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as

 class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

 return back the head of the linked list in the below method.
"""
#This is a "method-only" submission.
#You only need to complete this method.
def InsertNth(head, data, position):
    node = head
    if position == 0:
        node = Node(data)
        node.data = data
        node.next = head
        return node
    else:
        while position > 0:
            node = node.next

            i = node.next
            node.next = Node(data)
            node.next.next = i
            return head
</code>```

my current output is 321024, but I need it to be 310542. Any help is greatly appreciated!

答:
```<code>def insertNodeAtPosition(head, data, position):
    currNode = head
    while position > 1:
        position -= 1
        currNode = currNode.next

    temp = currNode
    node = SinglyLinkedListNode(data)
    node.next = temp.next
    currNode.next = node
    return head
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This question is a hackerrank challenge. link here: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list

"""
Insert Node at a specific position in a linked list
head input could be None as well for empty list
Node is defined as

 class Node(object):

   def __init__(self, data=None, next_node=None):
       self.data = data
       self.next = next_node

 return back the head of the linked list in the below method.
"""
#This is a "method-only" submission.
#You only need to complete this method.
def InsertNth(head, data, position):
    node = head
    if position == 0:
        node = Node(data)
        node.data = data
        node.next = head
        return node
    else:
        while position > 0:
            node = node.next

            i = node.next
            node.next = Node(data)
            node.next.next = i
            return head

my current output is 321024, but I need it to be 310542. Any help is greatly appreciated!


问:
Converting lines in to columns
I used this  script to generate the below output from server show /system1/swid*" |egrep -w "name|VersionString" | sed 's/^[ \t]*//;s/[ \t]*$//', but I am unable to convert these lines into columns. please help me to get some idea to convert this into columns.

```<code>name=iLO
VersionString=2.73 Feb 11 2020
name=System ROM
VersionString=P89 v2.76 (10/21/2019)
name=Redundant System ROM
VersionString=P89 v2.64 (10/17/2018)
name=Intelligent Provisioning
VersionString=2.70.75
</code>```

Required output

```<code>    name=iLO                            name=System ROM                             name=Redundant System ROM                   name=Intelligent Provisioning
VersionString=2.73 Feb 11 2020      VersionString=P89 v2.76 (10/21/2019)        VersionString=P89 v2.64 (10/17/2018)        VersionString=2.70.75
</code>```

image

答:
You can do this :

```<code>awk '
/^name/{ names= $0 ";" names}
!/^name/ && NF{data= $0 ";" data}
END { printf("%s\n%s\n",names,data)}' input.txt
</code>```

Which will print :

```<code>name=Intelligent Provisioning;name=Redundant System ROM;name=System ROM;name=iLO;
VersionString=2.70.75;VersionString=P89 v2.64 (10/17/2018);VersionString=P89 v2.76 (10/21/2019);VersionString=2.73 Feb 11 2020;
</code>```

Hope it is useful for you.

Title: Converting lines in to columns

Body:
I used this  script to generate the below output from server show /system1/swid*" |egrep -w "name|VersionString" | sed 's/^[ \t]*//;s/[ \t]*$//', but I am unable to convert these lines into columns. please help me to get some idea to convert this into columns.

name=iLO
VersionString=2.73 Feb 11 2020
name=System ROM
VersionString=P89 v2.76 (10/21/2019)
name=Redundant System ROM
VersionString=P89 v2.64 (10/17/2018)
name=Intelligent Provisioning
VersionString=2.70.75

Required output

    name=iLO                            name=System ROM                             name=Redundant System ROM                   name=Intelligent Provisioning
VersionString=2.73 Feb 11 2020      VersionString=P89 v2.76 (10/21/2019)        VersionString=P89 v2.64 (10/17/2018)        VersionString=2.70.75

image

Body:
You can do this :

awk '
/^name/{ names= $0 ";" names}
!/^name/ && NF{data= $0 ";" data}
END { printf("%s\n%s\n",names,data)}' input.txt

Which will print :

name=Intelligent Provisioning;name=Redundant System ROM;name=System ROM;name=iLO;
VersionString=2.70.75;VersionString=P89 v2.64 (10/17/2018);VersionString=P89 v2.76 (10/21/2019);VersionString=2.73 Feb 11 2020;

Hope it is useful for you.


问:
Difference between two date strings in java
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

```<code>public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }
</code>```

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

```<code>try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }
</code>```

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.

答:
you'll never get a difference of exactly 3 milliseconds between two dates gotten from a yyyy/MM/dd formatted string (maximum accuracy will be 24 hours)

if you want 3 days difference use 24*60*60*1000 for a factor to scale the values

Body:
I am trying to calculate difference between two date strings both of which are taken from user through a html form in format (yyyy/MM/dd)
Code:

public boolean diffDate() throws ParseException
 {
     date1 = getissuedate();
     date2 = getduedate();
         Calendar cal1 = Calendar.getInstance();
    Calendar cal2 = Calendar.getInstance();
    SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy/MM/dd");
    SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy/MM/dd");
Date date_old = formatter1.parse(date1);
Date date_new = formatter2.parse(date2);
long milis1 = date_old.getTime();
long milis2 = date_new.getTime();

long diff = milis2 - milis1;

    if( diff<3 || diff>3)
    {
        return true;
    }
    else
    {
        return false;
    }
 }

Now am using an if condition to report error in my webpage if difference between the date is not equal to 3.
Code:

try {
        if(diffDate())
        {
            errors.add("duedate", new ActionMessage("error.duedate.required"));
        }
    } catch (ParseException ex) {
        Logger.getLogger(IssueBookForm.class.getName()).log(Level.SEVERE, null, ex);
    }

where error.duedate.required is mapped to "check date"

So, the issue is "check date" error is printed for any value of both date string.


问:
Why the step "Get_from_session" does not work in ios with corvertigo server 7.7?
We are storing values in the aplication session using only “set in session” and “get from session” steps.

We have several apps in a production environment with a Convertigo Server 7.4. whit convertigo project in ionic 3 and angular 5, a and we have migrated to convertigo server 7.7. convertigo project in ionic 5 and angular 8. We have configured the properties"Context timeout" and "HTTP session timeout" in 3600 secons.

When we test on an android device everything works correctly, but when we test on an ios device it has no value in expression of the step "Get from session"

enter image description here

The value between the step "Set_Token" in "Login" sequence and the step "Get_token" in "ServicesData" sequence is lost, however if the step "Get from session" is in the sequence "Login" after step "Set_token", it works and it only happens in ios.

Comparing logs between the ios app and the android app the difference I see is that in ios it shows:
enter image description here
enter image description here
and on android it shows:
enter image description here

Why with convertigo server 7.7 the step "Get_from_session" works on android and not on ios?

Thank you

答:
Steps in a sequence are executed on the server and are platform indepedendants.

Make sure that calls to Login and ServicesData sequences are made on the same JSESSIONID.
For instance, in the iOS logs, the Login sequence is called using the 56B4DA...D34D JSESSIONID and the ServicesData with 85CD3D...0A19, so this is normal that the Step "GetFromSession" in ServicesData does not retrieve value from Step "SetInSession" from Login sequence.

You must preserve the same session between sequences calls.

Hope that Helps.

Regards,

Gregory.


问:
How to call Python Script from class in Symfony
I'm wondering how I can call a python script from a class in Symfony. I keep getting an error that it can't locate the script.

```<code>May 28 13:54:13 |INFO | PHP    python: can't open file 'Request.py': [Errno 2] No such file or directory
</code>```

The code is as followed:

```<code>        $python = shell_exec("python Request.py");
        echo $python;
</code>```

The script is outside the symfony project, but I'm not quite sure how to get the path relative to the class file.

答:
```<code>$path = shell_exec("pwd");
echo $path;
</code>```

Should show you your current directory.

And I would suggest using Symfony Process Component https://symfony.com/doc/current/components/process.html

Body:
I'm wondering how I can call a python script from a class in Symfony. I keep getting an error that it can't locate the script.

May 28 13:54:13 |INFO | PHP    python: can't open file 'Request.py': [Errno 2] No such file or directory

The code is as followed:

        $python = shell_exec("python Request.py");
        echo $python;

The script is outside the symfony project, but I'm not quite sure how to get the path relative to the class file.

Body:
$path = shell_exec("pwd");
echo $path;

Should show you your current directory.

And I would suggest using Symfony Process Component https://symfony.com/doc/current/components/process.html


问:
How can I make all the points on a dense plot visible in matplotlib?
I'm using this basic code to display a plot using matplotlib. The lists for the x and y axis are large.

plt.plot(r,trajectory,"k.")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()
```

<p>How can I format my plot better to view all the details? </p>

<p>With the above configuration what I see is</p>

<p><img src="https://i.stack.imgur.com/VEFsP.png" alt="Initial"></p>

<p>But what I want to get to is something that looks like this with each point visible (atleast high enough resolution to zoom in)</p>

<p><img src="https://i.stack.imgur.com/trN4q.png" alt="final"></p>

<p>Update:
I found that tuning the available parameters iteratively can yield good results. Used a combination of the answers below to understand parameters and arrive at this configuration.</p>

<pre class="lang-py prettyprint-override"><code>f = plt.figure(figsize=(6,4),dpi=300)
plt.plot(r, trajectory, "k,", markersize=0.01, mew=0)
f.savefig("bifurcation_diag.png")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()
</code>```

答:
You can use a smaller marker size. The problem is that there are so many data points that they are overlapping resulting in a dark image.

I explain this below using an example dataset. The left figure shows default marker size and the right figure shows the same data with a smaller marker size using argument ms=1. You can choose ms=2, ms=3 etc. as per your need.

```<code>import numpy as np

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))

# Default marker size
ax1.plot(np.random.randint(0, 100, 10000), np.random.randint(0, 100, 10000), 'k.')

# Smaller marker size `ms=1`
ax2.plot(np.random.randint(0, 100, 10000), np.random.randint(0, 100, 10000), 'k.', ms=1)
</code>```

Body:
I'm using this basic code to display a plot using matplotlib. The lists for the x and y axis are large.

plt.plot(r,trajectory,"k.")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()

How can I format my plot better to view all the details?

With the above configuration what I see is

But what I want to get to is something that looks like this with each point visible (atleast high enough resolution to zoom in)

Update:
I found that tuning the available parameters iteratively can yield good results. Used a combination of the answers below to understand parameters and arrive at this configuration.

f = plt.figure(figsize=(6,4),dpi=300)
plt.plot(r, trajectory, "k,", markersize=0.01, mew=0)
f.savefig("bifurcation_diag.png")
plt.title("Bifurcation diagram")
plt.xlabel("R")
plt.ylabel("Xn")
plt.show()

Body:
You can use a smaller marker size. The problem is that there are so many data points that they are overlapping resulting in a dark image.

I explain this below using an example dataset. The left figure shows default marker size and the right figure shows the same data with a smaller marker size using argument ms=1. You can choose ms=2, ms=3 etc. as per your need.

import numpy as np

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4))

# Default marker size
ax1.plot(np.random.randint(0, 100, 10000), np.random.randint(0, 100, 10000), 'k.')

# Smaller marker size `ms=1`
ax2.plot(np.random.randint(0, 100, 10000), np.random.randint(0, 100, 10000), 'k.', ms=1)


问:
How to change text color when custom cursor is on hover
When red cursor is hover on Works text, i want to change the Works text color black to blue and text will be zoom In on that red cursor area. anyone suggest me how to do this in JavaScript

   jQuery(document).ready(function() {
        var mouseX = 0, mouseY = 0;
        var xp = 0, yp = 0;
        $(document).mousemove(function(e){
            mouseX = e.pageX - 30;
            mouseY = e.pageY - 30;
        });
        setInterval(function(){
            xp += ((mouseX - xp)/6);
            yp += ((mouseY - yp)/6);
            $(".cursor").css({left: xp +'px', top: yp +'px'});
        }, 20);
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> h1{
        text-align: center;
        font-size: 5rem;
        margin-top: 20%;
    }
    .cursor{
        position: absolute;
        background: red;
        width: 100px;
        height: 100px;
        border-radius: 50px;
    }</code>```

Works

```

答:
You should add pointer-events: none; to the cursor, so it doesn't interefer with the element below.
And then add Hover or whatever pseudoclass you need to colorize it.

jQuery(document).ready(function() {
        var mouseX = 0, mouseY = 0;
        var xp = 0, yp = 0;
        $(document).mousemove(function(e){
            mouseX = e.pageX - 30;
            mouseY = e.pageY - 30;
        });
        setInterval(function(){
            xp += ((mouseX - xp)/6);
            yp += ((mouseY - yp)/6);
            $(".cursor").css({left: xp +'px', top: yp +'px'});
        }, 20);
    });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1{
        text-align: center;
        font-size: 5rem;
        margin-top: 20%;
    }

    h1:hover {
    color: red;
}
    .cursor{
        position: absolute;
        background: red;
        width: 100px;
        height: 100px;
        border-radius: 50px;
        pointer-events: none;
    }</code>```

Works

```

Body:
When red cursor is hover on Works text, i want to change the Works text color black to blue and text will be zoom In on that red cursor area. anyone suggest me how to do this in JavaScript

   jQuery(document).ready(function() {
        var mouseX = 0, mouseY = 0;
        var xp = 0, yp = 0;
        $(document).mousemove(function(e){
            mouseX = e.pageX - 30;
            mouseY = e.pageY - 30;
        });
        setInterval(function(){
            xp += ((mouseX - xp)/6);
            yp += ((mouseY - yp)/6);
            $(".cursor").css({left: xp +'px', top: yp +'px'});
        }, 20);
    });

 h1{
        text-align: center;
        font-size: 5rem;
        margin-top: 20%;
    }
    .cursor{
        position: absolute;
        background: red;
        width: 100px;
        height: 100px;
        border-radius: 50px;
    }

Works

Body:
You should add pointer-events: none; to the cursor, so it doesn't interefer with the element below.
And then add Hover or whatever pseudoclass you need to colorize it.

jQuery(document).ready(function() {
        var mouseX = 0, mouseY = 0;
        var xp = 0, yp = 0;
        $(document).mousemove(function(e){
            mouseX = e.pageX - 30;
            mouseY = e.pageY - 30;
        });
        setInterval(function(){
            xp += ((mouseX - xp)/6);
            yp += ((mouseY - yp)/6);
            $(".cursor").css({left: xp +'px', top: yp +'px'});
        }, 20);
    });

h1{
        text-align: center;
        font-size: 5rem;
        margin-top: 20%;
    }

    h1:hover {
    color: red;
}
    .cursor{
        position: absolute;
        background: red;
        width: 100px;
        height: 100px;
        border-radius: 50px;
        pointer-events: none;
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Works</h1>
<div class="cursor">


问:
Currently the function is supposed to take 1 required parameter, and 2 option.... How to fix?
Currently the function is supposed to take 1 required parameter, and 2 optional parameters, however the code doesn’t work. Fix the code so that it passes the test. This should only require changing one line of code.

```<code>def waste(var = "Water", mar, marble = "type"):
    final_string = var + " " + marble + " " + mar
    return final_string
</code>```

SyntaxError: non-default argument follows default argument on line 2
I changed a lot of time fixing it but no result
Thanks!

答:
You must have positional arguments first, then named arguments in the function signature in order for the function to work:

```<code>def waste(mar, var="Water", marble="type"):
    final_string = var + " " + marble + " " + mar
    return final_string
</code>```

You can simplify the function a bit, by returning a f-string (requires Python version >= 3.6):

```<code>def waste(mar, var="Water", marble="type"):
    return f"{var} {marble} {mar}"
</code>```

Body:
Currently the function is supposed to take 1 required parameter, and 2 optional parameters, however the code doesn’t work. Fix the code so that it passes the test. This should only require changing one line of code.

def waste(var = "Water", mar, marble = "type"):
    final_string = var + " " + marble + " " + mar
    return final_string

SyntaxError: non-default argument follows default argument on line 2
I changed a lot of time fixing it but no result
Thanks!

Body:
You must have positional arguments first, then named arguments in the function signature in order for the function to work:

def waste(mar, var="Water", marble="type"):
    final_string = var + " " + marble + " " + mar
    return final_string

You can simplify the function a bit, by returning a f-string (requires Python version >= 3.6):

def waste(mar, var="Water", marble="type"):
    return f"{var} {marble} {mar}"


问:
How can i use trust and key store into cacerts in ruby?
As java security has cacerts file and provide to store trust and key. is ruby provide same security as java provide.let me know any ideas to do create secure connection to websocket server.</p>

答:
welcome to Stack Overflow.

I understand you're coming from the Java world. However, it's difficult to tell what exactly you are needing.

If you are wondering about how TLS/SSL certificates are handled in Ruby, please check the answer at https://stackoverflow.com/a/9238221/2658159.

If you are wondering about how the server should be set up (you write "create secure connection to websocket..."), that is not a Ruby-specific question. You'll want to think about posting another question, with the appropriate tags, and a clear, reproducible example of the specific question in mind.


问:
Have a problem on how to set a default class
In the shape.cpp I need set a default constructor for class Point, But I don't know how to do that.

Thanks

```<code>Point::Point(double _f, double _g){
    f = 1;
    g = 1;

}
Rectangle::Rectangle():Point(1, 1) {
    x = 1;
    y = 1;

}
Rectangle::Rectangle( Point q, double l, double w):x(l),y(w),Point(q) {
}

</code>```

答:
```<code>#include <iostream>
using namespace std;

class Point{
    int f,g;                           //declaring point(f,g)
    public :
    Point();                           //This will be your default constructor
    Point(double _f,double _g);        // Constructor for class Point
    int getf(){                        //just for purpose of display function() below. You can remove this once you understand code.
        return f;
    }
    int getg(){                        //just for purpose of display function() below. You can remove this once you understand code.
        return g;
    }
};

class Rectangle{
    double l,w;                         //declaring variable to store length and width of Rectangle
    Point pt;                           //whatever your use of point is
    public :
    Rectangle(Point q,double l,double w); //constructor for class Rectangle
    void display(){                     // displaying the class...just for demonstration
        cout<<"l = "<<l<<endl;
        cout<<"w = "<<w<<endl;
        cout<<"pt = ("<<pt.getf()<<", "<<pt.getg()<<")\n";
    }
};
//Defining the constructor of class Point
Point::Point(double _f, double _g):f(_f),g(_g){}     // I have used initialiser list here

Point::Point():f(0),g(0){}     // (your needed default constructor)

Rectangle::Rectangle( Point q, double l, double w):l(l),w(w),pt(q) {} //Defining the constructor of class Rectangle

int main()
{   //Demonstrating object creation and displaying of object r of class rectangle
    Point p(1,2);
    Rectangle r(p,5,10);
    r.display();
}
</code>```

I have attached the code that would help you understand about constructors and how to define them.

Hope this solves your question !

Body:
In the shape.cpp I need set a default constructor for class Point, But I don't know how to do that.

Thanks

Point::Point(double _f, double _g){
    f = 1;
    g = 1;

}
Rectangle::Rectangle():Point(1, 1) {
    x = 1;
    y = 1;

}
Rectangle::Rectangle( Point q, double l, double w):x(l),y(w),Point(q) {
}

Body:
#include <iostream>
using namespace std;

class Point{
    int f,g;                           //declaring point(f,g)
    public :
    Point();                           //This will be your default constructor
    Point(double _f,double _g);        // Constructor for class Point
    int getf(){                        //just for purpose of display function() below. You can remove this once you understand code.
        return f;
    }
    int getg(){                        //just for purpose of display function() below. You can remove this once you understand code.
        return g;
    }
};

class Rectangle{
    double l,w;                         //declaring variable to store length and width of Rectangle
    Point pt;                           //whatever your use of point is
    public :
    Rectangle(Point q,double l,double w); //constructor for class Rectangle
    void display(){                     // displaying the class...just for demonstration
        cout<<"l = "<<l<<endl;
        cout<<"w = "<<w<<endl;
        cout<<"pt = ("<<pt.getf()<<", "<<pt.getg()<<")\n";
    }
};
//Defining the constructor of class Point
Point::Point(double _f, double _g):f(_f),g(_g){}     // I have used initialiser list here

Point::Point():f(0),g(0){}     // (your needed default constructor)

Rectangle::Rectangle( Point q, double l, double w):l(l),w(w),pt(q) {} //Defining the constructor of class Rectangle

int main()
{   //Demonstrating object creation and displaying of object r of class rectangle
    Point p(1,2);
    Rectangle r(p,5,10);
    r.display();
}

I have attached the code that would help you understand about constructors and how to define them.

Hope this solves your question !


问:
Easy way to clamp Neural Network outputs between 0 and 1?
So I'm working on writing a GAN neural network and I want to set my network's output to 0 if it is less than 0 and 1 if it is greater than 1 and leave it unchanged otherwise. I'm pretty new to tensorflow, but I don't know of any tensorflow function or activation to do this without unwanted side effects. So I made my loss function so it calculates the loss as if the output was clamped, with this code:

```<code>def discriminator_loss(real_output, fake_output):
    real_output_clipped = min(max(real_output.numpy()[0],
    0), 1)
    fake_output_clipped = min(max(fake_output.numpy()[0],
    0), 1)

    real_clipped_tensor =
    tf.Variable([[real_output_clipped]], dtype = "float32")
    fake_clipped_tensor =
    tf.Variable([[fake_output_clipped]], dtype = "float32")

    real_loss = cross_entropy(tf.ones_like(real_output),
    real_clipped_tensor)
    fake_loss = cross_entropy(tf.zeros_like(fake_output),
    fake_clipped_tensor)

    total_loss = real_loss + fake_loss
    return total_loss
</code>```

but I get this error:

```<code>ValueError: No gradients provided for any variable: ['dense_50/kernel:0', 'dense_50/bias:0', 'dense_51/kernel:0', 'dense_51/bias:0', 'dense_52/kernel:0', 'dense_52/bias:0', 'dense_53/kernel:0', 'dense_53/bias:0'].
</code>```

Does anyone know a better way to do this, or a way to fix this error?

Thanks!

答:
You can apply a ReLU layer from Keras as your final layer and set max_value=1.0. For example:

```<code>model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(32, input_shape=(16,)))
model.add(tf.keras.layers.Dense(32))
model.add(tf.keras.layers.ReLU(max_value=1.0))
</code>```

You can read more about it here: https://www.tensorflow.org/api_docs/python/tf/keras/layers/ReLU

Body:
So I'm working on writing a GAN neural network and I want to set my network's output to 0 if it is less than 0 and 1 if it is greater than 1 and leave it unchanged otherwise. I'm pretty new to tensorflow, but I don't know of any tensorflow function or activation to do this without unwanted side effects. So I made my loss function so it calculates the loss as if the output was clamped, with this code:

def discriminator_loss(real_output, fake_output):
    real_output_clipped = min(max(real_output.numpy()[0],
    0), 1)
    fake_output_clipped = min(max(fake_output.numpy()[0],
    0), 1)

    real_clipped_tensor =
    tf.Variable([[real_output_clipped]], dtype = "float32")
    fake_clipped_tensor =
    tf.Variable([[fake_output_clipped]], dtype = "float32")

    real_loss = cross_entropy(tf.ones_like(real_output),
    real_clipped_tensor)
    fake_loss = cross_entropy(tf.zeros_like(fake_output),
    fake_clipped_tensor)

    total_loss = real_loss + fake_loss
    return total_loss

but I get this error:

ValueError: No gradients provided for any variable: ['dense_50/kernel:0', 'dense_50/bias:0', 'dense_51/kernel:0', 'dense_51/bias:0', 'dense_52/kernel:0', 'dense_52/bias:0', 'dense_53/kernel:0', 'dense_53/bias:0'].

Does anyone know a better way to do this, or a way to fix this error?

Thanks!

Body:
You can apply a ReLU layer from Keras as your final layer and set max_value=1.0. For example:

model = tf.keras.Sequential()
model.add(tf.keras.layers.Dense(32, input_shape=(16,)))
model.add(tf.keras.layers.Dense(32))
model.add(tf.keras.layers.ReLU(max_value=1.0))

You can read more about it here: https://www.tensorflow.org/api_docs/python/tf/keras/layers/ReLU


问:
Minlength error in template driven form in angular 8
I am getting below error when i click the submit button.

```<code>ERROR TypeError: Cannot read property 'minlength' of null
</code>```

I do not know why i am getting this error.So How to resolve this issue.

app.component.html:

```<code><form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>
<div class="form-group">
                <label for="categoryName">Category Name:</label>
                <input type="text" class="form-control" name="categoryName" [(ngModel)]="cate.categoryName" minlength="5" #categoryname="ngModel" [ngClass]="{ 'is-invalid': f.submitted && categoryName.invalid }" required/>
                <div *ngIf="f.submitted && categoryName.invalid" class="invalid-feedback">
                    <div *ngIf="categoryName.errors.required">
                        Category Name is required
                    </div>
                </div>
                <div *ngIf="categoryName?.touched && categoryName?.errors.minlength" class="invalid-feedback">
                    Category Name must be at least 5 characters long.
                </div>
            </div>
</form>
</code>```

答:
Since you removed the origin of the error, I'm assuming the error is coming from

This line:

```

<p>Here <code>categoryName?.errors</code> is null and you tried to access <code>minlength</code> on this null value.</p>

<p>To avoid this error, add a <code>?</code> operator before <code>.minlength</code> like:</p>

<pre class="lang-html prettyprint-override"><code><div *ngIf="categoryName?.touched && categoryName?.errors?.minlength" class="invalid-feedback">
</code>```

Body:
I am getting below error when i click the submit button.

ERROR TypeError: Cannot read property 'minlength' of null

I do not know why i am getting this error.So How to resolve this issue.

app.component.html:

<form name="form" (ngSubmit)="f.form.valid && onSubmit()" #f="ngForm" novalidate>

                Category Name:
                <input type="text" class="form-control" name="categoryName" [(ngModel)]="cate.categoryName" minlength="5" #categoryname="ngModel" [ngClass]="{ 'is-invalid': f.submitted && categoryName.invalid }" required/>

                        Category Name is required

                    Category Name must be at least 5 characters long.

</form>

Body:
Since you removed the origin of the error, I'm assuming the error is coming from

This line:

<div *ngIf="categoryName?.touched && categoryName?.errors.minlength" class="invalid-feedback">

Here categoryName?.errors is null and you tried to access minlength on this null value.

To avoid this error, add a ? operator before .minlength like:

<div *ngIf="categoryName?.touched && categoryName?.errors?.minlength" class="invalid-feedback">


问:
Python Output Snowflake Connector To CSV
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this. Currently, my code example looks like:

```<code>query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)
</code>```

Is there a way for me to print the output of the query, like maybe print(query_output) and then also write it to csv like query_output.to_csv(path)?

答:
You can do like this :</p>
```<code>import csv
.....
.....
.....
rows = cur.fetchall()
column_names = [i[0] for i in cur.description]
with open('samplefile.csv', 'w') as fp:
  myFile = csv.writer(fp, lineterminator = '\n')
  myFile.writerow(column_names)
  myFile.writerows(rows)
</code>```

Body:
I currently am trying to print the output of a snowflake connector query and write it to csv, but I'm having issues doing this. Currently, my code example looks like:

query = '''SELECT TOP 10 * FROM TABLE;'''

conn = snowflake.connector.connect(user='XXXX',
                                   password='XXXX',
                                   account='XXXX')

query_output = conn.cursor().execute(query)

Is there a way for me to print the output of the query, like maybe print(query_output) and then also write it to csv like query_output.to_csv(path)?

Body:
You can do like this :

import csv
.....
.....
.....
rows = cur.fetchall()
column_names = [i[0] for i in cur.description]
with open('samplefile.csv', 'w') as fp:
  myFile = csv.writer(fp, lineterminator = '\n')
  myFile.writerow(column_names)
  myFile.writerows(rows)


问:
Power Efficient Software Coding
In a typical handheld/portable embedded system device Battery life is a major concern in design of H/W, S/W and the features the device can support. From the Software programming perspective, one is aware of MIPS, Memory(Data and Program) optimized code.
I am aware of the H/W Deep sleep mode, Standby mode that are used to clock the hardware at lower Cycles or turn of the clock entirel to some unused circutis to save power, but i am looking for some ideas from that point of view:

Wherein my code is running and it needs to keep executing, given this how  can I write the code "power" efficiently so as to consume minimum watts?

Are there any special programming constructs, data structures, control structures which i should look at to achieve minimum power consumption for a given functionality.

Are there any s/w high level design considerations which one should keep in mind at time of code structure design, or during low level design to make the code as power efficient(Least power consuming) as possible?

答: Look at what your compiler generates, particularly for hot areas of code.</p>

OwnerDisplayName: goldenmean

Title: Power Efficient Software Coding

LastEditorDisplayName: Tim

OwnerDisplayName: Ned


问:
Dynamically hooking up a class having different possible constructors
Let's say I have two classes that look like this:

```<code>public class ByteFilter
{
    private Func <int, byte[]> readBytes;
    private Action<byte[]> writeBytes;

    public ByteFilter(Func <int, byte[]> readBytes, Action<byte[]> writeBytes)
    {
        this.readBytes = readBytes;
        this.writeBytes = writeBytes;
    }
}

public class PacketFilter
{
    private Func<Packet> readPacket;
    private Action<Packet> writePacket;

    Public PacketFilter(Func<Packet> readPacket, Action<Packet> writePacket)
    {
        this.readBytes = readPacket;
        this.writeBytes = writePacket;
    }
}
</code>```

Either class may be instantiated at runtime (via Activator.CreateInstance) to perform a filtering function.  The read and write methods will be hooked up at runtime to methods from other classes that will provide and accept byte arrays or packets.

Within each filter is additional code that performs the filtering function:

```<code>public void Process()
{
    while (!done)
    {
        byte[] data = ReadBytes();      // or ReadPacket()
        // perform filtering on data
        WriteBytes(data);               // or WritePacket()
    }
}
</code>```

If only one of the above constructor signatures will be present in each filter, how do I determine (using Reflection) which constructor signature is present, so that I can hook up the appropriate methods at runtime?

Note: If I'm daffy and doing this the wrong way, I'd like to know that too.

答:
Can't you do something like?

```<code>bool packetConstructor =
            typeof(PacketFilter).GetConstructors()
                                .Any(c => c.GetParameters()
                                           .Any(p => p.ParameterType
                                                    == typeof(Func<Packet>)));
</code>```

replacing typeof(PacketFilter) with appropriate instance.

Body:
Let's say I have two classes that look like this:

public class ByteFilter
{
    private Func <int, byte[]> readBytes;
    private Action<byte[]> writeBytes;

    public ByteFilter(Func <int, byte[]> readBytes, Action<byte[]> writeBytes)
    {
        this.readBytes = readBytes;
        this.writeBytes = writeBytes;
    }
}

public class PacketFilter
{
    private Func<Packet> readPacket;
    private Action<Packet> writePacket;

    Public PacketFilter(Func<Packet> readPacket, Action<Packet> writePacket)
    {
        this.readBytes = readPacket;
        this.writeBytes = writePacket;
    }
}

Either class may be instantiated at runtime (via Activator.CreateInstance) to perform a filtering function.  The read and write methods will be hooked up at runtime to methods from other classes that will provide and accept byte arrays or packets.

Within each filter is additional code that performs the filtering function:

public void Process()
{
    while (!done)
    {
        byte[] data = ReadBytes();      // or ReadPacket()
        // perform filtering on data
        WriteBytes(data);               // or WritePacket()
    }
}

If only one of the above constructor signatures will be present in each filter, how do I determine (using Reflection) which constructor signature is present, so that I can hook up the appropriate methods at runtime?

Note: If I'm daffy and doing this the wrong way, I'd like to know that too.

Body:
Can't you do something like?

bool packetConstructor =
            typeof(PacketFilter).GetConstructors()
                                .Any(c => c.GetParameters()
                                           .Any(p => p.ParameterType
                                                    == typeof(Func<Packet>)));

replacing typeof(PacketFilter) with appropriate instance.


问:
How do I make a refresh button that refresh every user's input on form minutes
I have a code that read in a richtextbox the last row from a txt file.
What I want to introduce now is a refresh button with something like a text box.
I want to put it so user can put the number on the form that means minutes for the code and then user press the button refresh and the program will refresh every ... minutes. The program just call last file opened with open file dialog, refresh it on richtextbox every ... minutes.

Here is what I did to refresh just when you press the button refresh (maybe for implement it as I want I should put on the form another button and a text box?):

```<code>    private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                    thePath = ofd.FileName;
                    Refresh();
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
        Refresh();
    }
</code>```

How should the code be?
Thank you for help.

答:
You should use some kind of Timer.
For example, you can declare a private System.Windows.Forms.Timer refreshtimer and instatiate it at the button click.
Assuming the textbox name is TextBox1, the code should look like this:

```<code> private System.Windows.Forms.Timer refreshtimer;
 private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                    thePath = ofd.FileName;
                    Refresh();
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
            refreshtimer = new System.Windows.Forms.Timer();
            refreshtimer.Tick += new EventHandler(timer_Tick);
            refreshtimer.Interval = Convert.ToInt32(TextBox1.Text) * 60000; //60000 is one minute
            refreshtimer.Start();
    }
    void timer_Tick(object sender, EventArgs e)
        {
                   Refresh();
        }
</code>```

At the refresh button click I set the interval to the value of the TextBox (the interval is set in miliseconds, that is why I have multiplied by 60000).
I suggest you put the intialization of the timer in the constructor of the class.
Ask me more if you have any question and I will edit my answer.

Body:
I have a code that read in a richtextbox the last row from a txt file.
What I want to introduce now is a refresh button with something like a text box.
I want to put it so user can put the number on the form that means minutes for the code and then user press the button refresh and the program will refresh every ... minutes. The program just call last file opened with open file dialog, refresh it on richtextbox every ... minutes.

Here is what I did to refresh just when you press the button refresh (maybe for implement it as I want I should put on the form another button and a text box?):

    private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                    thePath = ofd.FileName;
                    Refresh();
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
        Refresh();
    }

How should the code be?
Thank you for help.

Body:
You should use some kind of Timer.
For example, you can declare a private System.Windows.Forms.Timer refreshtimer and instatiate it at the button click.
Assuming the textbox name is TextBox1, the code should look like this:

 private System.Windows.Forms.Timer refreshtimer;
 private string thePath;
    public async void OpenFileBtn_ClickAsync(object sender, EventArgs e)
    {
         using(OpenFileDialog ofd = new OpenFileDialog() { Filter = "Text File|*.txt", Multiselect = false })
         {

             if (ofd.ShowDialog() == DialogResult.OK)
             {
                    thePath = ofd.FileName;
                    Refresh();
             }
         }
    }

    private void Refresh()
    {
        using (StreamReader rd = new StreamReader(thePath))
        {
            string[] lines = rd.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
            ReaderRichTxtBox.Text = lines[lines.Length - 1];
        }
    }

    private void RefreshBtn_Click(object sender, EventArgs e)
    {
            refreshtimer = new System.Windows.Forms.Timer();
            refreshtimer.Tick += new EventHandler(timer_Tick);
            refreshtimer.Interval = Convert.ToInt32(TextBox1.Text) * 60000; //60000 is one minute
            refreshtimer.Start();
    }
    void timer_Tick(object sender, EventArgs e)
        {
                   Refresh();
        }

At the refresh button click I set the interval to the value of the TextBox (the interval is set in miliseconds, that is why I have multiplied by 60000).
I suggest you put the intialization of the timer in the constructor of the class.
Ask me more if you have any question and I will edit my answer.


问:
What are some good resources for getting started with/learning APL?
I'm trying to get started with APL and any related IDEs, tools, compilers, etc. I may need to install locally. I also looked at the APL repl online, but all the symbols seem to be very tough to type (I don't even know where to get started).

I would like to know of any online resources, software or packages I need to install, as well as books or courses on APL. I don't think there was a good answer on StackOverflow about this question, so I would be very grateful if anyone can point me towards the right direction.

答:
A great portal for APL resources is APL Wiki.

I think Dyalog APL is the friendliest interpreter for local install.

For an easy to use online REPL, check out Try APL which has a floating keyboard, a click-to-insert "Primer" for the symbols, and also allows using backtick ` as a prefix key to type. APL Wiki has more in-depth information on typing glyphs.

APL Wiki is again the place to go to for learning resources.

Finally, the APL Orchard is a very active chat room here on Stack Exchange, where plenty of friendly APLers are ready to help, explain, discuss, and teach. I'll always respond if you ping me with @Adám there ― and when I'm online, often immediately.


问:
Custom Tab Bar React Navigation 5
I'm trying to make a tab bar like in the picture bellow, using React Navigation.

I tried some codes, but nothing worked. Some codes are from previous React Navigation Version. The really problem is make the tab bar have a margin from from bottom and both sides, and borders rounded.

Anyone can help me please?!

答:
here is demo: https://snack.expo.io/@nomi9995/createbottomtabnavigator-%7C-react-navigation

you can use tabBar props to make custom TABBAR

```<code><NavigationContainer>
      <Tab.Navigator tabBar={props => <MyTabBar {...props} />}>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
</code>```

MyTabBar Component

```<code>function MyTabBar({ state, descriptors, navigation }) {
  return (
    <View style={{ flexDirection: 'row',backgroundColor:"#F4AF5F",height:50,borderRadius:50,justifyContent:"center",alignItems:"center" }}>
      {state.routes.map((route, index) => {
        const { options } = descriptors[route.key];
        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',
            target: route.key,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name);
          }
        };

        const onLongPress = () => {
          navigation.emit({
            type: 'tabLongPress',
            target: route.key,
          });
        };

        return (
          <TouchableOpacity
            accessibilityRole="button"
            accessibilityStates={isFocused ? ['selected'] : []}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={{ flex: 1, alignItems:"center" }}
          >
            <Text style={{ color: isFocused ? '#673ab7' : '#222' }}>
              {label}
            </Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}
</code>```

Title: Custom Tab Bar React Navigation 5

Body:
here is demo: https://snack.expo.io/@nomi9995/createbottomtabnavigator-%7C-react-navigation

you can use tabBar props to make custom TABBAR

<NavigationContainer>
      <Tab.Navigator tabBar={props => <MyTabBar {...props} />}>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>

MyTabBar Component

function MyTabBar({ state, descriptors, navigation }) {
  return (
    <View style={{ flexDirection: 'row',backgroundColor:"#F4AF5F",height:50,borderRadius:50,justifyContent:"center",alignItems:"center" }}>
      {state.routes.map((route, index) => {
        const { options } = descriptors[route.key];
        const label =
          options.tabBarLabel !== undefined
            ? options.tabBarLabel
            : options.title !== undefined
            ? options.title
            : route.name;

        const isFocused = state.index === index;

        const onPress = () => {
          const event = navigation.emit({
            type: 'tabPress',
            target: route.key,
          });

          if (!isFocused && !event.defaultPrevented) {
            navigation.navigate(route.name);
          }
        };

        const onLongPress = () => {
          navigation.emit({
            type: 'tabLongPress',
            target: route.key,
          });
        };

        return (
          <TouchableOpacity
            accessibilityRole="button"
            accessibilityStates={isFocused ? ['selected'] : []}
            accessibilityLabel={options.tabBarAccessibilityLabel}
            testID={options.tabBarTestID}
            onPress={onPress}
            onLongPress={onLongPress}
            style={{ flex: 1, alignItems:"center" }}
          >
            <Text style={{ color: isFocused ? '#673ab7' : '#222' }}>
              {label}
            </Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
}


问:
How to develop between branches when you have permanent unstaged changes?
I have my whole production code in a repository and locally I had to changed some backend/frontend code out of neccessity and leave them in a permanant "unstaged change" mode.

Since I did all the test locally, I didn't need to use branches until today.

We now have a dev branch and I commit my changes to dev then checkout master and git merge dev.

The only issue is that anytime my change happens to one of those unstaged files, I get the famous:

```<code>Please commit your changes or stash them before you switch branches.
Aborting
</code>```

This answer somehow helps https://stackoverflow.com/a/22424970 but this is not an efficient way for me to do this on every commit.

Is there any way I can do less work on each commit/merge?

答:
Not all of them, the part that is new is commited, rest stays.

Okay, but that's your problem. A file is the atomic unit of thought in git. You cannot mark just a part of a file as outside of git's purview. If you show any of a file to git, git now knows about the whole file and sees (and rightly says) that you've modified. And that is what you are doing.

So, you have conflicting desires. Basically if you're going to work this way, then you have to live with the consequences.

Body:
I have my whole production code in a repository and locally I had to changed some backend/frontend code out of neccessity and leave them in a permanant "unstaged change" mode.

Since I did all the test locally, I didn't need to use branches until today.

We now have a dev branch and I commit my changes to dev then checkout master and git merge dev.

The only issue is that anytime my change happens to one of those unstaged files, I get the famous:

Please commit your changes or stash them before you switch branches.
Aborting

This answer somehow helps https://stackoverflow.com/a/22424970 but this is not an efficient way for me to do this on every commit.

Is there any way I can do less work on each commit/merge?


问:
React-native child component not updating when parent state updates
I have a parent component which holds a child component. The parent is getting its data from redux. The object in store looks something like the below:

```<code>//object in redux store
object :[{
      item: {
         name: 'item'1,
         selected: false
         },
      item:{
         name: 'item'1,
         selected: false
    }
   }]
</code>```

My Parent component contains a FlatList which renders the child component:

```<code>//parent component
<FlatList
  data={this.props.object}
  renderItem={( object ) => <Object object={object.item} />}
  keyExtractor={object => object.id}
/>
</code>```

My child component contains a button, which toggles the selected property of each item. The desired behavior is that the style of the button changes based on the value if the selected property. My child button component looks something like the below:

```<code>// child component
render(){
  return (
    <View>
       <Text>{this.props.name}</Text>
       <Button
         title="toggle"
         buttonStyle={{backgroundColor: this.props.selected? 'red' : 'green'}}
         onPress={() => handling toggle by changing state in store, it works fine and
         console.logs correctly}/>
    </View>
 );
}
</code>```

After the button is toggled, the state of the object does change, and console.logs correctly, however the style of the button only updated when i go out and back into the page as if the child component is not updating.

How can i get the button style to update directly on button toggle? Thanks

答:
it turns out the changes I was doing in my reducer did not trigger a component update due to the shallow equality comparison redux performs.

I fixed by returning this in my reducers

```<code>let obj = {...}
return { ...state, object: {...state.object}
</code>```

instead of

```<code>let obj = {...}
return {...state, object: obj }
</code>```

Body:
I have a parent component which holds a child component. The parent is getting its data from redux. The object in store looks something like the below:

//object in redux store
object :[{
      item: {
         name: 'item'1,
         selected: false
         },
      item:{
         name: 'item'1,
         selected: false
    }
   }]

My Parent component contains a FlatList which renders the child component:

//parent component
<FlatList
  data={this.props.object}
  renderItem={( object ) => <Object object={object.item} />}
  keyExtractor={object => object.id}
/>

My child component contains a button, which toggles the selected property of each item. The desired behavior is that the style of the button changes based on the value if the selected property. My child button component looks something like the below:

// child component
render(){
  return (
    <View>
       <Text>{this.props.name}</Text>
       <Button
         title="toggle"
         buttonStyle={{backgroundColor: this.props.selected? 'red' : 'green'}}
         onPress={() => handling toggle by changing state in store, it works fine and
         console.logs correctly}/>
    </View>
 );
}

After the button is toggled, the state of the object does change, and console.logs correctly, however the style of the button only updated when i go out and back into the page as if the child component is not updating.

How can i get the button style to update directly on button toggle? Thanks

Body:
it turns out the changes I was doing in my reducer did not trigger a component update due to the shallow equality comparison redux performs.

I fixed by returning this in my reducers

let obj = {...}
return { ...state, object: {...state.object}

instead of

let obj = {...}
return {...state, object: obj }


问:
What is a "Tcl wrapper" and how does it work?
I am learning Python and occasionally hear the term "Tcl wrapper" thrown around and have absolutely no idea what it means.

Can anyone explain a "Tcl wrapper" is/does?

Thanks

答:
Tcl is a full-fledged language in its own right.

Python uses Tcl/Tk for the graphical user interface,
tkinter.  In this case python is a wrapper around Tcl/Tk.

Depending on the context, a Tcl wrapper could be a Tcl language wrapper
around another language, a wrapper around another API, or in the case
of Python, a wrapper around Tcl's API.


问:
SwiftUI Switching between views
I have a parent view (Content View) containing an array of integers,

The view switcher function inside the parent switches the child view depending on the value of the integer in the array.

The issue I have is is that 'view1' is re-presented (after being presented before) the view is not redrawn and the text in the textfield remains populated.

How can I redraw the child view each time the switch function is called?

thanks

```<code>struct ContentView: View {

    var views =  [2,1,1]
    @State var currentView = 0

    var body: some View {

        VStack{
            viewSwitcher()
        }
    }

    func viewSwitcher() -> AnyView {
        switch views[currentView] {
        case 1:
            return AnyView(view1(currentView: self.$currentView))
        case 2:
            return AnyView(view2(currentView: self.$currentView))
        default:
            return AnyView(EmptyView())
        }
    }
}

struct view1:View {

    @State var textInput: String = ""
    @Binding var currentView: Int

    var body: some View {
        VStack{

            Text("View 1")

            TextField("Enter Text", text: self.$textInput)

            Button(action: {
                self.currentView += 1
            }){
                Text("Submit")
            }
        }
    }
}

struct view2:View {

    @Binding var currentView: Int

    var body: some View {

        VStack{
            Text("View 2")
            Button(action: {
                self.currentView += 1
            }){
                Text("Submit")
            }
        }
    }
}
</code>```

答:
Here is possible solution. Using .id modifier makes view unique per-update, so rebuilds.

Tested with Xcode 11.4 / iOS 13.4

```<code>func viewSwitcher() -> AnyView {
    switch views[currentView] {
    case 1:
        return AnyView(view1(currentView: self.$currentView).id(UUID()))
    case 2:
        return AnyView(view2(currentView: self.$currentView).id(UUID()))
    default:
        return AnyView(EmptyView())
    }
}
</code>```

Title: SwiftUI Switching between views

Body:
I have a parent view (Content View) containing an array of integers,

The view switcher function inside the parent switches the child view depending on the value of the integer in the array.

The issue I have is is that 'view1' is re-presented (after being presented before) the view is not redrawn and the text in the textfield remains populated.

How can I redraw the child view each time the switch function is called?

thanks

struct ContentView: View {

    var views =  [2,1,1]
    @State var currentView = 0

    var body: some View {

        VStack{
            viewSwitcher()
        }
    }

    func viewSwitcher() -> AnyView {
        switch views[currentView] {
        case 1:
            return AnyView(view1(currentView: self.$currentView))
        case 2:
            return AnyView(view2(currentView: self.$currentView))
        default:
            return AnyView(EmptyView())
        }
    }
}

struct view1:View {

    @State var textInput: String = ""
    @Binding var currentView: Int

    var body: some View {
        VStack{

            Text("View 1")

            TextField("Enter Text", text: self.$textInput)

            Button(action: {
                self.currentView += 1
            }){
                Text("Submit")
            }
        }
    }
}

struct view2:View {

    @Binding var currentView: Int

    var body: some View {

        VStack{
            Text("View 2")
            Button(action: {
                self.currentView += 1
            }){
                Text("Submit")
            }
        }
    }
}

Body:
Here is possible solution. Using .id modifier makes view unique per-update, so rebuilds.

Tested with Xcode 11.4 / iOS 13.4

func viewSwitcher() -> AnyView {
    switch views[currentView] {
    case 1:
        return AnyView(view1(currentView: self.$currentView).id(UUID()))
    case 2:
        return AnyView(view2(currentView: self.$currentView).id(UUID()))
    default:
        return AnyView(EmptyView())
    }
}


问:
is there a way to add automatically buttons on each element of a generated list?
I'm working on a web app that lets people schedule lessons and timeslots, and I'm trying to make it so that people can click on the timeslot to accept it. Currently, the table is retrieved from the database and generated with this code:

```<code>function updateSchedules(name = "missing", grade = "missing", date = "missing", time = "missing", status = "missing", id) {
    let table = document.getElementById('schedules');
    let color;

    console.log("Output schedule for " + name);

    if (status.toLowerCase() === 'pending') {
        color = "background-color:rgb(252, 38, 0)";
    } else if (status.toLowerCase() === 'confirmed') {
        color = 'background-color:rgb(0, 255, 13)';
    } else {
        color = 'background-color:rgb(35, 64, 153)';
    }

    table.innerHTML += `
    <tr>
        <td>${name}</td>
        <td>${grade}</td>
        <td id=testday2>${date}</td>
        <td id=testtime2>${time}</td>
        <td style="${color}">${status}</td>
    </tr>`;
}
</code>```

Is there a way to add buttons on each row of the table that refers to each row's unique id without just making buttons and adding event listeners manually for each row?

答:
You have to add one more  tag with <button> tag and bind with onlick event and pass unique_id in function parameter like this:

```<code><td><button type="button" onclick="myfunc(${id})"></button></td>
</code>```

${id} may be string or number it's depend on requirements

Note-:

You have to pass unique id from (backend).

unique_id might be primary key of database row.

Then write script to handle button like-:

```<code><script>
  function myfunc(unique_id){
     console.log(unique_id);
     // do something
  }
<script>
</code>```

More appropriate if you use anchor tag with button like-:

```<code><td><a onclick="myfunc(${id}")><button type="button"></button></a></td>
</code>```

There are multiple ways to do this same thing. More appropriate if you use this keyword with jquery instead of write pure javascript.

Body:
I'm working on a web app that lets people schedule lessons and timeslots, and I'm trying to make it so that people can click on the timeslot to accept it. Currently, the table is retrieved from the database and generated with this code:

function updateSchedules(name = "missing", grade = "missing", date = "missing", time = "missing", status = "missing", id) {
    let table = document.getElementById('schedules');
    let color;

    console.log("Output schedule for " + name);

    if (status.toLowerCase() === 'pending') {
        color = "background-color:rgb(252, 38, 0)";
    } else if (status.toLowerCase() === 'confirmed') {
        color = 'background-color:rgb(0, 255, 13)';
    } else {
        color = 'background-color:rgb(35, 64, 153)';
    }

    table.innerHTML += `

        ${name}
        ${grade}
        ${date}
        ${time}
        ${status}

`;
}

Is there a way to add buttons on each row of the table that refers to each row's unique id without just making buttons and adding event listeners manually for each row?

Body:
You have to add one more <td> tag with <button> tag and bind with onlick event and pass unique_id in function parameter like this:

<td><button type="button" onclick="myfunc(${id})"></button></td>

${id} may be string or number it's depend on requirements

Note-:

You have to pass unique id from (backend).

unique_id might be primary key of database row.

Then write script to handle button like-:

<script>
  function myfunc(unique_id){
     console.log(unique_id);
     // do something
  }
<script>

More appropriate if you use anchor tag with button like-:

<td><a onclick="myfunc(${id}")><button type="button"></button></a></td>

There are multiple ways to do this same thing. More appropriate if you use this keyword with jquery instead of write pure javascript.


问:
Clarification about apostrophe responsive images
I have some question regarding apostrophes apostrophe-images-widgets and its srcset functionality. It's explained in you Documentation under Responsive Images. I've implemented this solution but i think I misunderstood something becuase the delivered image is still one-half size as background of the parent div focal-point-test.

I mean this:

So the actual img with srcset attribute:

{# lib/modules/my-image-widget/views/widget.html #}

```

<p>Is in the the image but there is also a background defined for the parent <code>focal-point-test</code> with:</p>

<pre class="lang-html prettyprint-override"><code>{% set image = apos.images.first(data.page.main) %}
{% if image %}
  <div class="focal-point-test" style="
    {%- if apos.attachments.hasFocalPoint(image) -%}
      background-position: {{ apos.attachments.focalPointToBackgroundPosition(image) }};
    {%- endif -%}
    background-image: url({{ apos.attachments.url(image, { size: 'one-half' }) }})"></div>
{% endif %}

</code>```

In this case two images will overlap one correct defined image with focalPoint cropping and the actual img element which has the srcset attribute but no background-size: cover;

I found out that you are hiding the img in your image widget:

apos-slideshow .apos-slideshow-item img {
    visibility: hidden;
    width: 100%;
    height: auto;
}
```

So then the actual img with srcset would be hidden and the parent div in this case .apos-slideshow-item will deliver the image still in full size.

So I wanted to ask for some clarification what I have misunderstood in this case?

答:
The apostrophe-images-widgets module uses that double image technique specifically for when it contains multiple images and is acting as a slide show. That technique helps to maintain image appearance when the images are different sizes. That is why the apos-slideshow .apos-slideshow-item img CSS selector is hidden. The intention was that only the background-image would be visible.

As an aside, and as a member of the Apostrophe core team, I can tell
  you that this is an outdated strategy that we don't use anymore
  ourselves very often, if at all. But it's hard to remove or
  significantly change things like this once hundreds of sites are using
  it.

If you are making your own images widget (which would be a good idea), I would not use both the background-image wrapper and a normal img tag. Decide on which works best for your use case. There are still good reasons to use both (maybe other variations on a slider), but that depends on the project.

If your goal is to use the focal point tool, a normal img tag with a normal src attribute won't be enough. One way is to use a background-image attribute on an element that you have set the size for some other way (e.g., width and height styles) with the background-position using the focal point values. Another way is to use object-fit instead, with the focal point values in an object-position style.

Body:
I have some question regarding apostrophes apostrophe-images-widgets and its srcset functionality. It's explained in you Documentation under Responsive Images. I've implemented this solution but i think I misunderstood something becuase the delivered image is still one-half size as background of the parent div focal-point-test.

I mean this:

So the actual img with srcset attribute:

{# lib/modules/my-image-widget/views/widget.html #}

Is in the the image but there is also a background defined for the parent focal-point-test with:

{% set image = apos.images.first(data.page.main) %}
{% if image %}

{% endif %}

In this case two images will overlap one correct defined image with focalPoint cropping and the actual img element which has the srcset attribute but no background-size: cover;

I found out that you are hiding the img in your image widget:

apos-slideshow .apos-slideshow-item img {
    visibility: hidden;
    width: 100%;
    height: auto;
}

So then the actual img with srcset would be hidden and the parent div in this case .apos-slideshow-item will deliver the image still in full size.

So I wanted to ask for some clarification what I have misunderstood in this case?


问:
How to create chunks of videos (.ts) and .m3u8 file from a mp4 video?
I need to create chunks of videos (.ts) of fixed duration (say 5 or 10 seconds) from a mp4 video. And also I need the chunks in different formats (260p, 480p, 720p, 1080p).

I'm able to create the chunks and m3u8 using the command below:

```<code>ffmpeg -i input.mp4 -g 60 -hls_time 10 out.m3u8
</code>```

but not able to create for different resolutions as mentioned above.

答:
Use the scale filter and the HLS muxer:</p>

```<code>ffmpeg -i input.mp4 -filter_complex "[0]scale=-2:260[260];[0]scale=-2:480[480];[0]scale=-2:720[720];[0]scale=-2:1080[1080]" -map "[260]" -map 0:a -map "[480]" -map 0:a -map "[720]" -map 0:a -map "[1080]" -map 0:a -f hls -hls_time 10 -var_stream_map "v:0,a:0,name:260 v:1,a:1,name:480 v:2,a:2,name:720 v:3,a:3,name:1080" -hls_segment_filename "%v_%03d.ts" -master_pl_name "master.m3u8" "output_%v.m3u8"
</code>```

Body:
I need to create chunks of videos (.ts) of fixed duration (say 5 or 10 seconds) from a mp4 video. And also I need the chunks in different formats (260p, 480p, 720p, 1080p).

I'm able to create the chunks and m3u8 using the command below:

ffmpeg -i input.mp4 -g 60 -hls_time 10 out.m3u8

but not able to create for different resolutions as mentioned above.

Body:
Use the scale filter and the HLS muxer:

ffmpeg -i input.mp4 -filter_complex "[0]scale=-2:260[260];[0]scale=-2:480[480];[0]scale=-2:720[720];[0]scale=-2:1080[1080]" -map "[260]" -map 0:a -map "[480]" -map 0:a -map "[720]" -map 0:a -map "[1080]" -map 0:a -f hls -hls_time 10 -var_stream_map "v:0,a:0,name:260 v:1,a:1,name:480 v:2,a:2,name:720 v:3,a:3,name:1080" -hls_segment_filename "%v_%03d.ts" -master_pl_name "master.m3u8" "output_%v.m3u8"