问:
Custom Image View Cut Left and Right Edges Semi Circle
Need help with developing a custom view. This is the kind of view I need to develop:

Have tried a way, but it does not look like a card, its curve and card can be seen in the background. Need something transparent at the cut left and right edges.

Have referred https://github.com/mreram/TicketView, but this does not give a card like effect, need a view with cut edge at left and right in the middle and looks like a card. Any ideas on customizing an image view to look like this ?

答:
I hope this will help you, I did create a class long before which extends FrameLayout which can do the work for you.

Here is what the output will look like

I achieved this by following code.

MyRoundCornerFrame.java

```<code>import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;

public class MyRoundCornerFrame extends FrameLayout {
    private final static float CORNER_RADIUS = 30.0f; //card radius chnage accordingly
    private float cornerRadius;

    public MyRoundCornerFrame(Context context) {
        super(context);
        init(context, null, 0);
    }

    public MyRoundCornerFrame(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public MyRoundCornerFrame(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int count = canvas.save();

        final Path path = new Path();
        path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
        canvas.clipPath(path, Region.Op.INTERSECT);

        canvas.clipPath(path);
        super.dispatchDraw(canvas);
        canvas.restoreToCount(count);
    }
}
</code>```

My XML file looks like below

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:paddingTop="30dp">

    <your.package.name.MyRoundCornerFrame
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="20dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@drawable/food"
            android:padding="20dp" />

    </your.package.name.MyRoundCornerFrame>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:background="@drawable/ticket_view"
        android:padding="10dp"
        tools:ignore="ContentDescription" />

</FrameLayout>
</code>```

for displaying semi-circles at the center I created an XML which named ticket_view.xml layer-list which looks like below

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="5dp" />
        </shape>
    </item>

    <item
        android:width="50dp"
        android:height="50dp"
        android:gravity="start|center">
        <shape android:shape="oval">
            <solid android:color="@android:color/white" />

        </shape>
    </item>

    <item
        android:width="50dp"
        android:height="50dp"
        android:gravity="end|center">
        <shape android:shape="oval">
            <solid android:color="@android:color/white" />

        </shape>
    </item>

</layer-list>
</code>```

A plus point for this is you don't need any library to create this.

I hope this will help you somehow, happy coding

Body:
I hope this will help you, I did create a class long before which extends FrameLayout which can do the work for you.

Here is what the output will look like

I achieved this by following code.

MyRoundCornerFrame.java

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Region;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.widget.FrameLayout;

public class MyRoundCornerFrame extends FrameLayout {
    private final static float CORNER_RADIUS = 30.0f; //card radius chnage accordingly
    private float cornerRadius;

    public MyRoundCornerFrame(Context context) {
        super(context);
        init(context, null, 0);
    }

    public MyRoundCornerFrame(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public MyRoundCornerFrame(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        cornerRadius = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, CORNER_RADIUS, metrics);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        int count = canvas.save();

        final Path path = new Path();
        path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), cornerRadius, cornerRadius, Path.Direction.CW);
        canvas.clipPath(path, Region.Op.INTERSECT);

        canvas.clipPath(path);
        super.dispatchDraw(canvas);
        canvas.restoreToCount(count);
    }
}

My XML file looks like below

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:paddingTop="30dp">

    <your.package.name.MyRoundCornerFrame
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="20dp">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:background="@drawable/food"
            android:padding="20dp" />

    </your.package.name.MyRoundCornerFrame>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_marginTop="20dp"
        android:layout_marginBottom="20dp"
        android:background="@drawable/ticket_view"
        android:padding="10dp"
        tools:ignore="ContentDescription" />

</FrameLayout>

for displaying semi-circles at the center I created an XML which named ticket_view.xml layer-list which looks like below

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <corners android:radius="5dp" />
        </shape>
    </item>

    <item
        android:width="50dp"
        android:height="50dp"
        android:gravity="start|center">
        <shape android:shape="oval">
            <solid android:color="@android:color/white" />

        </shape>
    </item>

    <item
        android:width="50dp"
        android:height="50dp"
        android:gravity="end|center">
        <shape android:shape="oval">
            <solid android:color="@android:color/white" />

        </shape>
    </item>

</layer-list>

A plus point for this is you don't need any library to create this.

I hope this will help you somehow, happy coding


来源: stackexchange

问:
How to get a file from laravel folder storage for a treatment
I saved an image in storage / app / public and I created a symbolic link to public / storage and the link works well but when I try to get the image with the method Storage :: get ($path) I am being sent a FileNotFoundException. I would like to know how to get my image in my code

```<code> $fichier=Storage::get('storage/avatarDebutFemme.png');
</code>```

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
  storage/avatarDebutFemme.png

Previous exceptions

File not found at path: storage/avatarDebutFemme.png (0)

答:
tested and works
storage_path() use absolute path
you will need To create the symbolic link

```<code>php artisan storage:link
</code>```

view img tag

```<code>src="{{route('employee.get.image', $employee->id)}}"
</code>```

below is function

```<code>$path = storage_path('app/public/'.$image_url);//this will load storage/app/public/
    if (!File::exists($path)) {
        $path = public_path('images/avatar.jpg');
    }
    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type",'image/jpeg');

    return $response;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I saved an image in storage / app / public and I created a symbolic link to public / storage and the link works well but when I try to get the image with the method Storage :: get ($path) I am being sent a FileNotFoundException. I would like to know how to get my image in my code

 $fichier=Storage::get('storage/avatarDebutFemme.png');

Illuminate \ Contracts \ Filesystem \ FileNotFoundException
  storage/avatarDebutFemme.png

Previous exceptions

File not found at path: storage/avatarDebutFemme.png (0)

Body:
tested and works
storage_path() use absolute path
you will need To create the symbolic link

php artisan storage:link

view img tag

src="{{route('employee.get.image', $employee->id)}}"

below is function

$path = storage_path('app/public/'.$image_url);//this will load storage/app/public/
    if (!File::exists($path)) {
        $path = public_path('images/avatar.jpg');
    }
    $file = File::get($path);
    $type = File::mimeType($path);

    $response = Response::make($file, 200);
    $response->header("Content-Type",'image/jpeg');

    return $response;


问:
How to sum float numbers in the format hours and minutes?
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});```
</div>
</div>
</p>

<p>The result should be like this:</p>

```0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20
```

答:
May I know why you want the first result to be 0? Below Is a way to do this with a single loop. Comments are in the code to explain.
With each loop we add the minutes, and if they are greater than 60, we add an hour, and then use % 60 to get get the remaining minutes. Floats can be a pain to work with,

e.g 1.1 + 2.2 === 3.3 is false

So I converted the numbers to a string, and then back to an int.

const arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4];
let hoursTally = 0;
let minutesTally = 0;

for(let i = 0; i < arr.length; i++) {
  // Convert the float to a string, as floats can be a pain to add together
  const time = arr[i].toString().split('.');
  // Tally up the hours.
  hoursTally += parseInt(time[0]);
  // Tally up the minutes;
  const minute = time[1];
  if(minute) {
    // We do this so we add 20 minutes, not 2 minutes
    if(minute.length < 2) {
      minutesTally += parseInt(minute) * 10;
    } else {
      minutesTally += parseInt(minute);
    }
    // If the minutesTally is greater than 60, add an hour to hours
    if(minutesTally >= 60) {
      hoursTally++;
      // Set the minutesTally to be the remainder after dividing by 60
      minutesTally = minutesTally % 60;
    }
  }
  console.log(`${hoursTally}.${minutesTally}`);
}```

Body:
How to sum float numbers in the format hours and minutes?

Those. if  calculate two such numbers 0.35+3.45 then it should be = 4.20, not 3.80

var arr = [0.15, 0.2, 3.45, 0.4, 2, 0.3, 5.2, 1, 1.4, 1.1, 2.4, 1, 3.4]

var sum = 0.0;

arr.forEach(function(item) {
  console.log(sum);
  sum += parseFloat(item);
});

The result should be like this:

0
0.15
0.35
4.20
5.0
7.0
7.30
12.50
13.50
15.30
16.40
19.20
20.20


问:
How to get the value from the input
I am trying to catch a change of input but it doesn't work with the button increase or decrease the value, what is the solution here?</p>

```<code><div class="container">
          <button id="tang" class="btn btn-success">+</button>
          <input type="text"  name="" id="number" value="1"">
          <button id="giam" class="btn btn-danger">-</button>
          <h1 id="show"></h1>
      </div>
</code>```

```<code>$("#tang").click(function(){
            let result = parseInt($("#number").val()) +1 ;
            $("#number").val(result);
        });
        $("#giam").click(function(){
            let result = parseInt($("#number").val()) -1 ;
            $("#number").val(result);
        });

        $("#number").change(function(){
            $("#show").text($("#number").val());
        })
</code>```

答:
It is working for me. Here is the working code at: https://jsfiddle.net/297s50gk/

Did you include jQuery in your page?

HTML

```<code><div class="container">
  <button id="tang" class="btn btn-success">+</button>
  <input type="text"  name="" id="number" value="1"">
  <button id="giam" class="btn btn-danger">-</button>
  <h1 id="show"></h1>
</div>

$("#tang").click(function(){
  let result = parseInt($("#number").val()) +1 ;
  $("#number").val(result);
});
$("#giam").click(function(){
  let result = parseInt($("#number").val()) -1 ;
  $("#number").val(result);
});

$("#number").change(function(){
  $("#show").text($("#number").val());
})
</code>```

Title: How to get the value from the input

Body:
I am trying to catch a change of input but it doesn't work with the button increase or decrease the value, what is the solution here?

          <button id="tang" class="btn btn-success">+</button>
          <input type="text"  name="" id="number" value="1"">
          <button id="giam" class="btn btn-danger">-</button>

$("#tang").click(function(){
            let result = parseInt($("#number").val()) +1 ;
            $("#number").val(result);
        });
        $("#giam").click(function(){
            let result = parseInt($("#number").val()) -1 ;
            $("#number").val(result);
        });

        $("#number").change(function(){
            $("#show").text($("#number").val());
        })

Body:
It is working for me. Here is the working code at: https://jsfiddle.net/297s50gk/

Did you include jQuery in your page?

HTML

<div class="container">
  <button id="tang" class="btn btn-success">+</button>
  <input type="text"  name="" id="number" value="1"">
  <button id="giam" class="btn btn-danger">-</button>
  <h1 id="show"></h1>
</div>

$("#tang").click(function(){
  let result = parseInt($("#number").val()) +1 ;
  $("#number").val(result);
});
$("#giam").click(function(){
  let result = parseInt($("#number").val()) -1 ;
  $("#number").val(result);
});

$("#number").change(function(){
  $("#show").text($("#number").val());
})


答:
As a quick fix you could add an event trigger to your lines in the button .click functions like

```<code>$("#number").val(result).change();
</code>```

You could go further and combine the two click() functions into one (with an if clause for increasing/decreasing the value).

Title: How to get the value from the input

Body:
As a quick fix you could add an event trigger to your lines in the button .click functions like

$("#number").val(result).change();

You could go further and combine the two click() functions into one (with an if clause for increasing/decreasing the value).


问:
android.support.v7.widget.GridLayout cannot get it to work
I have an android project which utilizes GridLayout in most of its menus and screens. The problem however is that GridLayout is supported from API 14 and onwards.

Since I want to make the application available to older version of android as well, I tried to use Android's own Support Library GridLayout which adds support up to API 7.
This was exactly what I was looking for, however I cannot for the life of me get it to work. I have tried all of these explanations and ideas:

Android's official instructions

Solution 1

Solution 2

Solution 3

Solution 4

Solution 5

and more...

No matter what I do, how I do it or what IDE I use (whether Eclipse ADT or Android Studio), it always gives me an error in the Layout XML along the lines of:

```<code>The following classes could be instantiated:  - android.support.v7.widget.GridLayout

With either one of these exceptions showing in the error log:

1. android.content.res.Resources$NotFoundException: Could not resolve value 0x7F080000
2. java.lang.classnotfoundexception: android.support.v7.gridlayout.R$dimen
</code>```

Edit: For reference this is what I'm using to create the support gridlayout (taken directly from the android sample programs):

```<code><android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/blue"
    android:padding="10dip"
    app:columnCount="4"
    >
    <TextView
        android:text="@string/string_test"
    />
    <EditText
        app:layout_gravity="fill_horizontal"
        app:layout_column="0"
        app:layout_columnSpan="4"
    />
    <Button
        android:text="@string/button_test"
        app:layout_column="2"
    />
</android.support.v7.widget.GridLayout>
</code>```

What could I possibly be doing wrong that none of the above solutions work? Is there something I'm missing, maybe there's a problem with my original code?

Any help is appreciated

答:
For current stable Release 1.0.0 :
To add a dependency on GridLayout, you must add the Google Maven repository to your project.
Add the dependencies for the artifacts you need in the build.gradle file for your app or module:</p>

```<code>dependencies {
    implementation "androidx.gridlayout:gridlayout:1.0.0"
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an android project which utilizes GridLayout in most of its menus and screens. The problem however is that GridLayout is supported from API 14 and onwards.

Since I want to make the application available to older version of android as well, I tried to use Android's own Support Library GridLayout which adds support up to API 7.
This was exactly what I was looking for, however I cannot for the life of me get it to work. I have tried all of these explanations and ideas:

Android's official instructions

Solution 1

Solution 2

Solution 3

Solution 4

Solution 5

and more...

No matter what I do, how I do it or what IDE I use (whether Eclipse ADT or Android Studio), it always gives me an error in the Layout XML along the lines of:

The following classes could be instantiated:  - android.support.v7.widget.GridLayout

With either one of these exceptions showing in the error log:

1. android.content.res.Resources$NotFoundException: Could not resolve value 0x7F080000
2. java.lang.classnotfoundexception: android.support.v7.gridlayout.R$dimen

Edit: For reference this is what I'm using to create the support gridlayout (taken directly from the android sample programs):

<android.support.v7.widget.GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/blue"
    android:padding="10dip"
    app:columnCount="4"
    >
    <TextView
        android:text="@string/string_test"
    />
    <EditText
        app:layout_gravity="fill_horizontal"
        app:layout_column="0"
        app:layout_columnSpan="4"
    />
    <Button
        android:text="@string/button_test"
        app:layout_column="2"
    />
</android.support.v7.widget.GridLayout>

What could I possibly be doing wrong that none of the above solutions work? Is there something I'm missing, maybe there's a problem with my original code?

Any help is appreciated

Body:
For current stable Release 1.0.0 :
To add a dependency on GridLayout, you must add the Google Maven repository to your project.
Add the dependencies for the artifacts you need in the build.gradle file for your app or module:

dependencies {
    implementation "androidx.gridlayout:gridlayout:1.0.0"
}


问:
Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.22.2 from https://repo.maven.apache.org/maven2
I've just create a new spring boot project and I have a problem in the pom.xml and I have no idea how to resolve it, please someone help.

this is my pom.xml
i got an error in first line.
"Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.22.2 from https://repo.maven.apache.org/maven2
 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or
 updates are forced. Original error: Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.22.2
 from/to central (https://repo.maven.apache.org/maven2): The operation was cancelled."

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.5.RELEASE</version>
  <relativePath/>
 </parent>
 <groupId>com.amol.student.dal</groupId>
 <artifactId>studentdal</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>studentdal</name>
 <description>Student DAL</description>

 <properties>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

</project>```

答: @Rishikesh Chaudhari answer is correct, before you delete folder "maven-surefire-plugin" make sure that you are in a network that can access and download dependencies from the maven repository. The IDE will download the dependency for you when you update your project(click on project name>Maven>Update project)     </p>


问:
API design: how to handle third party's APIs errors
I'm building an API for our client. Let's call it MY_API.

1) Our client POST /user with json request {username: 'TEST', password: 'xxx'}.

2) MY_API will register the user 'TEST' on a third-party api such as https://register.xxx.xxx. Let's call it THEIR_API

3) If THEIR_API returns 200 with payload {username: 'TEST' token: 'xxx'} , MY_API will extract these information and send to the client.

4) If THEIR_API returns 400, MY_API will just forward the payload to the client.

Here is my question:
on step 4), should I extract the error message and then send to the client? or forward is fine for an API?

Thanks

答:
I would say, don't relay on THEIR_API error message, you never know today everything looks fine but tomorrow what they are gonna expose as error.
For example they may expose some DB information which is not a good practice or they may send some unreadable message. So better to take control on your side.</p>


问:
React > How to set focus on the input field after adding a new row by using react-table
I decided to use react-table to build the grid.

Just one thing to have better UI, that is I want to focus on the input field of the new item after clicking on the add new button.

I intend to use ref but have no idea how fowardRef to the child item

Here is my example use of react-table:

https://codesandbox.io/s/beautiful-proskuriakova-lpfxn

In this case, I want to focus on the field First Name after adding a new row.

UPDATED:
I am able to focus on the input by using autoFocus support by native HTML.

The answer here

But I still want to handle focus by using React Ref

答:
You are trying to apply forwardRef() on functional component and React doc says

You may not use the ref attribute on function components React ref doc

You can use useImeprativeHandle() which can be;

```<code>const Table = React.forwardRef((props, ref) => {
  const inputRef = React.useRef();
  React.useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }), []);
  return <Editable ref={inputRef} {...props} />;
}
</code>```

Now you are able to reach ref with creating ref and call the imperative's method. I did not look how to focus your element but you can handle forwardRef problem by using imperativeHandle.

OR

You can convert your EditTable component to classed based comp.

Body:
You are trying to apply forwardRef() on functional component and React doc says

You may not use the ref attribute on function components React ref doc

You can use useImeprativeHandle() which can be;

const Table = React.forwardRef((props, ref) => {
  const inputRef = React.useRef();
  React.useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }), []);
  return <Editable ref={inputRef} {...props} />;
}

Now you are able to reach ref with creating ref and call the imperative's method. I did not look how to focus your element but you can handle forwardRef problem by using imperativeHandle.

OR

You can convert your EditTable component to classed based comp.


问:
How can I find the count of semicolon separated values?
I have a list of all email ids which I have copied from the 'To' field, from an email I received in MS Outlook. These values (email ids) are separated by a semicolon. I have copied this big list of email ids into Excel. Now I want to find the number of email ids in this list; basically by counting the number of semi colons.

One way I can do this is by writing C code. i.e. store the big list as string buffer, and keep comparing the chars to ";" in a while(char == ';') loop.
But I want to do it quickly.

Is there any quick way to find that out using either:

1.) Regular expression (I use powergrep for processing the regexps)

2.) In excel itself (any excel macro/plugin for that?)

3.) DOS script method

4.) Any other quick way of getting it done?

答:
C# 3.0 with LINQ would make this easy if it is an option for you over C

myString.ToCharArray().Count(char => char = ';')

OwnerDisplayName: goldenmean

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Svante

OwnerDisplayName: MattH


问:
Best practice for printing in flex?
I'm looking to print my view to an A5-printer but when I test the print functionality to pdf, I always get a narrow and long printout.

Is there a way to set the pageheight and width? According to adobe help it's read-only.

Does anyone have experience with printing in flex?

答:
The default flex printing is indeed rather dodgy.

If you really want smoother printouts, you could use one of the following open source libraries that do the job just fine

On the client side:
AlivePDF
or PurePDF (as3 IText Port)

On the server side (through BlazeDS or a servlet): IText

Cheers

Title: Best practice for printing in flex?


问:
'opencv-python' installed but still shows 'ModuleNotFoundError: No module named cv2 '
I have run the command

```<code>pip3 list
</code>```

It shows that I have already installed these versions of OpenCV

opencv-contrib-python    4.1.2.30

  opencv-python            4.2.0.32

But whenever I import cv2 it shows the error

ModuleNotFoundError: No module named 'cv2'

答:
If you had a previous version installed. Uninstall it first and try installing it. See the instructions here:
https://pypi.org/project/opencv-python/</p>

Body:
I have run the command

pip3 list

It shows that I have already installed these versions of OpenCV

opencv-contrib-python    4.1.2.30

  opencv-python            4.2.0.32

But whenever I import cv2 it shows the error

ModuleNotFoundError: No module named 'cv2'


问:
Cannot login to seeded custom IdentityUser from PasswordHasher

I created user in context OnModelCreating method. When I m trying to login using given password it always fails.

I also tried to create new account by using UserManager and it works like a charm.

I think the problem is somewhere in PasswordHasher.

Context class

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    var unconfirmedUser = new AppUser
    {
        Id = 2,
        UserName = "00001",
        Identifier = "00001",
        FirstName = "TestName",
        LastName = "TestLastName",
        NormalizedUserName = "TestAccount1",
        SecurityStamp = Guid.NewGuid().ToString(),
        LockoutEnabled = true
    };
    unconfirmedUser.PasswordHash = new PasswordHasher<AppUser>()
       .HashPassword(unconfirmedUser, "f1fRlQ9c&i72yI_2ApLT");

    builder.Entity<AppUser>().HasData(unconfirmedUser); ;
}
```

<p><strong>Controller</strong></p>

<pre class="lang-c prettyprint-override"><code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        var result = await SignInManager.PasswordSignInAsync(model.Identifier, model.Password,
            false, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            Logger.LogInformation($"User: [{model.Identifier}] logged in.");
            return LocalRedirect(returnUrl);
        }
        if (result.IsLockedOut)
        {
            Logger.LogWarning($"User account: [{model.Identifier}] locked out.");
            return RedirectToAction("Lockout", "Account");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Niepoprawne hasło");
        }
    }
    return View(model);
}
</code>```

Startup.cs

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    //options.Lockout.AllowedForNewUsers = true;
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedAccount = false;
    options.SignIn.RequireConfirmedPhoneNumber = false;
});
```

答:
By default , asp.net core identity will login using NormalizedUserName when performing SignInManager.PasswordSignInAsync . If you want to use Identifier to login , a simply way is to use NormalizedUserName directly as Identifier :

```<code>NormalizedUserName = "00001",
</code>```

Body:
I created user in context OnModelCreating method. When I m trying to login using given password it always fails.

I also tried to create new account by using UserManager and it works like a charm.

I think the problem is somewhere in PasswordHasher.

Context class

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    var unconfirmedUser = new AppUser
    {
        Id = 2,
        UserName = "00001",
        Identifier = "00001",
        FirstName = "TestName",
        LastName = "TestLastName",
        NormalizedUserName = "TestAccount1",
        SecurityStamp = Guid.NewGuid().ToString(),
        LockoutEnabled = true
    };
    unconfirmedUser.PasswordHash = new PasswordHasher<AppUser>()
       .HashPassword(unconfirmedUser, "f1fRlQ9c&i72yI_2ApLT");

    builder.Entity<AppUser>().HasData(unconfirmedUser); ;
}

Controller

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginModel model, string returnUrl = null)
{
    returnUrl = returnUrl ?? Url.Content("~/");

    if (ModelState.IsValid)
    {
        var result = await SignInManager.PasswordSignInAsync(model.Identifier, model.Password,
            false, lockoutOnFailure: true);
        if (result.Succeeded)
        {
            Logger.LogInformation($"User: [{model.Identifier}] logged in.");
            return LocalRedirect(returnUrl);
        }
        if (result.IsLockedOut)
        {
            Logger.LogWarning($"User account: [{model.Identifier}] locked out.");
            return RedirectToAction("Lockout", "Account");
        }
        else
        {
            ModelState.AddModelError(string.Empty, "Niepoprawne hasło");
        }
    }
    return View(model);
}

Startup.cs

services.Configure<IdentityOptions>(options =>
{
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = true;
    options.Password.RequireUppercase = true;
    options.Password.RequireNonAlphanumeric = true;
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
    options.Lockout.MaxFailedAccessAttempts = 5;
    //options.Lockout.AllowedForNewUsers = true;
    options.SignIn.RequireConfirmedEmail = false;
    options.SignIn.RequireConfirmedAccount = false;
    options.SignIn.RequireConfirmedPhoneNumber = false;
});

Body:
By default , asp.net core identity will login using NormalizedUserName when performing SignInManager.PasswordSignInAsync . If you want to use Identifier to login , a simply way is to use NormalizedUserName directly as Identifier :

NormalizedUserName = "00001",


问:
Unable to download the form data using javascript. Looking for distinct class and sleecting the [i]th component
I am trying to download the form data which the user enters through a utility which I have built on HTML and Node.js. I have defined a dictionary data where I am capturing the data and adding it to the payload in a particular format.
I am using querySelectorAll to look for the distinct classes and then populating those fields in my data section accordingly. Although the same data is getting replicated in both sections A and B parts of the data(as shown in the code). Can anyone help me solve this issue as the fields for A and B sections are different and I need to capture both of them. Attaching the code to replicate the issue and also the html part of the code.
For example, While I attempted to create a class MC_IP and looked for it using queryselector I am getting the error 'Cannot read property 'value' of undefined'.

JS Part

    let paylod=''
    const Ctids = document.querySelectorAll('.CONTROLLER_ID');
    const mcIps = document.querySelectorAll('.mc_ip');
    const MCIP = document.querySelectorAll('.MC_IP');
    const mcNetmasks = document.querySelectorAll('.Netmask_IP');
    const mcGateways = document.querySelectorAll('.Gateway_IP');
    const mc = document.querySelectorAll('.RBOD_MC');
    const ec = document.querySelectorAll('.RBOD_EC');
    const fu = document.querySelectorAll('.RBOD_FU');
    const sc = document.querySelectorAll('.RBOD_SC');

    const step = oForm.chassis.value;

        let payload = '';
        //Creating the data elements to be cpatured in the downloaded yaml file

        for (let i = 0; i < 2; i++) {
const data = {" PDU:": {"PDU_IP":['     PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
          "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
          "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
        },
        "   \n  Controller: # Controller settings ": {

            "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
                "Netmask IP_A":["           MC_IP",' '+mcIps[i+1].value,'  # RBOD MC IP',''+'\n'],
                "MC_Netmask_A": ["          MC_Netmask",' '+mcNetmasks[i+1].value,'  # RBOD MC Netmask',''+'\n'],
                'MC_Gateway_A':['           MC_Gateway',' '+mcGateways[i+1].value,'  # RBOD MC Gateway',''+'\n'],
                'MC_A': ['          MC',' '+mc[i+1].value,'  # RBOD MC port',''+'\n'],
                'SC_A':['           SC',' '+sc[i+1].value,'  # RBOD SC port',''+'\n'],
                'FU_A':['           FU',' '+fu[i+1].value,'  # RBOD FU port',''+'\n'],
                'EC_A':["           EC",' '+ec[i+1].value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
                'Controller_ID#2': ["           ID",' '+Ctids[i+1].value,"  #Controller ID, A or B",''+'\n'],
            "Controller_ID#3": ['\n'+"      -  # Controller A for RBOD/EBOD"],
                "Netmask IP_B":["           MC_IP",' '+MCIP[i+1].value,'  # RBOD MC IP',''+'\n'],
                "MC_Netmask_B": ["          MC_Netmask",' '+mcNetmasks[i+1].value,'  # RBOD MC Netmask',''+'\n'],
                'MC_Gateway_B':['           MC_Gateway',' '+mcGateways[i+1].value,'  # RBOD MC Gateway',''+'\n'],
                'MC_B': ['          MC',' '+mc[i+1].value,'  # RBOD MC port',''+'\n'],
                'SC_B':['           SC',' '+sc[i+1].value,'  # RBOD SC port',''+'\n'],
                'FU_B':['           FU',' '+fu[i+1].value,'  # RBOD FU port',''+'\n'],
                'EC_B':["           EC",' '+ec[i+1].value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
                'Controller_ID#4': ["           ID",' '+Ctids[i+1].value,"  #Controller ID, A or B",''+'\n'],
        }
      };
      addToPayload(data, '' );
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="tab1"  class="tabcontent">
<h4>Chasis 1 Details</h4>
<div id="extra" style="display:hidden;">

<h6>Additional Details Required for Controller A</h6>
  <label for='Controller_ID1'>Controller_ID:</label>
  <select class="CONTROLLER_ID" id='Controller_ID1' required>
    <option value=""> - Select the Controller ID - </option>
    <option value='A'>A </select>
  <label for='iSCSI1'>iSCSI IPs:</label><input class="iSCSI_IP" type='text' name='iSCSIip1' id="ip1" placeholder='Enter iSCSI ips' disabled="disabled" />
  <label for='HBA_Ports_A'>HBA_Ports:</label><input class="hba_ports" type='text' id="hba" name='hba_ports1' placeholder='Enter the HBA Ports' disabled="disabled" />
  <label for='MC_IP_A'>MC_IP:</label><input class="mc_ip" type='text' name='extra_ip1' id='mc_ip' placeholder='Enter the MC_IP' />
  <label for='MC_Netmask_A'>MC_Netmask:</label><input class="Netmask_IP" type='text' id='netmask_ip1' placeholder='Enter the MC_Netmask' />
  <label for='MC_Gateway_A'>MC_Gateway:</label><input class="Gateway_IP" type='text' id='gateway_ip1' placeholder='Enter the MC_Gateway' />
  <label for='MC_A'>MC:</label><input class="RBOD_MC" type='text' id='rbod_mc1' placeholder='Enter the MC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <label for='SC_A'>SC:</label><input class="RBOD_SC" type='text' id='rbod_sc1' placeholder='Enter the SC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <label for='FU_A'>FU:</label><input class="RBOD_FU" type='text' id='rbod_fu1' placeholder='Enter the FU Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <label for='EC_A'>EC:</label><input class="RBOD_EC" type='text' id='rbod_ec1' placeholder='Enter the EC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <br>
  <br>
  <h6>Additional Details Required for Controller B</h6>
  <label for='Controller_ID'>Controller_ID:</label>
  <select class="CONTROLLER_ID" id='Controller_ID' required>
    <option value=""> - Select the Controller ID - </option>
    <option value='B'>B </select>
  <label for='iSCSI2'>iSCSI IPs:</label><input class="iSCSI_IP" type='text' name='iSCSIip2' id="ip2" placeholder='Enter iSCSI ips' disabled="disabled" />
  <label for='HBA_Ports'>HBA_Ports:</label><input class="hba_ports" type='text' id="hba1"  placeholder='Enter the HBA Ports' disabled="disabled" />
  <label for='MC_IP_B'>MC_IP:</label><input class="MCIP" type='text'  id='mcip' placeholder='Enter the MC_IP' />
  <label for='MC_Netmask'>MC_Netmask:</label><input class="Netmask_IP" type='text'  id="netmaskip" placeholder='Enter the MC_Netmask' />
  <label for='MC_Gateway'>MC_Gateway:</label><input class="Gateway_IP" type='text'  id="gatewayip" placeholder='Enter the MC_Gateway' />
  <label for='MC'>MC:</label><input class="RBOD_MC" type='text' name='rbod_mc' placeholder='Enter the MC Port' id="rbodmc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <label for='SC'>SC:</label><input class="RBOD_SC" type='text' name='rbod_sc' placeholder='Enter the SC Port' id="rbodsc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <label for='FU'>FU:</label><input class="RBOD_FU" type='text' name='rbod_fu' placeholder='Enter the FU Port' id="rbodfu" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  <label for='EC'>EC:</label><input class="RBOD_EC" type='text' name='rbod_ec' placeholder='Enter the EC Port' id="rbodec" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />

</div>
</div></code>```

答:
This is happening because you are using the wrong index to get elements from your array of HTML elements.  When you try and get the value from an element in the array, you are using mc[i+1].value instead of mc[i].value (remember arrays in JS start from 0).

When you are using mc[i+1] to get an element from the array, your index exceeds the maximum index of the array of HTML elements so undefined is returned.

So changing all your [x+1] to [x] should resolve the issue.

Body:
I am trying to download the form data which the user enters through a utility which I have built on HTML and Node.js. I have defined a dictionary data where I am capturing the data and adding it to the payload in a particular format.
I am using querySelectorAll to look for the distinct classes and then populating those fields in my data section accordingly. Although the same data is getting replicated in both sections A and B parts of the data(as shown in the code). Can anyone help me solve this issue as the fields for A and B sections are different and I need to capture both of them. Attaching the code to replicate the issue and also the html part of the code.
For example, While I attempted to create a class MC_IP and looked for it using queryselector I am getting the error 'Cannot read property 'value' of undefined'.

JS Part

    let paylod=''
    const Ctids = document.querySelectorAll('.CONTROLLER_ID');
    const mcIps = document.querySelectorAll('.mc_ip');
    const MCIP = document.querySelectorAll('.MC_IP');
    const mcNetmasks = document.querySelectorAll('.Netmask_IP');
    const mcGateways = document.querySelectorAll('.Gateway_IP');
    const mc = document.querySelectorAll('.RBOD_MC');
    const ec = document.querySelectorAll('.RBOD_EC');
    const fu = document.querySelectorAll('.RBOD_FU');
    const sc = document.querySelectorAll('.RBOD_SC');

    const step = oForm.chassis.value;

        let payload = '';
        //Creating the data elements to be cpatured in the downloaded yaml file

        for (let i = 0; i < 2; i++) {
const data = {" PDU:": {"PDU_IP":['     PDU_IP',' '+ oForm.ip.value,"   #PDU IP",'  '+'\n'],
          "PDU_LEFT":['     PDU_LEFT',[oForm.lo.value]," # left_outlet(s) ",'   '+'\n'],
          "PDU_RIGHT":['        PDU_RIGHT',[oForm.ro.value]," # right_outlet(s) ", '    '+'\n']
        },
        "   \n  Controller: # Controller settings ": {

            "Controller_ID#1": ["       -  # Controller A for RBOD/EBOD"],
                "Netmask IP_A":["           MC_IP",' '+mcIps[i+1].value,'  # RBOD MC IP',''+'\n'],
                "MC_Netmask_A": ["          MC_Netmask",' '+mcNetmasks[i+1].value,'  # RBOD MC Netmask',''+'\n'],
                'MC_Gateway_A':['           MC_Gateway',' '+mcGateways[i+1].value,'  # RBOD MC Gateway',''+'\n'],
                'MC_A': ['          MC',' '+mc[i+1].value,'  # RBOD MC port',''+'\n'],
                'SC_A':['           SC',' '+sc[i+1].value,'  # RBOD SC port',''+'\n'],
                'FU_A':['           FU',' '+fu[i+1].value,'  # RBOD FU port',''+'\n'],
                'EC_A':["           EC",' '+ec[i+1].value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
                'Controller_ID#2': ["           ID",' '+Ctids[i+1].value,"  #Controller ID, A or B",''+'\n'],
            "Controller_ID#3": ['\n'+"      -  # Controller A for RBOD/EBOD"],
                "Netmask IP_B":["           MC_IP",' '+MCIP[i+1].value,'  # RBOD MC IP',''+'\n'],
                "MC_Netmask_B": ["          MC_Netmask",' '+mcNetmasks[i+1].value,'  # RBOD MC Netmask',''+'\n'],
                'MC_Gateway_B':['           MC_Gateway',' '+mcGateways[i+1].value,'  # RBOD MC Gateway',''+'\n'],
                'MC_B': ['          MC',' '+mc[i+1].value,'  # RBOD MC port',''+'\n'],
                'SC_B':['           SC',' '+sc[i+1].value,'  # RBOD SC port',''+'\n'],
                'FU_B':['           FU',' '+fu[i+1].value,'  # RBOD FU port',''+'\n'],
                'EC_B':["           EC",' '+ec[i+1].value,'  # EC port on RBOD or GEM port on JBOD',''+'\n'],
                'Controller_ID#4': ["           ID",' '+Ctids[i+1].value,"  #Controller ID, A or B",''+'\n'],
        }
      };
      addToPayload(data, '' );
}

Chasis 1 Details

Additional Details Required for Controller A

  Controller_ID:
  <select class="CONTROLLER_ID" id='Controller_ID1' required>
    <option value=""> - Select the Controller ID - </option>
    <option value='A'>A </select>
  iSCSI IPs:<input class="iSCSI_IP" type='text' name='iSCSIip1' id="ip1" placeholder='Enter iSCSI ips' disabled="disabled" />
  HBA_Ports:<input class="hba_ports" type='text' id="hba" name='hba_ports1' placeholder='Enter the HBA Ports' disabled="disabled" />
  MC_IP:<input class="mc_ip" type='text' name='extra_ip1' id='mc_ip' placeholder='Enter the MC_IP' />
  MC_Netmask:<input class="Netmask_IP" type='text' id='netmask_ip1' placeholder='Enter the MC_Netmask' />
  MC_Gateway:<input class="Gateway_IP" type='text' id='gateway_ip1' placeholder='Enter the MC_Gateway' />
  MC:<input class="RBOD_MC" type='text' id='rbod_mc1' placeholder='Enter the MC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  SC:<input class="RBOD_SC" type='text' id='rbod_sc1' placeholder='Enter the SC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  FU:<input class="RBOD_FU" type='text' id='rbod_fu1' placeholder='Enter the FU Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  EC:<input class="RBOD_EC" type='text' id='rbod_ec1' placeholder='Enter the EC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />

Additional Details Required for Controller B

  Controller_ID:
  <select class="CONTROLLER_ID" id='Controller_ID' required>
    <option value=""> - Select the Controller ID - </option>
    <option value='B'>B </select>
  iSCSI IPs:<input class="iSCSI_IP" type='text' name='iSCSIip2' id="ip2" placeholder='Enter iSCSI ips' disabled="disabled" />
  HBA_Ports:<input class="hba_ports" type='text' id="hba1"  placeholder='Enter the HBA Ports' disabled="disabled" />
  MC_IP:<input class="MCIP" type='text'  id='mcip' placeholder='Enter the MC_IP' />
  MC_Netmask:<input class="Netmask_IP" type='text'  id="netmaskip" placeholder='Enter the MC_Netmask' />
  MC_Gateway:<input class="Gateway_IP" type='text'  id="gatewayip" placeholder='Enter the MC_Gateway' />
  MC:<input class="RBOD_MC" type='text' name='rbod_mc' placeholder='Enter the MC Port' id="rbodmc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  SC:<input class="RBOD_SC" type='text' name='rbod_sc' placeholder='Enter the SC Port' id="rbodsc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  FU:<input class="RBOD_FU" type='text' name='rbod_fu' placeholder='Enter the FU Port' id="rbodfu" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
  EC:<input class="RBOD_EC" type='text' name='rbod_ec' placeholder='Enter the EC Port' id="rbodec" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />


问:
How to check only specific s3 bucket exists using boto3
I am trying to list a specific bucket in my aws account. But I have used list_buckets() method which returns all the buckets. Purpose is to check if this bucket exists or not

I could have used head_bucket() method, but it doesn't return anything in return (according to boto3 documentation)

I am using mistral workflows to get this bucket (still calling boto3 methtods) not python

But somehow, is there a boto3 method to check if the s3 bucket exists or not?

I need to get the return and compare it accordingly to check if the bucket exists. So if that condition satisfies, it only triggers the next task in mistral stackstorm workflow.

In case you need I will put the workflow as well.

```<code>check_if_exists:
        action: aws_boto3.boto3action
        input:
          action_name: "list_buckets"
          region: <% $.bucket_region %>
          service: "s3"
        publish:
          return_code: <% task(check_if_exists).result.result.Buckets.select($.Name) %>
        on-success:
           - task_one
        on-error:
          - fail
</code>```

答:
You should be able to use head_bucket() method. This will return 200 OK if the bucket exists and you have necessary permissions to access it. If the bucket does not exist or if you do not have permission, you will get 403 or 404.

Boto3 Documentation: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.head_bucket

Body:
I am trying to list a specific bucket in my aws account. But I have used list_buckets() method which returns all the buckets. Purpose is to check if this bucket exists or not

I could have used head_bucket() method, but it doesn't return anything in return (according to boto3 documentation)

I am using mistral workflows to get this bucket (still calling boto3 methtods) not python

But somehow, is there a boto3 method to check if the s3 bucket exists or not?

I need to get the return and compare it accordingly to check if the bucket exists. So if that condition satisfies, it only triggers the next task in mistral stackstorm workflow.

In case you need I will put the workflow as well.

check_if_exists:
        action: aws_boto3.boto3action
        input:
          action_name: "list_buckets"
          region: <% $.bucket_region %>
          service: "s3"
        publish:
          return_code: <% task(check_if_exists).result.result.Buckets.select($.Name) %>
        on-success:
           - task_one
        on-error:
          - fail


问:
How do I extract a certain amount of lines after a pattern in perl?
Lets say I have a text file:

```<code>Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

So far all I have is code to find the target and print it out:

```<code>use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}
</code>```

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

答:
Same solution in slightly different code

```<code>use strict;
use warnings;

my $how_many = 3;
my $pattern = qr/Target Name\d/;

while(<DATA>) {
    next unless /$pattern/;
    print;
    my $count = $how_many;
    while( $count-- > 0 ) { print scalar <DATA> }
    print "\n";
}

__DATA__
Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10
</code>```

Output

```<code>Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9
</code>```

Body:
Lets say I have a text file:

Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

I want to be able to search for a target pattern (there could be multiple in the text file like in example above) and then print out a certain amount of lines that is following it. Lets say 3 lines. So then the output I would want is

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9

So far all I have is code to find the target and print it out:

use strict;
use warning;
open (my $INFILE, $input_file);
my $outfile = "output.txt";
open (my $OUTFILE, '>', $outfile);

my $name;

while (my $line = <$INFILE>) {
  if ($line =~ m#TARGET\s+(\S+)#){
    $name = $1;
    print $OUTFILE "Target $name\n";
  }
}

I am not sure how to print out the next 3 lines following Target. Note: Assume that the targets are always farther apart than 3 lines from each other. I think I would need a counter right?

Body:
Same solution in slightly different code

use strict;
use warnings;

my $how_many = 3;
my $pattern = qr/Target Name\d/;

while(<DATA>) {
    next unless /$pattern/;
    print;
    my $count = $how_many;
    while( $count-- > 0 ) { print scalar <DATA> }
    print "\n";
}

__DATA__
Line 1
Line 2
Target Name1
Line 3
Line 4
Line 5
Line 6
Target Name2
Line 7
Line 8
Line 9
Line 10

Output

Target Name1
Line 3
Line 4
Line 5

Target Name2
Line 7
Line 8
Line 9


问:
i want to add the following from a list but the result only concatinates

Sample value of n is 5

```<code>    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

</code>```

Expected Result : 615

答:
You can use this.

```<code>n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
out=sum([int(i) for i in n.split('+')])
</code>```

if you want only the first three elements to be added then use this.

```<code>out_3=sum([int(i) for i in n.split('+')[:4]])
</code>```

Body:
Sample value of n is 5

    n = input("Enter a No: ")
    n = "{0}+{0}{0}+{0}{0}{0}".format(n)
    n = n.split("+")
    a=n[0]
    b=n[1]
    c=n[2]
    n = (a + b + c)
    print(n)

Expected Result : 615

Body:
You can use this.

n = input("Enter a No: ")
n = "{0}+{0}{0}+{0}{0}{0}".format(n)
out=sum([int(i) for i in n.split('+')])

if you want only the first three elements to be added then use this.

out_3=sum([int(i) for i in n.split('+')[:4]])


答:
There is a typo in your code and wrap your all function inside in document.ready.

typo in this line

 <input type="text"  name="" id="number" value="1""> //remove one double quote.

$(document).ready(function(){
       $("#tang").click(function(){
             var container=$("#number");
            let result = parseInt(container.val()) +1 ;
            container.val(result);
            container.val(result).change();
        });
        $("#giam").click(function(){
            var container=$("#number");
            let result = parseInt(container.val()) -1 ;
            if(result<0)
              result=0;
            container.val(result);
            container.val(result).change();
        });

        $("#number").change(function(){
            $("#show").text($("#number").val());
        })
   })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
          <button id="tang" class="btn btn-success">+</button>
          <input type="text"  name="" id="number" value="1">
          <button id="giam" class="btn btn-danger">-</button>
          <h1 id="show"></h1>
 </div></code>```

Title: How to get the value from the input

Body:
There is a typo in your code and wrap your all function inside in document.ready.

typo in this line

 <input type="text"  name="" id="number" value="1""> //remove one double quote.

$(document).ready(function(){
       $("#tang").click(function(){
             var container=$("#number");
            let result = parseInt(container.val()) +1 ;
            container.val(result);
            container.val(result).change();
        });
        $("#giam").click(function(){
            var container=$("#number");
            let result = parseInt(container.val()) -1 ;
            if(result<0)
              result=0;
            container.val(result);
            container.val(result).change();
        });

        $("#number").change(function(){
            $("#show").text($("#number").val());
        })
   })

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
          <button id="tang" class="btn btn-success">+</button>
          <input type="text"  name="" id="number" value="1">
          <button id="giam" class="btn btn-danger">-</button>
          <h1 id="show"></h1>
 </div>


问:
How to enable Auto-completion of PECL Mongo classes in Netbeans
Is there any chance to have/enable auto-completion of Mongo PHP PECL classes in netbeans?</p>

答: My only found on this is to write PHP class stubs, and put it into netbeans dir</p>


问:
TypeError: Cannot read property 'fn' of undefined in react js
I have installed the owl carousel(npm install react-owl-carousel2). While running the code it is displaying the below error.

```<code>TypeError: Cannot read property 'fn' of undefined
    eval
    ././src/owl.carousel.js?:1667:4
    eval
    ././src/owl.carousel.js?:1701:3
    (anonymous function)
    C:/xampp/htdocs/new-react/node_modules/react-owl-carousel2/lib/OwlCarousel.js:63
      60 | /* 1 */
      61 | /***/ function(module, exports) {
      62 |
     63 |   eval("'
</code>```

What do I need to do for 'fn' of undefined error?

答:
```<code>let owl_carousel = require('owl.carousel');
window.fn = owl_carousel;
</code>```

https://github.com/OwlCarousel2/OwlCarousel2/issues/2537
https://github.com/OwlCarousel2/OwlCarousel2/issues/2206

Body:
I have installed the owl carousel(npm install react-owl-carousel2). While running the code it is displaying the below error.

TypeError: Cannot read property 'fn' of undefined
    eval
    ././src/owl.carousel.js?:1667:4
    eval
    ././src/owl.carousel.js?:1701:3
    (anonymous function)
    C:/xampp/htdocs/new-react/node_modules/react-owl-carousel2/lib/OwlCarousel.js:63
      60 | /* 1 */
      61 | /***/ function(module, exports) {
      62 |
     63 |   eval("'

What do I need to do for 'fn' of undefined error?

Body:
let owl_carousel = require('owl.carousel');
window.fn = owl_carousel;

https://github.com/OwlCarousel2/OwlCarousel2/issues/2537
https://github.com/OwlCarousel2/OwlCarousel2/issues/2206


问:
Microsoft Azure AD Graph API to add member to a group
Trying to add members to a group using Microsoft graph API, was able to add member to the group to which Application owner is the owner of but not to the group that was created by other member.

When I try to add member to the group and Application owner is not the owner of the group, I am receiving the following error

```<code>{
    "error": {
        "code": "Authorization_RequestDenied",
        "message": "Insufficient privileges to complete the operation.",
        "innerError": {
            "request-id": "2c5a99ff-70XXXXXXXXXXXXXXXXX",
            "date": "2X-XX-XXXX 23:42:54"
        }
    }
}
</code>```

These are the permissions given to the App API

Can someone help me understand how the add member to group works with Azure? only group owner will be able to add member to the group? Is there any configuration that needs to be enabled for Application to let Application owner add member to any group?

答:
If you are using Delegated permissions, the effective permissions of a token will be the combined permissions of the app and user.
If the user does not have the necessary role/ownership, then your app can't do it either. </p>

<p>If your app needs to act with more permissions than the user has, you'll need to use application permissions instead of delegated permissions.
To use app permissions, your app back-end must acquire tokens using the client credentials flow, which does not involve a user.
In this case only the application's app permissions matter, delegated permissions will have no effect. </p>

Body:
Trying to add members to a group using Microsoft graph API, was able to add member to the group to which Application owner is the owner of but not to the group that was created by other member.

When I try to add member to the group and Application owner is not the owner of the group, I am receiving the following error

{
    "error": {
        "code": "Authorization_RequestDenied",
        "message": "Insufficient privileges to complete the operation.",
        "innerError": {
            "request-id": "2c5a99ff-70XXXXXXXXXXXXXXXXX",
            "date": "2X-XX-XXXX 23:42:54"
        }
    }
}

These are the permissions given to the App API

Can someone help me understand how the add member to group works with Azure? only group owner will be able to add member to the group? Is there any configuration that needs to be enabled for Application to let Application owner add member to any group?

Body:
If you are using Delegated permissions, the effective permissions of a token will be the combined permissions of the app and user.
If the user does not have the necessary role/ownership, then your app can't do it either.

If your app needs to act with more permissions than the user has, you'll need to use application permissions instead of delegated permissions.
To use app permissions, your app back-end must acquire tokens using the client credentials flow, which does not involve a user.
In this case only the application's app permissions matter, delegated permissions will have no effect.


问:
ReactJS: Getting Failed to Compile Error While Starting the Server
I am a beginner in ReactJS. Just after finishing a course on the basics of React and Redux. I have started a new Udemy course entitled "React Data Visualization - Build a Cryptocurrency Dashboard." I am facing a problem in lecture 4 while trying to start the server with yarn start command:

```<code>Failed to compile
./src/index.js
Cannot find file: 'index.js' does not match the corresponding name on disk: '.\src\App\app'.
</code>```

Here are my codes on index.js file under app directory:

```<code>import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render(){
    return (
      <div>
        Hello World
      </div>
    );
  }

}

export default App;
</code>```

Here are my codes on index.js file under src directory:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
</code>```

How can I fix the issue?

You can find the project files here.

https://drive.google.com/open?id=1u-8mCYSWZtXPbIqELKsF33FOiXb3yrkH

Edit 1: I am adding the codes inside package.json file, as suggested by @Wesgur:

```<code>{
  "name": "cryptodash",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}
</code>```

Edit 2: I am adding the image to show the folder structure, as suggested by @Madhavan.V:

答: @Shawan It is just a typo change the App import statement in src/index from import App from './App'; to import App from './app';.

Body:
I am a beginner in ReactJS. Just after finishing a course on the basics of React and Redux. I have started a new Udemy course entitled "React Data Visualization - Build a Cryptocurrency Dashboard." I am facing a problem in lecture 4 while trying to start the server with yarn start command:

Failed to compile
./src/index.js
Cannot find file: 'index.js' does not match the corresponding name on disk: '.\src\App\app'.

Here are my codes on index.js file under app directory:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  render(){
    return (

        Hello World

    );
  }

}

export default App;

Here are my codes on index.js file under src directory:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';

ReactDOM.render(<App />, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.

How can I fix the issue?

You can find the project files here.

https://drive.google.com/open?id=1u-8mCYSWZtXPbIqELKsF33FOiXb3yrkH

Edit 1: I am adding the codes inside package.json file, as suggested by @Wesgur:

{
  "name": "cryptodash",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.3.2",
    "@testing-library/user-event": "^7.1.2",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "3.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Edit 2: I am adding the image to show the folder structure, as suggested by @Madhavan.V:


问:
Mat select filter for object Array
I want to introduce a search option in my mat-select DropDown.I went through a lot of similar working options, but those are not working for me because of the object array I am passing to the Dropdown. any help is appreciated. thank you.

My Code

HTML File

```<code><mat-form-field>
   <mat-select (selectionChange)="getSubtier($event.value)">
     <input (keyup)="onKey($event.target.value)">
     <mat-option>None</mat-option>
     <mat-option *ngFor="let state of selectedStates" [value]="state">{{state.name}}</mat-option>
   </mat-select>
</mat-form-field>
</code>```

TS File

```<code> states: string[] = [
        {
          toptier_agency_id: 15,
          create_date: 1517428376464,
          update_date: 1560547998012,
          toptier_code: "013",
          abbreviation: "DOC",
          name: "Department of Commerce",
          website: "https://www.commerce.gov/",
          mapped_org_name: "COMMERCE, DEPARTMENT OF",
          display_yn: "Y"
        },
        {
          toptier_agency_id: 16,
          create_date: 1517428376787,
          update_date: 1560547999157,
          toptier_code: "014",
          abbreviation: "DOI",
          name: "Department of the Interior",
          website: "https://www.doi.gov/",
          mapped_org_name: "INTERIOR, DEPARTMENT OF THE",
          display_yn: "Y"
        }];

 selectedValue: string;
  selectedStates = [];

  ngOnInit() {
    this.selectedStates = this.states;
  }
  onKey(value) {
    this.selectedStates = this.search(value);
  }
  getSubtier(value) {
    console.log(value);
  }

  search(value: string) {
    // this.selectedStates=[]
   // let filter = value.toLowerCase();
    // this.selectedStates = this.selectedStates['name'].filter((unit) => unit.label.indexOf(value) > -1);
  }
</code>```

StackBliz Demo

答:
Modify search functuon. Use filter and includes

Try like this:

```<code>onKey(value) {
  this.selectedStates = this.search(value);
}

search(value: string) {
  let filter = this.states.filter(item =>
    item.name.toLowerCase().includes(value.toLowerCase())
  );
  return [...filter];
}
</code>```

Working Demo

Title: Mat select filter for object Array

Body:
I want to introduce a search option in my mat-select DropDown.I went through a lot of similar working options, but those are not working for me because of the object array I am passing to the Dropdown. any help is appreciated. thank you.

My Code

HTML File

<mat-form-field>
   <mat-select (selectionChange)="getSubtier($event.value)">
     <input (keyup)="onKey($event.target.value)">
     <mat-option>None</mat-option>
     <mat-option *ngFor="let state of selectedStates" [value]="state">{{state.name}}</mat-option>
   </mat-select>
</mat-form-field>

TS File

 states: string[] = [
        {
          toptier_agency_id: 15,
          create_date: 1517428376464,
          update_date: 1560547998012,
          toptier_code: "013",
          abbreviation: "DOC",
          name: "Department of Commerce",
          website: "https://www.commerce.gov/",
          mapped_org_name: "COMMERCE, DEPARTMENT OF",
          display_yn: "Y"
        },
        {
          toptier_agency_id: 16,
          create_date: 1517428376787,
          update_date: 1560547999157,
          toptier_code: "014",
          abbreviation: "DOI",
          name: "Department of the Interior",
          website: "https://www.doi.gov/",
          mapped_org_name: "INTERIOR, DEPARTMENT OF THE",
          display_yn: "Y"
        }];

 selectedValue: string;
  selectedStates = [];

  ngOnInit() {
    this.selectedStates = this.states;
  }
  onKey(value) {
    this.selectedStates = this.search(value);
  }
  getSubtier(value) {
    console.log(value);
  }

  search(value: string) {
    // this.selectedStates=[]
   // let filter = value.toLowerCase();
    // this.selectedStates = this.selectedStates['name'].filter((unit) => unit.label.indexOf(value) > -1);
  }

StackBliz Demo

Body:
Modify search functuon. Use filter and includes

Try like this:

onKey(value) {
  this.selectedStates = this.search(value);
}

search(value: string) {
  let filter = this.states.filter(item =>
    item.name.toLowerCase().includes(value.toLowerCase())
  );
  return [...filter];
}

Working Demo


问:
MYSQL remove duplicates from table with two columns
Have table contents_tags

```<code>+------------+--------+
| content_id | tag_id |
+------------+--------+
|          1 |      1 |
|          1 |      2 |
|          1 |      2 |
|          2 |      3 |
|          2 |      4 |
|          2 |      4 |
</code>```

I want create unique index with two columns

```<code>alter table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);
</code>```

But I already have duplicate entries and get error:

ERROR 1062 (23000): Duplicate entry '1-2' for key 'contents_tags'

```<code>alter IGNORE table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);
</code>```

IGNORE - don't work in Mysql 8

How can I remove duplicates?

答:
One more way if you are okay to drop your table.

IGNORE support for ALTER TABLE has been deprecated from 5.6 version if i'm not wrong. But you can still use IGNORE in INSERT.

```<code>CREATE TABLE contents_tags_new LIKE contents_tags;

ALTER TABLE contents_tags_new ADD UNIQUE INDEX (content_id ,tag_id );

INSERT IGNORE INTO contents_tags_new SELECT * FROM contents_tags;

DROP TABLE contents_tags;

RENAME TABLE contents_tags_new TO contents_tags;
</code>```

CHECK DEMO HERE

Body:
Have table contents_tags

+------------+--------+
| content_id | tag_id |
+------------+--------+
|          1 |      1 |
|          1 |      2 |
|          1 |      2 |
|          2 |      3 |
|          2 |      4 |
|          2 |      4 |

I want create unique index with two columns

alter table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);

But I already have duplicate entries and get error:

ERROR 1062 (23000): Duplicate entry '1-2' for key 'contents_tags'

alter IGNORE table contents_tags ADD UNIQUE `contents_tags` (`content_id`, `tag_id`);

IGNORE - don't work in Mysql 8

How can I remove duplicates?

Body:
One more way if you are okay to drop your table.

IGNORE support for ALTER TABLE has been deprecated from 5.6 version if i'm not wrong. But you can still use IGNORE in INSERT.

CREATE TABLE contents_tags_new LIKE contents_tags;

ALTER TABLE contents_tags_new ADD UNIQUE INDEX (content_id ,tag_id );

INSERT IGNORE INTO contents_tags_new SELECT * FROM contents_tags;

DROP TABLE contents_tags;

RENAME TABLE contents_tags_new TO contents_tags;

CHECK DEMO HERE


问:
Getting rows which contain certain value in a column per each group in Pandas
was wondering if you could provide some guidance with this one- I'm still working on this dataand here's what I am trying to do:
-For each grouped 'country or area', I am trying to get the rows that contain the 2016 'quantity' and the 2011 'quantity'. However, it looks like there may be some countries that don't have a row for 2016 or 2011. The problem is I get an error when executing the following code:

```<code>
for c in grp['Country or Area'].unique():
  deltafiveyrs.append(grp[(grp['Year'] == 2016.0) & (grp['Country or Area'] == c)]['Quantity'] -  grp[(grp['Year'] == 2011.0) & (grp['Country or Area'] == c)]['Quantity'])
</code>```

The error message I get is:

```<code>/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:5: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
  """
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-30-90579ab30ed1> in <module>()
      3
      4 for c in grp['Country or Area'].unique():
----> 5   deltafiveyrs.append(grp[(grp['Year'] == 2016.0) & (grp['Country or Area'] == c)]['Quantity'] -  grp[(grp['Year'] == 2011.0) & (grp['Country or Area'] == c)]['Quantity'])
      6
      7

/usr/local/lib/python3.6/dist-packages/pandas/core/base.py in __getitem__(self, key)
    266         else:
    267             if key not in self.obj:
--> 268                 raise KeyError("Column not found: {key}".format(key=key))
    269             return self._gotitem(key, ndim=1)
    270

KeyError: 'Column not found: False'
</code>```

does anybody know what is going on? Should the values in the 'years' column be changed from float to int? And what would be the best way on how to handle the groups with no values for 2011/2016?

Many thanks

答:
Explore and Clean the data before working on that.
few columns (ignoring Quantity footnotes) are having nan values. so lets drop those rows and proceed further. I tried this in jupyter notebook which gave dataframe of countries with quantity in year 2011 & 2016.</p>

```<code>cdf = df[['Country or Area', 'Commodity - Transaction', 'Year', 'Unit', 'Quantity']]
cdf.dropna()
cdf[(cdf['Year']== 2011) | (cdf['Year']== 2016)]
</code>```

Body:
was wondering if you could provide some guidance with this one- I'm still working on this dataand here's what I am trying to do:
-For each grouped 'country or area', I am trying to get the rows that contain the 2016 'quantity' and the 2011 'quantity'. However, it looks like there may be some countries that don't have a row for 2016 or 2011. The problem is I get an error when executing the following code:

for c in grp['Country or Area'].unique():
  deltafiveyrs.append(grp[(grp['Year'] == 2016.0) & (grp['Country or Area'] == c)]['Quantity'] -  grp[(grp['Year'] == 2011.0) & (grp['Country or Area'] == c)]['Quantity'])

The error message I get is:

/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py:5: DeprecationWarning: elementwise comparison failed; this will raise an error in the future.
  """
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-30-90579ab30ed1> in <module>()
      3
      4 for c in grp['Country or Area'].unique():
----> 5   deltafiveyrs.append(grp[(grp['Year'] == 2016.0) & (grp['Country or Area'] == c)]['Quantity'] -  grp[(grp['Year'] == 2011.0) & (grp['Country or Area'] == c)]['Quantity'])
      6
      7

/usr/local/lib/python3.6/dist-packages/pandas/core/base.py in __getitem__(self, key)
    266         else:
    267             if key not in self.obj:
--> 268                 raise KeyError("Column not found: {key}".format(key=key))
    269             return self._gotitem(key, ndim=1)
    270

KeyError: 'Column not found: False'

does anybody know what is going on? Should the values in the 'years' column be changed from float to int? And what would be the best way on how to handle the groups with no values for 2011/2016?

Many thanks

Body:
Explore and Clean the data before working on that.
few columns (ignoring Quantity footnotes) are having nan values. so lets drop those rows and proceed further. I tried this in jupyter notebook which gave dataframe of countries with quantity in year 2011 & 2016.

cdf = df[['Country or Area', 'Commodity - Transaction', 'Year', 'Unit', 'Quantity']]
cdf.dropna()
cdf[(cdf['Year']== 2011) | (cdf['Year']== 2016)]


问:
What is the right way to get an NSString object from an NSArray, keeping Memory Managment in mind?
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

```<code>NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];
</code>```

Now I want to get an object from this NSArray at index 2.

```<code>NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?
</code>```

OR I should first alloc nameString and then assign value to it ?

答: There is no need to release the nameString.You only release when you are using(alloc”, “new”, “copy”, or “mutableCopy”) .</p>

Body:
What is the right way to get an NSString object from an NSArray,  keeping Memory Managment in mind.

Suppose I have an array

NSArray *myNewArray = [[NSArray alloc] initWithObjects:.......];

Now I want to get an object from this NSArray at index 2.

NSString *nameString = [myNewArray objectAtIndex:2]; // is it the right way? how to deal with "nameString"
                                                     // now regarding memory managment, should I release it ?

OR I should first alloc nameString and then assign value to it ?


问:
How to conditionally add a child component to a parent component in React?
Consider an array like this:

```<code>const myArray = [1,2,3]
</code>```

Depending on the length of this array (which keeps changing only between 2 and 3), I want to add or remove a react-native-svg component which display this value.

This is how I have approached it so far (I know this code will not work):

```<code>const myComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);

    const mySVGComponents = useEffect(() => {
        //It is ensured that the array has at least two values
        let GroupWrapper = (() => {
            return (
                <G>
                    <SVGText>{myArray[0]}</SVGText>
                    <SVGText>{myArray[1]}</SVGText>
                </G>
            )
        })

        if (myArray.length === 3) {
            GroupWrapper = (() => {
                return (
                    <GroupWrapper>
                        <SVGText>{myArray[2]}</SVGText>
                    </GroupWrapper>
                )
            })
        }

        return GroupWrapper;

    }, [myArray]);

    return (
        <G>
            {mySVGComponents}
        </G>
    )
}
</code>```

How can I inject SVGText components into the <G> component conditionally based on the length of myArray?

答:
Only change your "mySVGComponents" to below given code.</p>

```<code>const mySVGComponents = useEffect(() => {
            //It is ensured that the array has at least two values

             let GroupWrapper = (() => {

               return (
                    <G>
                      {
                       myArray.map(item => <SVGText>{item}</SVGText>)
                      }
                    </G>
                )
            })
            return GroupWrapper;

        }, [myArray]);
</code>```

Body:
Consider an array like this:

const myArray = [1,2,3]

Depending on the length of this array (which keeps changing only between 2 and 3), I want to add or remove a react-native-svg component which display this value.

This is how I have approached it so far (I know this code will not work):

const myComponent = (props) => {
    const [myArray, setMyArray] = useState([1,2,3]);

    const mySVGComponents = useEffect(() => {
        //It is ensured that the array has at least two values
        let GroupWrapper = (() => {
            return (
                <G>
                    <SVGText>{myArray[0]}</SVGText>
                    <SVGText>{myArray[1]}</SVGText>
                </G>
            )
        })

        if (myArray.length === 3) {
            GroupWrapper = (() => {
                return (
                    <GroupWrapper>
                        <SVGText>{myArray[2]}</SVGText>
                    </GroupWrapper>
                )
            })
        }

        return GroupWrapper;

    }, [myArray]);

    return (
        <G>
            {mySVGComponents}
        </G>
    )
}

How can I inject SVGText components into the <G> component conditionally based on the length of myArray?

Body:
Only change your "mySVGComponents" to below given code.

const mySVGComponents = useEffect(() => {
            //It is ensured that the array has at least two values

             let GroupWrapper = (() => {

               return (
                    <G>
                      {
                       myArray.map(item => <SVGText>{item}</SVGText>)
                      }
                    </G>
                )
            })
            return GroupWrapper;

        }, [myArray]);


问:
Text detection in live camera swift
I am detecting text in live camera using swift but frames are not identified correct words.
The application works fine when I try to detect text in image and frames draw at exactly around the world.

for live camera what i did is create a capture video session  and implement AVCaptureVideoDataOutputSampleBufferDelegate then in didOutput i am taking buffered image and convert it in UIImage and detect text in it. but the same strategy is not working correctly in this case.

also, didOutput call every time after starting video session and what I want is to only call a function when the user moves his camera or find text.

```<code>    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
            print("didOutput")
            // do stuff here
                guard let hasImage = CMSampleBufferGetImageBuffer(sampleBuffer) else {
                    print("no image")
                    return
                }
                let imageBuffer = hasImage
                let ciimage : CIImage = CIImage(cvPixelBuffer: imageBuffer)
                liveCamImage = self.convert(cmage: ciimage)
                DispatchQueue.main.async {
                     self.drawRectOnText(imagefromCam:self.liveCamImage)
        }
    }
</code>```

is there any solution.
//conver function

```<code>func convert(cmage:CIImage) -> UIImage
    {
         let context:CIContext = CIContext.init(options: nil)
         let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
         let image:UIImage = UIImage.init(cgImage: cgImage)
         return image
    }
</code>```

答:
Use below code in your convert method:</p>

```<code>func convert(samImageBuff:CIImage) -> UIImage{

let imageBuffer = CMSampleBufferGetImageBuffer(samImageBuff)
var ciImage: CIImage? = nil
if let imageBuffer = imageBuffer as? CVPixelBuffer {
    ciImage = CIImage(cvPixelBuffer: imageBuffer)
}
let temporaryContext = CIContext(options: nil)
var videoImage: CGImage? = nil
if let ciImage = ciImage {
    videoImage = temporaryContext.createCGImage(ciImage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(imageBuffer), height: CVPixelBufferGetHeight(imageBuffer)))
}

var image: UIImage? = nil
if let videoImage = videoImage {
    image = UIImage(cgImage: videoImage)
}
CGImageRelease(videoImage)
 return image
 }
</code>```

Title: Text detection in live camera swift

Body:
I am detecting text in live camera using swift but frames are not identified correct words.
The application works fine when I try to detect text in image and frames draw at exactly around the world.

for live camera what i did is create a capture video session  and implement AVCaptureVideoDataOutputSampleBufferDelegate then in didOutput i am taking buffered image and convert it in UIImage and detect text in it. but the same strategy is not working correctly in this case.

also, didOutput call every time after starting video session and what I want is to only call a function when the user moves his camera or find text.

    func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
            print("didOutput")
            // do stuff here
                guard let hasImage = CMSampleBufferGetImageBuffer(sampleBuffer) else {
                    print("no image")
                    return
                }
                let imageBuffer = hasImage
                let ciimage : CIImage = CIImage(cvPixelBuffer: imageBuffer)
                liveCamImage = self.convert(cmage: ciimage)
                DispatchQueue.main.async {
                     self.drawRectOnText(imagefromCam:self.liveCamImage)
        }
    }

is there any solution.
//conver function

func convert(cmage:CIImage) -> UIImage
    {
         let context:CIContext = CIContext.init(options: nil)
         let cgImage:CGImage = context.createCGImage(cmage, from: cmage.extent)!
         let image:UIImage = UIImage.init(cgImage: cgImage)
         return image
    }

Body:
Use below code in your convert method:

func convert(samImageBuff:CIImage) -> UIImage{

let imageBuffer = CMSampleBufferGetImageBuffer(samImageBuff)
var ciImage: CIImage? = nil
if let imageBuffer = imageBuffer as? CVPixelBuffer {
    ciImage = CIImage(cvPixelBuffer: imageBuffer)
}
let temporaryContext = CIContext(options: nil)
var videoImage: CGImage? = nil
if let ciImage = ciImage {
    videoImage = temporaryContext.createCGImage(ciImage, from: CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(imageBuffer), height: CVPixelBufferGetHeight(imageBuffer)))
}

var image: UIImage? = nil
if let videoImage = videoImage {
    image = UIImage(cgImage: videoImage)
}
CGImageRelease(videoImage)
 return image
 }


问:
How to convert asarray's output back to normal array in Python?
I have some code which has used NumPy's asarray and therefore the array looks like this:

```<code>[[392 200]
 [461 194]
 [392 200]
 [161 202]]
</code>```

I want to convert it back to normal array with commas. I expect it to look like this:

```<code>[[392, 200],
 [461, 194],
 [392, 200],
 [161, 202]]
</code>```

What's the way out?

答:
You can certainly do that, have a look at the snippet below:</p>

```<code>import numpy as np

np_array = np.asarray([[392, 200], [461, 194], [392, 200], [161, 202]])
python_list = np_array.tolist()
</code>```

Body:
I have some code which has used NumPy's asarray and therefore the array looks like this:

[[392 200]
 [461 194]
 [392 200]
 [161 202]]

I want to convert it back to normal array with commas. I expect it to look like this:

[[392, 200],
 [461, 194],
 [392, 200],
 [161, 202]]

What's the way out?

Body:
You can certainly do that, have a look at the snippet below:

import numpy as np

np_array = np.asarray([[392, 200], [461, 194], [392, 200], [161, 202]])
python_list = np_array.tolist()


问:
Inputbox block the system.drawing
I am trying to code this function on a form: User click on the form, a inputbox asks user to input a name, and a circle is drawn on the place in the form where the user clicks. One issue now I faces is that circle is now draw at the place where the inputbox show up. I actually have a function to repaint every circle on the form, but it still does not work. Here is my code:</p>

```<code>private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        string ProvinceName;
        System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Graphics formGraphics;
        formGraphics = this.CreateGraphics();

        formGraphics.FillEllipse(myBrush, new Rectangle(e.X, e.Y, 10, 10));

        ProvinceName = Microsoft.VisualBasic.Interaction.InputBox("郡名", "", "无名",100,100);

        provinces.Add(new province(ProvinceName, e.X, e.Y));

        listBox1.SelectedIndex = provinces.Count - 1;

        myBrush.Dispose();
        formGraphics.Dispose();
        PaintMap();// This is the function repaint every recorded clicked locations.

    }
</code>```

答: I used Bipmap to store the paint and then use paint event to repaint the form. The problem is solved. I think when I directly use "System.Drawing, I paint on the inputbox.</p>

Title: Inputbox block the system.drawing

Body:
I am trying to code this function on a form: User click on the form, a inputbox asks user to input a name, and a circle is drawn on the place in the form where the user clicks. One issue now I faces is that circle is now draw at the place where the inputbox show up. I actually have a function to repaint every circle on the form, but it still does not work. Here is my code:

private void Form1_MouseClick(object sender, MouseEventArgs e)
    {
        string ProvinceName;
        System.Drawing.SolidBrush myBrush = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Graphics formGraphics;
        formGraphics = this.CreateGraphics();

        formGraphics.FillEllipse(myBrush, new Rectangle(e.X, e.Y, 10, 10));

        ProvinceName = Microsoft.VisualBasic.Interaction.InputBox("郡名", "", "无名",100,100);

        provinces.Add(new province(ProvinceName, e.X, e.Y));

        listBox1.SelectedIndex = provinces.Count - 1;

        myBrush.Dispose();
        formGraphics.Dispose();
        PaintMap();// This is the function repaint every recorded clicked locations.

    }