问:
How to unzip a zipped folder with rubyzip
I know how to retrieve the contents of a normal zip-file with rubyzip. But i got trouble unzipping the contents of a zipped folder and i hope any of u guys can help me out.

this is the code i use to unzip:

```<code>Zip::ZipFile::open(@file_location) do |zip|
 zip.each do |entry|
  next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?
  logger.debug "#{entry.name}"
  @data = File.new("#{Rails.root.to_s}/tmp/#{entry.name}")
 end
end
</code>```

entry.name gives me the name of the file inside the zip-file. This works perfectly with a normal zipfile. But when the zipfile is created from a folder, then the name of the entries are something like: test-folder/test.pdf. When i then try to create the file, it tells me the file can not be found. This is probably because it is inside the "test"-folder that is inside the zip.

If i check the entry to be a folder, no folder can be found. So i thought the solution to be to read the entry as a stream and then save it as a file. It is easy to get the entry-stream, but how do I save it as a file? This is what i got so far.

```<code>Zip::ZipFile::open(@file_location) do |zip|
 zip.each do |entry|
  next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?
  logger.debug "#{entry.name}"
  @data = entry.get_input_stream.read
  # How do i create a file from a stream?
 end
end
</code>```

Basically my question is: how can i create a file from a stream? Or is there an easier approach to this than mine?

===EDIT===
I use paperclip to store the files.

答:
I solved it by using a stream and creating a StringIO. Here is the code</p>

```<code>Zip::ZipFile::open(@file_location) do |zip|
 zip.each do |entry|
  next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?

  begin
   # the normal unzip-code
  rescue Errno::ENOENT
   # when the entry can not be found
   @data = entry.get_input_stream.read
   @file = StringIO.new(@data)
   @file.class.class_eval { attr_accessor :original_filename, :content_type }
   @file.original_filename = entry.name
   @file.content_type = MIME::Types.type_for(entry.name)

   # save it / whatever
  end
 end
end
</code>```

Body:
I know how to retrieve the contents of a normal zip-file with rubyzip. But i got trouble unzipping the contents of a zipped folder and i hope any of u guys can help me out.

this is the code i use to unzip:

Zip::ZipFile::open(@file_location) do |zip|
 zip.each do |entry|
  next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?
  logger.debug "#{entry.name}"
  @data = File.new("#{Rails.root.to_s}/tmp/#{entry.name}")
 end
end

entry.name gives me the name of the file inside the zip-file. This works perfectly with a normal zipfile. But when the zipfile is created from a folder, then the name of the entries are something like: test-folder/test.pdf. When i then try to create the file, it tells me the file can not be found. This is probably because it is inside the "test"-folder that is inside the zip.

If i check the entry to be a folder, no folder can be found. So i thought the solution to be to read the entry as a stream and then save it as a file. It is easy to get the entry-stream, but how do I save it as a file? This is what i got so far.

Zip::ZipFile::open(@file_location) do |zip|
 zip.each do |entry|
  next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?
  logger.debug "#{entry.name}"
  @data = entry.get_input_stream.read
  # How do i create a file from a stream?
 end
end

Basically my question is: how can i create a file from a stream? Or is there an easier approach to this than mine?

===EDIT===
I use paperclip to store the files.

Body:
I solved it by using a stream and creating a StringIO. Here is the code

Zip::ZipFile::open(@file_location) do |zip|
 zip.each do |entry|
  next if entry.name =~ /__MACOSX/ or entry.name =~ /\.DS_Store/ or !entry.file?

  begin
   # the normal unzip-code
  rescue Errno::ENOENT
   # when the entry can not be found
   @data = entry.get_input_stream.read
   @file = StringIO.new(@data)
   @file.class.class_eval { attr_accessor :original_filename, :content_type }
   @file.original_filename = entry.name
   @file.content_type = MIME::Types.type_for(entry.name)

   # save it / whatever
  end
 end
end


来源: stackexchange

问:
Can we set the order or any type of priority while running android test cases?
Suppose there is an android specific test cases is given as follows, as android instrumentation test cases running order is always not the same,

```<code>public class MainActivityUnitTest extends
    android.test.ActivityUnitTestCase<MainActivity> {

  private int buttonId;
  private MainActivity activity;

  public MainActivityUnitTest() {
    super(MainActivity.class);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    Intent intent = new Intent(getInstrumentation().getTargetContext(),
        MainActivity.class);
    startActivity(intent, null, null);
    activity = getActivity();
  }

  public void testLayout() {
    buttonId = com.vogella.android.test.simpleactivity.R.id.button1;
    assertNotNull(activity.findViewById(buttonId));
    Button view = (Button) activity.findViewById(buttonId);
    assertEquals("Incorrect label of the button", "Start", view.getText());
  }
  public void testLayoutFirst() {//some test cases specific code here ....}
  public void testLayoutSecond() {//some test cases specific code} here...}

  public void testIntentTriggerViaOnClick() {
    buttonId = com.vogella.android.test.simpleactivity.R.id.button1;
    Button view = (Button) activity.findViewById(buttonId);
    assertNotNull("Button not allowed to be null", view);

    view.performClick();

    // TouchUtils cannot be used, only allowed in
    // InstrumentationTestCase or ActivityInstrumentationTestCase2

    // Check the intent which was started
    Intent triggeredIntent = getStartedActivityIntent();
    assertNotNull("Intent was null", triggeredIntent);
    String data = triggeredIntent.getExtras().getString("URL");

    assertEquals("Incorrect data passed via the intent",
        "http://www.vogella.com", data);
  }

}
</code>```

Question : My question is , is there any way that we can set the order of android instrumentation test cases while they are running as i always seen that the running order of android test cases may same or different every time, so can we set any type of priority or order of there running sequence?.

In the above given test case code there are more than one test cases and each time the running sequence may differ than the previous one , so can we have a fixed order of there running sequence?

答:
Use the annotation below, </p>

```<code>@FixMethodOrder(MethodSorters.NAME_ASCENDING)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Suppose there is an android specific test cases is given as follows, as android instrumentation test cases running order is always not the same,

public class MainActivityUnitTest extends
    android.test.ActivityUnitTestCase<MainActivity> {

  private int buttonId;
  private MainActivity activity;

  public MainActivityUnitTest() {
    super(MainActivity.class);
  }
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    Intent intent = new Intent(getInstrumentation().getTargetContext(),
        MainActivity.class);
    startActivity(intent, null, null);
    activity = getActivity();
  }

  public void testLayout() {
    buttonId = com.vogella.android.test.simpleactivity.R.id.button1;
    assertNotNull(activity.findViewById(buttonId));
    Button view = (Button) activity.findViewById(buttonId);
    assertEquals("Incorrect label of the button", "Start", view.getText());
  }
  public void testLayoutFirst() {//some test cases specific code here ....}
  public void testLayoutSecond() {//some test cases specific code} here...}

  public void testIntentTriggerViaOnClick() {
    buttonId = com.vogella.android.test.simpleactivity.R.id.button1;
    Button view = (Button) activity.findViewById(buttonId);
    assertNotNull("Button not allowed to be null", view);

    view.performClick();

    // TouchUtils cannot be used, only allowed in
    // InstrumentationTestCase or ActivityInstrumentationTestCase2

    // Check the intent which was started
    Intent triggeredIntent = getStartedActivityIntent();
    assertNotNull("Intent was null", triggeredIntent);
    String data = triggeredIntent.getExtras().getString("URL");

    assertEquals("Incorrect data passed via the intent",
        "http://www.vogella.com", data);
  }

}

Question : My question is , is there any way that we can set the order of android instrumentation test cases while they are running as i always seen that the running order of android test cases may same or different every time, so can we set any type of priority or order of there running sequence?.

In the above given test case code there are more than one test cases and each time the running sequence may differ than the previous one , so can we have a fixed order of there running sequence?

Body:
Use the annotation below,

@FixMethodOrder(MethodSorters.NAME_ASCENDING)

ContentLicense: CC BY-SA 4.0


问:
Excel VBA Formula not calculating
I am trying to place a formula into the databodyrange of a table. However after the first row the formula is just placed into the cell and not calculated. It displays to formula as text.

I can even just click into the cell, press "Enter", and then it will calculate perfectly.

The cell format is correctly set to percentage.
Calculations are set to automatic.

my code is as follows

```<code>If i = 0 Then
    Set LastRow = DeviceTable.ListRows(1)
Else
    Set LastRow = DeviceTable.ListRows.Add
End If
LastRow.Range(3).Formula = formula
LastRow.Range(3).NumberFormat = "0%"
</code>```

答: I found that making it a percentage first, then adding the formula solved my problem.</p>

Title: Excel VBA Formula not calculating

Body:
I am trying to place a formula into the databodyrange of a table. However after the first row the formula is just placed into the cell and not calculated. It displays to formula as text.

I can even just click into the cell, press "Enter", and then it will calculate perfectly.

The cell format is correctly set to percentage.
Calculations are set to automatic.

my code is as follows

If i = 0 Then
    Set LastRow = DeviceTable.ListRows(1)
Else
    Set LastRow = DeviceTable.ListRows.Add
End If
LastRow.Range(3).Formula = formula
LastRow.Range(3).NumberFormat = "0%"


问:
Regex to get instagram picture (PHP)
I'm trying to use a regular expression to check if a URL is an Instagram picture and return just the beginning part of the URL with the /p/PICTUREID

So far this is what I've been able to come up with:

```<code>^(.*instagram.com\/p\/.*)\/
</code>```

This however requires there to be a trailing slash but I do not want to require it.

Examples (that should match):

```<code>https://www.instagram.com/p/BKbwlrfjGHY/?post->
https://www.instagram.com/p/BKbwlrfjGHY

http://www.instagram.com/p/BKbwlrfjGHY/ ->
http://www.instagram.com/p/BKbwlrfjGHY

instagram.com/p/BKbwlrfjGHY ->
instagram.com/p/BKbwlrfjGHY
</code>```

How do I stop at the trailing slash if it exists and anything else after?

Here is my regex101 for testing:

https://regex101.com/r/JJS2kz/1

Title: Regex to get instagram picture (PHP)

Body:
I'm trying to use a regular expression to check if a URL is an Instagram picture and return just the beginning part of the URL with the /p/PICTUREID

So far this is what I've been able to come up with:

^(.*instagram.com\/p\/.*)\/

This however requires there to be a trailing slash but I do not want to require it.

Examples (that should match):

https://www.instagram.com/p/BKbwlrfjGHY/?post->
https://www.instagram.com/p/BKbwlrfjGHY

http://www.instagram.com/p/BKbwlrfjGHY/ ->
http://www.instagram.com/p/BKbwlrfjGHY

instagram.com/p/BKbwlrfjGHY ->
instagram.com/p/BKbwlrfjGHY

How do I stop at the trailing slash if it exists and anything else after?

Here is my regex101 for testing:

https://regex101.com/r/JJS2kz/1

Body: (https?:\/\/www\.)?(?:instagram.com|instagr.am)\/p\/([^\/]*)\/?


问:
Xcode 11 backward compatibility: "UIWindowScene is only available in iOS 13 or newer"
In Xcode 11, I created a new app project from the Single View App template. I want this app to run in iOS 12 as well as iOS 13. But when I switch the deployment target to iOS 12, I got a lot of error messages like this one:

UIWindowScene is only available in iOS 13 or newer

What should I do?

答:
Could you please add this line code like the following

STEP1:-

@available out the SceneDelegate.swift

```<code>@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

//...

}
</code>```

STEP2:-

@available out some methods in AppDelegate.swift

```<code>// AppDelegate.swift

@available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

@available(iOS 13.0, *)
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}
</code>```

STEP3:-

You should declare window property in AppDelegate.swift file
 like var window: UIWindow?

```<code>class AppDelegate: UIResponder, UIApplicationDelegate {

     var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }
</code>```

Body:
Could you please add this line code like the following

STEP1:-

@available out the SceneDelegate.swift

@available(iOS 13.0, *)
class SceneDelegate: UIResponder, UIWindowSceneDelegate {

//...

}

STEP2:-

@available out some methods in AppDelegate.swift

// AppDelegate.swift

@available(iOS 13.0, *)
func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}

@available(iOS 13.0, *)
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

STEP3:-

You should declare window property in AppDelegate.swift file
 like var window: UIWindow?

class AppDelegate: UIResponder, UIApplicationDelegate {

     var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }


问:
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?

答:
If you don't want to convert to list, you can try str.translate, str.maketrans and repr:

```<code>>>> import numpy as np
>>> x = [[1,2,3],[4,5,6]]
>>> np.asarray(x)
array([[1, 2, 3],      # <------ repr
       [4, 5, 6]])
>>> print(np.asarray(x))
[[1 2 3]
 [4 5 6]]
>>> s = repr(np.asarray(x))
>>> print(s.translate(
                      str.maketrans({' ': '', '\n': '\n ', ',': ', '}))
                     .strip('array(/)')
          )
[[1, 2, 3],
 [4, 5, 6]]
</code>```

Or, much simply:

```<code>>>> print(str(np.asarray(x)).replace(' ',', ').replace('\n, ',',\n '))
[[1, 2, 3],
 [4, 5, 6]]
</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:
If you don't want to convert to list, you can try str.translate, str.maketrans and repr:

>>> import numpy as np
>>> x = [[1,2,3],[4,5,6]]
>>> np.asarray(x)
array([[1, 2, 3],      # <------ repr
       [4, 5, 6]])
>>> print(np.asarray(x))
[[1 2 3]
 [4 5 6]]
>>> s = repr(np.asarray(x))
>>> print(s.translate(
                      str.maketrans({' ': '', '\n': '\n ', ',': ', '}))
                     .strip('array(/)')
          )
[[1, 2, 3],
 [4, 5, 6]]

Or, much simply:

>>> print(str(np.asarray(x)).replace(' ',', ').replace('\n, ',',\n '))
[[1, 2, 3],
 [4, 5, 6]]


问:
How do I "clean" a String in PHP using regex?
For example suppose I have

```<code>$blah = "C$#@#.a534&";
</code>```

I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"

How do I do this?

答:
http://php.net/manual/en/function.preg-replace.php

replace all non-valid characters with the empty string.

Body:
For example suppose I have

$blah = "C$#@#.a534&";

I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"

How do I do this?


问:
How to show toast message using JobScheduler
I have been learning jobscheduler in andorid. I have trying to show a toast message in the onstartjob() after every 1minute. But its not showing up. Any help will be grateful.

jobschedul_service .class:

```<code>package com.prajwal.jobscheduler;

import android.app.Service;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class jobschedul_service extends JobService {

    @Override
    public boolean onStartJob(JobParameters jobParameters) {

        Toast.makeText(getApplicationContext(), "After 15 minutes", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}
</code>```

MainActivity.class:

```<code>package com.prajwal.jobscheduler;

import androidx.appcompat.app.AppCompatActivity;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_ARTWORK_JOB_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        JobScheduler jobScheduler =
                (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder
                (LOAD_ARTWORK_JOB_ID, new ComponentName(this, jobschedul_service.class))
                .setPeriodic(900000)
                .build());
    }
}
</code>```

Manifest.xml:

```<code>  <service
        android:name=".jobschedul_service"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BIND_JOB_SERVICE"></service>
</code>```

答:
Got the answer!

The reason was the setperiodic(long interval).

As per the ss below:

This function was added in API 21 i.e Lolipop version. Whereas I was running the app on version > Lolipop.

Whereas this new function in the image below:

was added in API 24 i.e. Nougat

Hence, if you are targetting your app below Nougat i.e < Nougat but >= Lolipop then use setPeriodic(long interval) method whereas if u r targetting >= Nougat then use setPeriodic(long interval, long flexinterval).

Solution

```<code> if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        {
            builder.setPeriodic(900000,6000);
        }
        else
        {
            builder.setPeriodic(900000);
        }
</code>```

Body:
I have been learning jobscheduler in andorid. I have trying to show a toast message in the onstartjob() after every 1minute. But its not showing up. Any help will be grateful.

jobschedul_service .class:

package com.prajwal.jobscheduler;

import android.app.Service;
import android.app.job.JobParameters;
import android.app.job.JobScheduler;
import android.app.job.JobService;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class jobschedul_service extends JobService {

    @Override
    public boolean onStartJob(JobParameters jobParameters) {

        Toast.makeText(getApplicationContext(), "After 15 minutes", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return true;
    }
}

MainActivity.class:

package com.prajwal.jobscheduler;

import androidx.appcompat.app.AppCompatActivity;

import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    private static final int LOAD_ARTWORK_JOB_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        JobScheduler jobScheduler =
                (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
        jobScheduler.schedule(new JobInfo.Builder
                (LOAD_ARTWORK_JOB_ID, new ComponentName(this, jobschedul_service.class))
                .setPeriodic(900000)
                .build());
    }
}

Manifest.xml:

  <service
        android:name=".jobschedul_service"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.BIND_JOB_SERVICE"></service>

Body:
Got the answer!

The reason was the setperiodic(long interval).

As per the ss below:

This function was added in API 21 i.e Lolipop version. Whereas I was running the app on version > Lolipop.

Whereas this new function in the image below:

was added in API 24 i.e. Nougat

Hence, if you are targetting your app below Nougat i.e < Nougat but >= Lolipop then use setPeriodic(long interval) method whereas if u r targetting >= Nougat then use setPeriodic(long interval, long flexinterval).

Solution

 if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        {
            builder.setPeriodic(900000,6000);
        }
        else
        {
            builder.setPeriodic(900000);
        }


问:
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

答:
Try the following:

introduce filter with an isVisible property

```<code>search(value: string) {
    return this.selectedStates.map(k => ({...k, isVisible:(k.name.toLowerCase().indexOf(value.toLowerCase()) > -1)}))
}
</code>```

add a getter for the filtered state

```<code>get filteredState() {
     return  this.selectedStates.filter(k=> k.isVisible === undefined || k.isVisible)
}
</code>```

then in your html replace selectedStates with filteredState

<mat-option *ngFor="let state of filteredState" [value]="state">{{state.name}}</mat-option>
```

TS Note: that you should replace states: string[] with states: any[] or with the object you are using

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:
Try the following:

introduce filter with an isVisible property

search(value: string) {
    return this.selectedStates.map(k => ({...k, isVisible:(k.name.toLowerCase().indexOf(value.toLowerCase()) > -1)}))
}

add a getter for the filtered state

get filteredState() {
     return  this.selectedStates.filter(k=> k.isVisible === undefined || k.isVisible)
}

then in your html replace selectedStates with filteredState

<mat-option *ngFor="let state of filteredState" [value]="state">{{state.name}}</mat-option>

TS Note: that you should replace states: string[] with states: any[] or with the object you are using


问:
Adding 12 months to February 29
I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

```<code>$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));
</code>```

Output:

```<code>03/01/2021
</code>```

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.

答:
using DateTime and DateInterval objects leads to 03/01/2021

```<code>$date = new \DateTime('02/29/2020');
$date->add(new \DateInterval('P12M'));
echo $date->format('m/d/Y');
</code>```

for me 03/01/2021 is not always a bad answer

Title: Adding 12 months to February 29

Body:
I want to add 12 months to my date. My start date is 02/29/2020 and I want to add 12 months to this.

Code:

$startdate = '02/29/2020';
date('m/d/Y', strtotime('+12 months', strtotime($startdate)));

Output:

03/01/2021

I used this code to add 12 months but the output is 03/01/2021, when the real output should be 02/28/2020.

Body:
using DateTime and DateInterval objects leads to 03/01/2021

$date = new \DateTime('02/29/2020');
$date->add(new \DateInterval('P12M'));
echo $date->format('m/d/Y');

for me 03/01/2021 is not always a bad answer


答:
If you know what characters should be allowed, you can use a negated character group (in a regular expression) to remove everything else:

```<code>$blah = preg_replace('/[^a-z0-9\.]/i', '', $blah);
</code>```

Note that i am using the i modifier for the regular expression. It matches case-insensitive, so that we do not need to specify a-z and A-Z.

Title: How do I "clean" a String in PHP using regex?

Body:
If you know what characters should be allowed, you can use a negated character group (in a regular expression) to remove everything else:

$blah = preg_replace('/[^a-z0-9\.]/i', '', $blah);

Note that i am using the i modifier for the regular expression. It matches case-insensitive, so that we do not need to specify a-z and A-Z.


答:
You may be confusing actual data structures with their displays.

If I copy-n-paste your 'normal array with commas':

```<code>In [593]: alist = [[392, 200],
     ...:  [461, 194],
     ...:  [392, 200],
     ...:  [161, 202]]
</code>```

I get a nested list, which displays as:

```<code>In [594]: alist
Out[594]: [[392, 200], [461, 194], [392, 200], [161, 202]]
</code>```

That's comma separated, but not broken into neat lines.

If I make a numpy array from that:

```<code>In [595]: arr = np.array(alist)
In [596]: arr
Out[596]:
array([[392, 200],
       [461, 194],
       [392, 200],
       [161, 202]])
</code>```

The repr display of the array includes the commas, but the str display omits them:

```<code>In [597]: print(arr)
[[392 200]
 [461 194]
 [392 200]
 [161 202]]
</code>```

That's the same array, same data structure, but with different display strings.

We can get a list from that with:

```<code>In [599]: arr.tolist()
Out[599]: [[392, 200], [461, 194], [392, 200], [161, 202]]
</code>```

But the differences between list and ndarray are much bigger than the comma-or-not display.

Title: How to convert asarray's output back to normal array in Python?

Body:
You may be confusing actual data structures with their displays.

If I copy-n-paste your 'normal array with commas':

In [593]: alist = [[392, 200],
     ...:  [461, 194],
     ...:  [392, 200],
     ...:  [161, 202]]

I get a nested list, which displays as:

In [594]: alist
Out[594]: [[392, 200], [461, 194], [392, 200], [161, 202]]

That's comma separated, but not broken into neat lines.

If I make a numpy array from that:

In [595]: arr = np.array(alist)
In [596]: arr
Out[596]:
array([[392, 200],
       [461, 194],
       [392, 200],
       [161, 202]])

The repr display of the array includes the commas, but the str display omits them:

In [597]: print(arr)
[[392 200]
 [461 194]
 [392 200]
 [161 202]]

That's the same array, same data structure, but with different display strings.

We can get a list from that with:

In [599]: arr.tolist()
Out[599]: [[392, 200], [461, 194], [392, 200], [161, 202]]

But the differences between list and ndarray are much bigger than the comma-or-not display.


问:
None type object has no attribute delete()

getting error 'NoneType' object has no attribute 'delete'

```<code>class LogoutViewSet(viewsets.ViewSet):

    def (self,request):
        user_token=request.auth
        refresh_token=RefreshToken.objects.filter(access_token=user_token)
        refresh_token.delete()
        user_token.delete()
        return Response({'done':True})
</code>```

答:
class LogoutViewSet(viewsets.ViewSet):

```<code>def list(self,request):
    try:
        user_token=request.auth
        print('TOKEN',request.auth)
        refresh_token=RefreshToken.objects.filter(access_token=user_token)
        refresh_token.delete()
        user_token.delete()
        return Response({'done':True})
    except Exception as error:
        return Response({"message": str(error), "success": False},
        status=status.HTTP_200_OK)
</code>```

then follo steps

1:in postman select GET
2:unser Header type (i)=Key=Authorization
               type (ii)=Value=Bearer CMEIe8hv8eMYvAcLyTGpAlXMpUb0Qz(token)

Body:
getting error 'NoneType' object has no attribute 'delete'

class LogoutViewSet(viewsets.ViewSet):

    def (self,request):
        user_token=request.auth
        refresh_token=RefreshToken.objects.filter(access_token=user_token)
        refresh_token.delete()
        user_token.delete()
        return Response({'done':True})

Body:
class LogoutViewSet(viewsets.ViewSet):

def list(self,request):
    try:
        user_token=request.auth
        print('TOKEN',request.auth)
        refresh_token=RefreshToken.objects.filter(access_token=user_token)
        refresh_token.delete()
        user_token.delete()
        return Response({'done':True})
    except Exception as error:
        return Response({"message": str(error), "success": False},
        status=status.HTTP_200_OK)

then follo steps

1:in postman select GET
2:unser Header type (i)=Key=Authorization
               type (ii)=Value=Bearer CMEIe8hv8eMYvAcLyTGpAlXMpUb0Qz(token)


问:
JSON parsing error syntax error unexpected end of input
I got the following piece of code

```<code>function pushJsonData(productName) {
    $.ajax({
        url: "/knockout/SaveProduct",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: " { \"Name\" : \"AA\" } ",
        async: false,
        success: function () {
            loadJsonData();
        },
        error: function (jqXHR, textStatus, errorThrown) {
          alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
        }
    });
}
</code>```

Notice that I hard coded the data value. The data get pushed into the database fine. However, I keep getting the error

parsing error syntax error unexpected end of input

I am sure my data is in correct JSON syntax. When I checked with on Network of Chrome inspector the saveProduct request showed the data is correct.

```<code>{ "Name": "AA" }
</code>```

This POST request did not have response. So I am clueless as to where the parse error was coming from. I tried using FireFox browser. the same thing happened.

Can anyone give some idea as to what is wrong?

Thanks,

P.S.
Here is the controller code

```<code>namespace MvcApplJSON.Controllers
{
    public class KnockoutController : Controller
    {
        //
        // GET: /Knockout/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetProductList()
        {
            var model = new List<Product>();
            try
            {
                using (var db = new KOEntities())
                {
                    var product = from p in db.Products orderby p.Name select p;
                    model = product.ToList();
                }
            }
            catch (Exception ex)
            { throw ex; }
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public void SaveProduct (Product product)
        {
            using (var db = new KOEntities())
            {
                db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
                db.SaveChanges();
            }
        }
    }
}
</code>```

答:
Don't Return Empty Json

In My Case I was returning Empty Json String in .Net Core Web API Project.

So I Changed My Code

From

```<code> return Ok();
</code>```

To

```<code> return Ok("Done");
</code>```

It seems you have to return some string or object.

Hope this helps.

Body:
I got the following piece of code

function pushJsonData(productName) {
    $.ajax({
        url: "/knockout/SaveProduct",
        type: "POST",
        contentType: "application/json",
        dataType: "json",
        data: " { \"Name\" : \"AA\" } ",
        async: false,
        success: function () {
            loadJsonData();
        },
        error: function (jqXHR, textStatus, errorThrown) {
          alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
        }
    });
}

Notice that I hard coded the data value. The data get pushed into the database fine. However, I keep getting the error

parsing error syntax error unexpected end of input

I am sure my data is in correct JSON syntax. When I checked with on Network of Chrome inspector the saveProduct request showed the data is correct.

{ "Name": "AA" }

This POST request did not have response. So I am clueless as to where the parse error was coming from. I tried using FireFox browser. the same thing happened.

Can anyone give some idea as to what is wrong?

Thanks,

P.S.
Here is the controller code

namespace MvcApplJSON.Controllers
{
    public class KnockoutController : Controller
    {
        //
        // GET: /Knockout/

        public ActionResult Index()
        {
            return View();
        }

        [HttpGet]
        public JsonResult GetProductList()
        {
            var model = new List<Product>();
            try
            {
                using (var db = new KOEntities())
                {
                    var product = from p in db.Products orderby p.Name select p;
                    model = product.ToList();
                }
            }
            catch (Exception ex)
            { throw ex; }
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public void SaveProduct (Product product)
        {
            using (var db = new KOEntities())
            {
                db.Products.Add(new Product { Name = product.Name, DateCreated = DateTime.Now });
                db.SaveChanges();
            }
        }
    }
}

Body:
Don't Return Empty Json

In My Case I was returning Empty Json String in .Net Core Web API Project.

So I Changed My Code

From

 return Ok();

To

 return Ok("Done");

It seems you have to return some string or object.

Hope this helps.


Title: How to transform given dataset in python?

Body:
            1           0.0   6.400000000
            2   6.400000000          27.0
            2          27.0  27.100000000
            2  27.100000000  27.400000000
            2  27.400000000  27.700000000
            2  27.700000000  30.600000000
            1  30.600000000          31.0
            1          31.0  36.600000000
            1  36.600000000  36.900000000
            1  36.900000000  37.100000000
            1  37.100000000  37.100000000
            1  37.100000000  37.300000000
            1  37.300000000  37.800000000
            1  37.800000000  38.900000000
            1  38.900000000  39.200000000
            1  39.200000000  39.300000000
            1  39.300000000  39.500000000
            1  39.500000000  39.700000000
            2  39.700000000  42.600000000
            2  42.600000000  42.600000000
            2  42.600000000  42.800000000
            1  42.800000000  44.900000000
            1  44.900000000  45.600000000
            2  45.600000000          51.0
            1          51.0  51.800000000

            1           0.0   6.400000000
            2   6.400000000  30.600000000
            1  30.600000000  39.500000000
... so on

I want to transform my data in the above format. I tried this with groupBy min and max for column but it seems like it doesn't give me the desirable results.

Body:
It seems data are not numeric, so first change them to numeric and then use GroupBy.agg with named aggregation working in pandas 0.25+:

df[['b','c']] = df[['b','c']].astype(float)
df1 = (df.groupby('a').agg(min_b=('b','min'),
                           max_b=('b','max'),
                           min_c=('c','min'),
                           max_c=('c','max'))
                      .reset_index())
print (df1)
   a  min_b  max_b  min_c  max_c
0  1    0.0   51.0    6.4   51.8
1  2    6.4   45.6   27.0   51.0

Setup:

   a             b             c
0  1           0.0   6.400000000
1  2   6.400000000          27.0
2  2          27.0  27.100000000
3  2  27.100000000  27.400000000
4  2  27.400000000  27.700000000
...
...
...

If need each groups separately:

df[['b','c']] = df[['b','c']].astype(float)
df1 = (df.groupby(df['a'].ne(df['a'].shift()).cumsum())
         .agg(a=('a','first'),
              min_b=('b','min'),
              max_b=('b','max'),
              min_c=('c','min'),
              max_c=('c','max'))
         .reset_index(drop=True))
print (df1)
   a  min_b  max_b  min_c  max_c
0  1    0.0    0.0    6.4    6.4
1  2    6.4   27.7   27.0   30.6
2  1   30.6   39.5   31.0   39.7
3  2   39.7   42.6   42.6   42.8
4  1   42.8   44.9   44.9   45.6
5  2   45.6   45.6   51.0   51.0
6  1    0.0   51.0    6.4   51.8
7  2    6.4    6.4   30.6   30.6
8  1   30.6   30.6   39.5   39.5


问:
mysql array of objects compare items
I have problem in mysql json that I want to compare one item of object in json array.
example:
in my table i have column aJson that is array :

```<code>[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":2}]
</code>```

I want to find the records where Code is greater than 3

output:

```<code>[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":8}]
</code>```

same for equal,less,like ...

答:
I think it can be solved using JSON_EXTRACT which is available in MySQL version >= 5.7

```<code>mysql> SELECT mycolumn
     > FROM mytable
     > WHERE mycolumn->"$.Code" > 3
</code>```

-> is an alias for JSON_EXTRACT

Ref:

https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#operator_json-column-path

Title: mysql array of objects compare items

Body:
I have problem in mysql json that I want to compare one item of object in json array.
example:
in my table i have column aJson that is array :

[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":2}]

I want to find the records where Code is greater than 3

output:

[{"Name":"Mohsen","Code":3},{"Name":"Ali","Code":5},{"Name":"Reza","Code":8}]

same for equal,less,like ...

Body:
I think it can be solved using JSON_EXTRACT which is available in MySQL version >= 5.7

mysql> SELECT mycolumn
     > FROM mytable
     > WHERE mycolumn->"$.Code" > 3

-> is an alias for JSON_EXTRACT

Ref:

https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#operator_json-column-path


问:
Hive UDF with Python error code return code 20001

import sys
import datetime
count = 0
try:
        for line in sys.stdin:
                orders= line.split(',')
                order_id = orders[0]
                order_time = orders[1]
                order_status = orders[3]
                order_status = order_status[:-1]
                order_date = order_time.split(" ")[0]
                #print '\t'.join([order_id, str(order_status)])
                if order_status == 'COMPLETE' and order_date[:4] == '2014':
                #print('{0} is {1}'.format(order_id,order_status))
                #print(order_date[:4])
                        count+=1
        print(count)
except:
        print sys.exc_info()```
</div>
</div>

I'm learning how to execute simple user-defined functions on
hive with python
I'm trying to execute the above python code on my hive table which contains comma-separated values
I tried cat orders.txt| python newworld.py and the output counts values perfectly. However, i'm unable to get the same output from the hive</p>
<p>error code below</p>
```[Error 20001]: An error occurred while reading or writing to your custom script. It may have crashed with an error.
        at org.apache.hadoop.hive.ql.exec.ScriptOperator.processOp(ScriptOperator.java:468)
        at org.apache.hadoop.hive.ql.exec.Operator.forward(Operator.java:815)
        at org.apache.hadoop.hive.ql.exec.SelectOperator.processOp(SelectOperator.java:84)
        at org.apache.hadoop.hive.ql.exec.Operator.forward(Operator.java:815)
        at org.apache.hadoop.hive.ql.exec.TableScanOperator.processOp(TableScanOperator.java:98)
        at org.apache.hadoop.hive.ql.exec.MapOperator$MapOpCtx.forward(MapOperator.java:157)
        at org.apache.hadoop.hive.ql.exec.MapOperator.process(MapOperator.java:497)
        ... 9 more
Caused by: java.io.IOException: Stream closed
```

答:
This is definitely late and hopefully you've solved this issue already, but for reference to those who have come across this: even if the original file is delimited by commas, Hive will delimit them by tabs instead. Thus, if you replaced the ',' with '\t' like:

```<code>orders= line.split('\t')
</code>```

assuming the rest of the code runs when you were debugging it directly with the txt file, it should work.

p.s. Unfortunately, I have never found the error codes to be helpful

Body:
import sys
import datetime
count = 0
try:
        for line in sys.stdin:
                orders= line.split(',')
                order_id = orders[0]
                order_time = orders[1]
                order_status = orders[3]
                order_status = order_status[:-1]
                order_date = order_time.split(" ")[0]
                #print '\t'.join([order_id, str(order_status)])
                if order_status == 'COMPLETE' and order_date[:4] == '2014':
                #print('{0} is {1}'.format(order_id,order_status))
                #print(order_date[:4])
                        count+=1
        print(count)
except:
        print sys.exc_info()

I'm learning how to execute simple user-defined functions on
hive with python
I'm trying to execute the above python code on my hive table which contains comma-separated values
I tried cat orders.txt| python newworld.py and the output counts values perfectly. However, i'm unable to get the same output from the hive

error code below

[Error 20001]: An error occurred while reading or writing to your custom script. It may have crashed with an error.
        at org.apache.hadoop.hive.ql.exec.ScriptOperator.processOp(ScriptOperator.java:468)
        at org.apache.hadoop.hive.ql.exec.Operator.forward(Operator.java:815)
        at org.apache.hadoop.hive.ql.exec.SelectOperator.processOp(SelectOperator.java:84)
        at org.apache.hadoop.hive.ql.exec.Operator.forward(Operator.java:815)
        at org.apache.hadoop.hive.ql.exec.TableScanOperator.processOp(TableScanOperator.java:98)
        at org.apache.hadoop.hive.ql.exec.MapOperator$MapOpCtx.forward(MapOperator.java:157)
        at org.apache.hadoop.hive.ql.exec.MapOperator.process(MapOperator.java:497)
        ... 9 more
Caused by: java.io.IOException: Stream closed

Body:
This is definitely late and hopefully you've solved this issue already, but for reference to those who have come across this: even if the original file is delimited by commas, Hive will delimit them by tabs instead. Thus, if you replaced the ',' with '\t' like:

orders= line.split('\t')

assuming the rest of the code runs when you were debugging it directly with the txt file, it should work.

p.s. Unfortunately, I have never found the error codes to be helpful


问:
Import-loop in R (read.csv)
I tried to import *.csv files with ongoing numbers in the mid of the name - so I tried to use a for-loop to generate the number and paste it into the filenames:

```<code>for (Number in 20:30){
  (paste("Test.",Number,"File"))<- read.csv("~/Test.-",Number,"File".csv", sep=";", comment.char="#")

}
</code>```

How can I avoid the blank, so the Import does work? Any other Suggestions?
Thanks a lot!

答:
Using "," in sep="," helped me. Thanks to manaR, Cedric .

```<code>for (i in 1:96){
  d <- read.csv(str_c("GRID_",Number,".csv"), sep=",",comment.char="#")
  source("Function_for grid.R")
}
</code>```

Title: Import-loop in R (read.csv)

Body:
I tried to import *.csv files with ongoing numbers in the mid of the name - so I tried to use a for-loop to generate the number and paste it into the filenames:

for (Number in 20:30){
  (paste("Test.",Number,"File"))<- read.csv("~/Test.-",Number,"File".csv", sep=";", comment.char="#")

}

How can I avoid the blank, so the Import does work? Any other Suggestions?
Thanks a lot!

Body:
Using "," in sep="," helped me. Thanks to manaR, Cedric .

for (i in 1:96){
  d <- read.csv(str_c("GRID_",Number,".csv"), sep=",",comment.char="#")
  source("Function_for grid.R")
}


问:
Create a Pandas Dataframe by appending one row at a time
How do I create an empty DataFrame, then add rows, one by one?

I created an empty DataFrame:

```<code>df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))
</code>```

Then I can add a new row at the end and fill a single field with:

```<code>df = df._set_value(index=len(df), col='qty1', value=10.0)
</code>```

It works for only one field at a time. What is a better way to add new row to df?

答:
pandas.DataFrame.append

DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) → 'DataFrame'

Code

```<code>df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)
</code>```

With ignore_index set to True:

```<code>df.append(df2, ignore_index=True)
</code>```

Body:
How do I create an empty DataFrame, then add rows, one by one?

I created an empty DataFrame:

df = pd.DataFrame(columns=('lib', 'qty1', 'qty2'))

Then I can add a new row at the end and fill a single field with:

df = df._set_value(index=len(df), col='qty1', value=10.0)

It works for only one field at a time. What is a better way to add new row to df?

Body:
pandas.DataFrame.append

DataFrame.append(self, other, ignore_index=False, verify_integrity=False, sort=False) → 'DataFrame'

Code

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('AB'))
df2 = pd.DataFrame([[5, 6], [7, 8]], columns=list('AB'))
df.append(df2)

With ignore_index set to True:

df.append(df2, ignore_index=True)


问:
How to access nested array and objects in http response In angular
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access specific or multiple values (or keys)?

```<code>{
  "data": [
    {
      "id": 2,
      "addEmployee": {
        "firstName": "Devansh"
      },
      "attendances": [
        {
          "id": 3,
          "checkIn": "2020-02-18T04:36:45.000Z",
          "checkOut": "2020-02-18T11:46:16.000Z",
          "totalHours": "7:9",
          "date": "2020-02-18",
          "status": "present",
          "createdAt": "2020-02-18T04:36:45.000Z",
          "updatedAt": "2020-02-18T11:46:16.000Z",
          "userId": 2
        }
      ]
    }
  ]
}
</code>```

how could i access the firstName and attendances array value

答:
You must be assigning the object to a variable like here I am assigning to val variable.
You can access the properties as below.
You can run the snippet here and see the output

let val =  {
  "data": [
    {
      "id": 2,
      "addEmployee": {
        "firstName": "Devansh"
      },
      "attendances": [
        {
          "id": 3,
          "checkIn": "2020-02-18T04:36:45.000Z",
          "checkOut": "2020-02-18T11:46:16.000Z",
          "totalHours": "7:9",
          "date": "2020-02-18",
          "status": "present",
          "createdAt": "2020-02-18T04:36:45.000Z",
          "updatedAt": "2020-02-18T11:46:16.000Z",
          "userId": 2
        }
      ]
    }
  ]
}

val.data.forEach(eachData => {
  console.log('Employee Name ---> ',eachData.addEmployee.firstName);
  eachData.attendances.forEach(atten => {
    console.log('attendance Object -->',atten);
  })
});```

Body:
I have a nested data structure containing objects and arrays. How can I extract the information, i.e. access specific or multiple values (or keys)?

{
  "data": [
    {
      "id": 2,
      "addEmployee": {
        "firstName": "Devansh"
      },
      "attendances": [
        {
          "id": 3,
          "checkIn": "2020-02-18T04:36:45.000Z",
          "checkOut": "2020-02-18T11:46:16.000Z",
          "totalHours": "7:9",
          "date": "2020-02-18",
          "status": "present",
          "createdAt": "2020-02-18T04:36:45.000Z",
          "updatedAt": "2020-02-18T11:46:16.000Z",
          "userId": 2
        }
      ]
    }
  ]
}

how could i access the firstName and attendances array value


答:
Or do it the other way round:</p>

```<code>$text = preg_replace('/[^a-zA-Z0-9.]/','',$text);
</code>```

Body:
For example suppose I have

$blah = "C$#@#.a534&";

I wish to filter the string so that only letters, numbers and "." remain yielding "C.a534"

How do I do this?

Body:
Or do it the other way round:

$text = preg_replace('/[^a-zA-Z0-9.]/','',$text);


问:
Cannot Create Variable Activity on data Factory
I am trying to create data factory resources using python and I am getting error while calling few classes

example- here I am trying to create "Set Variable Activity" but I am getting error

ref: https://learn.microsoft.com/en-us/python/api/azure-mgmt-datafactory/azure.mgmt.datafactory.models.setvariableactivity?view=azure-python

Error Message

NameError: name 'SetVariableActivity' is not defined

Code

```<code>from azure.mgmt.datafactory.models import *

variable_name = 'vGetDate'
var_activity = SetVariableActivity(name = 'Get Date',variable_name= variable_name, value = '@utcnow()' )
</code>```

I am getting NameError with DatasetFolder Class as well. I am not sure what went wrong, I thought I have imported all the required libraries and I am using on 3.7 v

Any input is greatly appreciated.

答:
I test the code on my side, it works fine, please try the same version of the libraries with me.

```<code>azure-common==1.1.23
azure-mgmt-datafactory==0.9.0
</code>```

My sample creates a pipeline with the Set variable activity:

```<code>from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.datafactory import DataFactoryManagementClient
from azure.mgmt.datafactory.models import *

subscription_id = '<subscription-id>'
credentials = ServicePrincipalCredentials(client_id='<client-id>', secret='<client-secret>', tenant='<tenant-id>')
adf_client = DataFactoryManagementClient(credentials, subscription_id)

variable_name = 'vGetDate'
var_activity = SetVariableActivity(name = 'Get Date',variable_name= variable_name, value = '@utcnow()' )

rg_name = '<resource-group-name>'
df_name = 'joyfactory'
p_name = 'Pipeline123'
params_for_pipeline = {}
p_obj = PipelineResource(
    activities=[var_activity], parameters=params_for_pipeline)
p = adf_client.pipelines.create_or_update(rg_name, df_name, p_name, p_obj)
print(p)
</code>```

Check in the portal:

Body:
I am trying to create data factory resources using python and I am getting error while calling few classes

example- here I am trying to create "Set Variable Activity" but I am getting error

ref: https://learn.microsoft.com/en-us/python/api/azure-mgmt-datafactory/azure.mgmt.datafactory.models.setvariableactivity?view=azure-python

Error Message

NameError: name 'SetVariableActivity' is not defined

Code

from azure.mgmt.datafactory.models import *

variable_name = 'vGetDate'
var_activity = SetVariableActivity(name = 'Get Date',variable_name= variable_name, value = '@utcnow()' )

I am getting NameError with DatasetFolder Class as well. I am not sure what went wrong, I thought I have imported all the required libraries and I am using on 3.7 v

Any input is greatly appreciated.

Body:
I test the code on my side, it works fine, please try the same version of the libraries with me.

azure-common==1.1.23
azure-mgmt-datafactory==0.9.0

My sample creates a pipeline with the Set variable activity:

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.datafactory import DataFactoryManagementClient
from azure.mgmt.datafactory.models import *

subscription_id = '<subscription-id>'
credentials = ServicePrincipalCredentials(client_id='<client-id>', secret='<client-secret>', tenant='<tenant-id>')
adf_client = DataFactoryManagementClient(credentials, subscription_id)

variable_name = 'vGetDate'
var_activity = SetVariableActivity(name = 'Get Date',variable_name= variable_name, value = '@utcnow()' )

rg_name = '<resource-group-name>'
df_name = 'joyfactory'
p_name = 'Pipeline123'
params_for_pipeline = {}
p_obj = PipelineResource(
    activities=[var_activity], parameters=params_for_pipeline)
p = adf_client.pipelines.create_or_update(rg_name, df_name, p_name, p_obj)
print(p)

Check in the portal:


问:
What does 'low in coupling and high in cohesion' mean
I have problems understanding the statement low in coupling and high in cohesion. I have googled and read a lot about this, but still finding it hard to understand.

To what I understand is High cohesion means, that we should have classes that are specialized to perform a particular function. Hope this is correct? Like a credit card validation class, which is specialized to validate credit cards only.

And still don't understand what low Coupling means?

答:
Low Coupling:--
Will keep it very simple.
If you change your module how does it impact other modules.

Example:-
If your service API is exposed as JAR, any change to method signature will break calling API (High/Tight coupling).

If your module and other module communicate via async messages. As long as you get messages, your method change signature will be local to your module (Low coupling).

Off-course if there is change in message format, calling client will need to make some change.


问:
Can vue-router open a link in a new tab?
I have a summary page and a detail subpage. All of the routes are implemented with vue-router (v 0.7.x) using programmatic navigation like this:

```<code>this.$router.go({ path: "/link/to/page" })
</code>```

However, when I route from the summary page to the subpage, I need to open the subpage in a new tab just as one would by adding _target="blank" to an  tag.

Is there a way to do this?

答:
This worked for me-

```<code>let routeData = this.$router.resolve(
{
  path: '/resources/c-m-communities',
  query: {'dataParameter': 'parameterValue'}
});
window.open(routeData.href, '_blank');
</code>```

I modified @Rafael_Andrs_Cspedes_Basterio answer

Body:
I have a summary page and a detail subpage. All of the routes are implemented with vue-router (v 0.7.x) using programmatic navigation like this:

this.$router.go({ path: "/link/to/page" })

However, when I route from the summary page to the subpage, I need to open the subpage in a new tab just as one would by adding _target="blank" to an  tag.

Is there a way to do this?

Body:
This worked for me-

let routeData = this.$router.resolve(
{
  path: '/resources/c-m-communities',
  query: {'dataParameter': 'parameterValue'}
});
window.open(routeData.href, '_blank');

I modified @Rafael_Andrs_Cspedes_Basterio answer


问:
Read Sentinel-2 L1C view angles from rasterio
I am trying to read the view angles from a Sentinel-2 image (L1C SAFE compact format) for executing an atmospheric correction algorithm. I can get those values by parsing the file MTD_TL.xml, but I am not able to get them through rasterio.

I have tried to access to those data using the xml:SENTINEL2 and the xml:VRT metadata domains, but I can only access to the values from the file MTD_MSIL1C.xml (the main metadata file).

The whole point of using rasterio is being able of using GDAL's virtual file system, as the images will be read from S3 buckets. Any alternatives for easily reading MTD_TL.xml through the virtual file system would be also valid (and really appreciated).

Thank you!!

答:
I answer to myself.

I could not find how to get the values I require, but according to https://gdal.org/user/virtual_file_systems.html the function VSIFOpenL may be used for opening the file. After that, manual parsing will do the trick :)

Ps. I must read the documentation slowly.


问:
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>```

答:
There are 2 options

Trigger change event like $("#number").change(). However, your code is repeated numerous code unnecessarily.

You should refactor code like below.

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

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

function AssignThenDisplayValue(value){;
  $("#number").val(value);
  $("#show").text(value);
}```
<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:
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:
There are 2 options

Trigger change event like $("#number").change(). However, your code is repeated numerous code unnecessarily.

You should refactor code like below.

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

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

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

<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 hide a column in output result in Mysql?
```<code>select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
         if(finish_position = 1 , @b:=@b+1,@b:=@b) opening_position,
         if(finish_position = 1 , @last_op:=official_rating,@last_op:=@last_op)last_opening_position,
         cast(if(@b = 0 or finish_position = 1,0,@last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
</code>```

I want to hide

opening_position, last_opening_position

columns from the output result. My Mysql version 8.0.18

答:
```<code>select historic_betfair_win_prices.sf_name,
       historic_runners.finish_position,
       historic_runners.official_rating,
       historic_betfair_win_prices.date,
       historic_betfair_win_prices.bsp,
       cast(if((@b := if(finish_position = 1 ,
                        @b+1,
                        @b))= 0 or finish_position = 1,
               0,
               (@last_op := if(finish_position = 1 ,
                              official_rating,
                              @last_op)) - official_rating) as decimal(10,2)) difffrom historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50
</code>```

Body:
select historic_betfair_win_prices.sf_name,historic_runners.finish_position,historic_runners.official_rating,historic_betfair_win_prices.date, historic_betfair_win_prices.bsp,
         if(finish_position = 1 , @b:=@b+1,@b:=@b) opening_position,
         if(finish_position = 1 , @last_op:=official_rating,@last_op:=@last_op)last_opening_position,
         cast(if(@b = 0 or finish_position = 1,0,@last_op - official_rating) as decimal(10,2)) diff
from historic_runners
inner join historic_betfair_win_prices on historic_betfair_win_prices.runner_id = historic_runners.runner_id and historic_betfair_win_prices.sf_race_id = historic_runners.race_id
cross join (select @b:=0, @last_op :=0) b
where historic_betfair_win_prices.sf_name = "Camanche Grey"
limit 50

I want to hide

opening_position, last_opening_position

columns from the output result. My Mysql version 8.0.18


问:
Changing the content of a div with .html after
After doing so:

```<code>        $.ajax({
            type: "POST",
            url: $("#form").attr("action"),
            data: "value=" + value + "&sel=" + sel,
            success: function(data) {
                $("#cont-pag").html(data);
            }
            /*success: function(msg) {
                alert(msg);
            }*/
        });
</code>```

I get a big chunk of code (I checked with the alert msg) inside a . I already have a big div cont-pag in my original page, I just want the one from the ajax call to replace the previous one. Am I doing this wrong?

Edit: the structure that's supposed to show up goes like this:
I have my query over here and stuff and then...

```<code>echo'<div id="cont_pag">
<ul id="content_pag">';
    while($row = mysql_fetch_object($res)){
                echo'<li>...</li>';
            }
echo'</ul>'; //here is when my msg will stop painting code, but there's more:
if (mysql_num_rows($res)>8)
echo '<div id="page_navigation"></div><div class="siguiente-pag"><p>'.$cajon_siguiente.'</p></div>
 </div>'; ?>
</code>```

Ok so I answer that last thing myself. I missed my markup as always:

```<code> echo '<div id="page_navigation"></div><div class="siguiente-pag"><p>'.$cajon_siguiente.'</p></div>';
 echo'</div>'; ?>
</code>```

And now the alert shows it properly but the .html doesn't replace the original div. May I have a conflicting script somewhere? (it's a complex project and a lot of people work on it and has a few jquery tweaks here and there). Can I do the div replacement differently?

答:
Try adding:

```<code>dataType: 'html',
</code>```

To specify what sort of data is being returned. Also consider using Firebug and it's console.log function to check for errors and what is being returned.

Body:
After doing so:

        $.ajax({
            type: "POST",
            url: $("#form").attr("action"),
            data: "value=" + value + "&sel=" + sel,
            success: function(data) {
                $("#cont-pag").html(data);
            }
            /*success: function(msg) {
                alert(msg);
            }*/
        });

I get a big chunk of code (I checked with the alert msg) inside a . I already have a big div cont-pag in my original page, I just want the one from the ajax call to replace the previous one. Am I doing this wrong?

Edit: the structure that's supposed to show up goes like this:
I have my query over here and stuff and then...

echo'

';
    while($row = mysql_fetch_object($res)){
                echo'
...
';
            }
echo'
'; //here is when my msg will stop painting code, but there's more:
if (mysql_num_rows($res)>8)
echo '

'.$cajon_siguiente.'

'; ?>

Ok so I answer that last thing myself. I missed my markup as always:

 echo '

'.$cajon_siguiente.'

';
 echo'
'; ?>

And now the alert shows it properly but the .html doesn't replace the original div. May I have a conflicting script somewhere? (it's a complex project and a lot of people work on it and has a few jquery tweaks here and there). Can I do the div replacement differently?

Body:
Try adding:

dataType: 'html',

To specify what sort of data is being returned. Also consider using Firebug and it's console.log function to check for errors and what is being returned.


答:
Use loop instead of using it directly using index values. </p>

```<code>let data =[
    {
        "id": 2,
        "addEmployee": {
            "firstName": "Devansh"
        },
        "attendances": [
            {
                "id": 3,
                "checkIn": "2020-02-18T04:36:45.000Z",
                "checkOut": "2020-02-18T11:46:16.000Z",
                "totalHours": "7:9",
                "date": "2020-02-18",
                "status": "present",
                "createdAt": "2020-02-18T04:36:45.000Z",
                "updatedAt": "2020-02-18T11:46:16.000Z",
                "userId": 2
            }
        ]
    },
    ];

data.forEach(eachData => {
 console.log(eachData.addEmployee.firstName);
  eachData.attendances.forEach(atten => {console.log(atten);})
});
</code>```

Title: How to access nested array and objects in http response In angular

Body:
Use loop instead of using it directly using index values.

let data =[
    {
        "id": 2,
        "addEmployee": {
            "firstName": "Devansh"
        },
        "attendances": [
            {
                "id": 3,
                "checkIn": "2020-02-18T04:36:45.000Z",
                "checkOut": "2020-02-18T11:46:16.000Z",
                "totalHours": "7:9",
                "date": "2020-02-18",
                "status": "present",
                "createdAt": "2020-02-18T04:36:45.000Z",
                "updatedAt": "2020-02-18T11:46:16.000Z",
                "userId": 2
            }
        ]
    },
    ];

data.forEach(eachData => {
 console.log(eachData.addEmployee.firstName);
  eachData.attendances.forEach(atten => {console.log(atten);})
});


问:
Django : HTML form action directing to view (or url?) with 2 arguments
Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment...

models.py

```<code>class data(models.Model):
    course = models.CharField(max_length = 250)

    def __str__(self):
        return self.course
</code>```

html

Converted the objects in models.course to schlist

```<code><link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" />
<form action={% views.process %}  method="GET">
      <div>
        <h4 style="font-family:verdana;">First Course: </h4>
        <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
          <option value=""></option>
          {% for item in schlist %}
          <option> {{ item }} </option>
          {% endfor %}
        </select>
      </div>
      </br>
      <div>
        <h4 style="font-family:verdana;">Second Course:</h4>
        <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
          <option value=""></option>
          {% for item in schlist %}
          <option> {{ item }} </option>
          {% endfor %}
        </select>
      </div>
      </br>
  <input type="submit" value="Compare!" />
</form>
</code>```

urls.py (having my doubts if this works..)

```<code>urlpatterns = [
    url(r'^(\d+)/(\d+)$',views.process, name = 'process'),
]
</code>```

view.py

```<code>def process(request,q1 ,q2):
    obj1= get_object_or_404(Schdata, course = q1)
    obj2= get_object_or_404(Schdata, course = q2)
 ........
</code>```

Was wondering if it is possible for the form action to direct the action to

(1) view.py or (2) url.py (and eventually to a view.py) with 2 arguments selected?

If so how should the form action  be? {{view ?}} or {{url ?}}. Am I missing out the definition of my arguments in my HTML?

Directing to views.py:

User input is CharField, could use get_object_or_404 to get the model pk. However when defining my urls.py I would get a Noreverse error as my url arguments is the primary key.

Directing to urls.py:

Url arguments is primary key. From the way I see it, I need to magically convert my User input Charfield to a pk before passing it to urls.py

Is there a (or) function for get() in django? E.g get_object_or_404(pk = q1 or course = q1)?

Would really appreciate any advice. Been staring at this for hours.

答:
Yes i'm late but it can help others for better understanding how Django processes the request.

Django 3.0 pattern

How Django processes the request

Basic :

First Django check the matching URL.

If URL is matched then calling the defined view to process the request. (Success)

If URL not matched/found the Django invokes error Page Not Found

In detail reading :

Official Django Documentations How Django processes a request

These are your URL patterns :

```<code>urlpatterns = [ path('profile/edit/<int:pk>/',views.editprofile, name='editprofile'),]
</code>```

Third argument in urlpatterns is for if you want to change the url pattern from current to this :

```<code>urlpatterns = [ url('profile/edit/user/id/<int:pk>',views.editprofile, name = 'editprofile'),]
</code>```

You don't need to redefine url pattern in all Templates where you using url name.

For Example :

This is my template profile.html where i used the url name instead of hard coded url.

```<code><a class="item" href="{% url 'editprofile' user.id %}" >Edit profile </a>
</code>```

Solution of your problem :

.html

Only use url name instead of hard coded url in your templates and pass arguments.

```<code><form action={% process no_of_arguments  %}  method="POST">
</code>```

views.py

Here you can process your request

```<code>def process(request,no_of_arguments):
</code>```

Become good django developer

You can also use Django ModelForms for your model.
Using model forms or simple form you can do multiple things

Modular approach

Write server side validation in related form instead of doing in views.py

Readable code - Clean code

Body:
Started learning django about a week ago and ran into a wall. Would really appreciate any enlightenment...

models.py

class data(models.Model):
    course = models.CharField(max_length = 250)

    def __str__(self):
        return self.course

html

Converted the objects in models.course to schlist

<link rel="stylesheet" type="text/css" href="{% static '/chosen/chosen.css' %}" />
<form action={% views.process %}  method="GET">

First Course:

        <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
          <option value=""></option>
          {% for item in schlist %}
          <option> {{ item }} </option>
          {% endfor %}
        </select>

Second Course:

        <select data-placeholder="Course" style="width:350px;" class="chosen-select" tabindex="7">
          <option value=""></option>
          {% for item in schlist %}
          <option> {{ item }} </option>
          {% endfor %}
        </select>

  <input type="submit" value="Compare!" />
</form>

urls.py (having my doubts if this works..)

urlpatterns = [
    url(r'^(\d+)/(\d+)$',views.process, name = 'process'),
]

view.py

def process(request,q1 ,q2):
    obj1= get_object_or_404(Schdata, course = q1)
    obj2= get_object_or_404(Schdata, course = q2)
 ........

Was wondering if it is possible for the form action to direct the action to

(1) view.py or (2) url.py (and eventually to a view.py) with 2 arguments selected?

If so how should the form action  be? {{view ?}} or {{url ?}}. Am I missing out the definition of my arguments in my HTML?

Directing to views.py:

User input is CharField, could use get_object_or_404 to get the model pk. However when defining my urls.py I would get a Noreverse error as my url arguments is the primary key.

Directing to urls.py:

Url arguments is primary key. From the way I see it, I need to magically convert my User input Charfield to a pk before passing it to urls.py

Is there a (or) function for get() in django? E.g get_object_or_404(pk = q1 or course = q1)?

Would really appreciate any advice. Been staring at this for hours.

Body:
Yes i'm late but it can help others for better understanding how Django processes the request.

Django 3.0 pattern

How Django processes the request

Basic :

First Django check the matching URL.

If URL is matched then calling the defined view to process the request. (Success)

If URL not matched/found the Django invokes error Page Not Found

In detail reading :

Official Django Documentations How Django processes a request

These are your URL patterns :

urlpatterns = [ path('profile/edit/<int:pk>/',views.editprofile, name='editprofile'),]

Third argument in urlpatterns is for if you want to change the url pattern from current to this :

urlpatterns = [ url('profile/edit/user/id/<int:pk>',views.editprofile, name = 'editprofile'),]

You don't need to redefine url pattern in all Templates where you using url name.

For Example :

This is my template profile.html where i used the url name instead of hard coded url.

<a class="item" href="{% url 'editprofile' user.id %}" >Edit profile </a>

Solution of your problem :

.html

Only use url name instead of hard coded url in your templates and pass arguments.

<form action={% process no_of_arguments  %}  method="POST">

views.py

Here you can process your request

def process(request,no_of_arguments):

Become good django developer

You can also use Django ModelForms for your model.
Using model forms or simple form you can do multiple things

Modular approach

Write server side validation in related form instead of doing in views.py

Readable code - Clean code


问:
Xamarin Animation from Left to Center of the device
I am trying to develop an android app using Xamarin. I need the animation like images to move from left of the screen to center of the screen in home page when the app is loading for the first time.

I have tried the existing animation techniques but not satisfied it since it was always allowing to move from the current position to the next position and again back.

But I need the animation like a move from left to the current position(in the center) or right to the current position of centre.

Can someone please help to resolve it.

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="TestMobileApp.MainPage">
    <Application.Resources>
        <Style TargetType="Picker" x:Key="pickerStyle" >
            <Setter Property="TitleColor" Value="White"/>
        </Style>
        <Style TargetType="Frame" x:Key="frameStyle" >
            <Setter Property="CornerRadius" Value="10"/>
            <Setter Property="Margin" Value="50,12,50,0"/>
            <Setter Property="BackgroundColor" Value="Gray"/>
            <Setter Property="HeightRequest" Value="40"/>
            <Setter Property="OutlineColor" Value="Black"/>
            <Setter Property="Padding" Value="0"/>
        </Style>
    </Application.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackLayout Grid.Row="0" Orientation="Horizontal" BackgroundColor="White" HeightRequest="50" WidthRequest="390">
            <!--<Image Source="Menu.PNG" VerticalOptions="Center" HeightRequest="30" />
            <Image HorizontalOptions="End" Source="Help.PNG" VerticalOptions="Center" HeightRequest="30" />-->
        </StackLayout>
        <Label Grid.Row="1" BackgroundColor="Red" HeightRequest="02" WidthRequest="415"></Label>
        <StackLayout Grid.Row="2"  Orientation="Vertical" BackgroundColor="White" HeightRequest="50" WidthRequest="390">
            <Label Margin="0,10,0,0"></Label>
            <AbsoluteLayout AbsoluteLayout.LayoutBounds="0,1,1,1">
                <Frame x:Name="processOrderFrame" Style="{StaticResource frameStyle}" AbsoluteLayout.LayoutBounds="0.0,0.5,0.2,0.2" AbsoluteLayout.LayoutFlags="All">
                    <Picker x:Name="ddlProcessOrder" Title="PROCESS ORDER" Style="{StaticResource pickerStyle}">
                        <Picker.Items>
                            <x:String>Order1</x:String>
                            <x:String>Order2</x:String>
                            <x:String>Order3</x:String>
                        </Picker.Items>
                    </Picker>
                </Frame>
            </AbsoluteLayout>
            <Frame x:Name="lookupsFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlLookups" Title="LOOKUPS" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Lookup1</x:String>
                        <x:String>Lookup2</x:String>
                        <x:String>Lookup3</x:String>
                        <x:String>Lookup4</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="qualityManagementFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlQualityManagement" Title="QUALITY STRUCTURE" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Quality1</x:String>
                        <x:String>Quality2</x:String>
                        <x:String>Quality3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="reportsFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlReports" Title="REPORTS" Style="{StaticResource pickerStyle}">
                    <Picker.Items>
                        <x:String>Report1</x:String>
                        <x:String>Report2</x:String>
                        <x:String>Report3</x:String>
                        <x:String>Report4</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="inventoryManagementFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlInventoryManagement" Title="INVENTORY" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Inventory1</x:String>
                        <x:String>Inventory2</x:String>
                        <x:String>Inventory3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="documentManagementFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlDocumentManagement" Title="DOCUMENTATION" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Documentation1</x:String>
                        <x:String>Documentation2</x:String>
                        <x:String>Documentation3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="administrationFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlAdministration" Title="ADMINISTRATION" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Administration1</x:String>
                        <x:String>Administration2</x:String>
                        <x:String>Administration4</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="siteAutomationFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlSiteAutomation" Title="SITE AUTOMATION" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Automation1</x:String>
                        <x:String>Automation2</x:String>
                        <x:String>Automation3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>
        </StackLayout>
    </Grid>
</ContentPage>
</code>```

--
CS Code -

```<code>public MainPage()
        {
            InitializeComponent();
            LoadAnimate();
        }
 private void LoadAnimate()
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                var xPosition = 0.5;
                var currentPosition = 0.0;
                while (currentPosition < xPosition)
                {
                    await Task.Delay(1);
                    currentPosition += 0.04;

                    AbsoluteLayout.SetLayoutBounds(processOrderFrame, new Rectangle(currentPosition, 0.5, 0.2, 0.2));
                }

            });
        }
</code>```

答:
There are many solutions which can implement it .

For example , you could use AbsoluteLayout and change the position of Frame

```<code><AbsoluteLayout BackgroundColor="White" AbsoluteLayout.LayoutBounds="0,1,1,1">
    <!--  -->
    <Frame x:Name="lookupsFrame" BackgroundColor="Olive" AbsoluteLayout.LayoutBounds="0.00,0.5,0.2,0.2" AbsoluteLayout.LayoutFlags="All">

          //...

    </Frame>

</AbsoluteLayout>

</code>```

```<code>private async void Button_Clicked(object sender, EventArgs e)
    {
        Device.BeginInvokeOnMainThread(async () =>
        {

            var xPosition = 0.5;
            var currentPosition = 0.0;
            while (currentPosition < xPosition)
            {
                await Task.Delay(1);
                currentPosition += 0.04;

                AbsoluteLayout.SetLayoutBounds(lookupsFrame, new Rectangle(currentPosition, 0.5, 0.2,0.2));
            }

        });
    }
</code>```

Body:
I am trying to develop an android app using Xamarin. I need the animation like images to move from left of the screen to center of the screen in home page when the app is loading for the first time.

I have tried the existing animation techniques but not satisfied it since it was always allowing to move from the current position to the next position and again back.

But I need the animation like a move from left to the current position(in the center) or right to the current position of centre.

Can someone please help to resolve it.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="TestMobileApp.MainPage">
    <Application.Resources>

    </Application.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackLayout Grid.Row="0" Orientation="Horizontal" BackgroundColor="White" HeightRequest="50" WidthRequest="390">

        </StackLayout>

        <StackLayout Grid.Row="2"  Orientation="Vertical" BackgroundColor="White" HeightRequest="50" WidthRequest="390">

            <AbsoluteLayout AbsoluteLayout.LayoutBounds="0,1,1,1">
                <Frame x:Name="processOrderFrame" Style="{StaticResource frameStyle}" AbsoluteLayout.LayoutBounds="0.0,0.5,0.2,0.2" AbsoluteLayout.LayoutFlags="All">
                    <Picker x:Name="ddlProcessOrder" Title="PROCESS ORDER" Style="{StaticResource pickerStyle}">
                        <Picker.Items>
                            <x:String>Order1</x:String>
                            <x:String>Order2</x:String>
                            <x:String>Order3</x:String>
                        </Picker.Items>
                    </Picker>
                </Frame>
            </AbsoluteLayout>
            <Frame x:Name="lookupsFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlLookups" Title="LOOKUPS" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Lookup1</x:String>
                        <x:String>Lookup2</x:String>
                        <x:String>Lookup3</x:String>
                        <x:String>Lookup4</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="qualityManagementFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlQualityManagement" Title="QUALITY STRUCTURE" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Quality1</x:String>
                        <x:String>Quality2</x:String>
                        <x:String>Quality3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="reportsFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlReports" Title="REPORTS" Style="{StaticResource pickerStyle}">
                    <Picker.Items>
                        <x:String>Report1</x:String>
                        <x:String>Report2</x:String>
                        <x:String>Report3</x:String>
                        <x:String>Report4</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="inventoryManagementFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlInventoryManagement" Title="INVENTORY" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Inventory1</x:String>
                        <x:String>Inventory2</x:String>
                        <x:String>Inventory3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="documentManagementFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlDocumentManagement" Title="DOCUMENTATION" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Documentation1</x:String>
                        <x:String>Documentation2</x:String>
                        <x:String>Documentation3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="administrationFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlAdministration" Title="ADMINISTRATION" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Administration1</x:String>
                        <x:String>Administration2</x:String>
                        <x:String>Administration4</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>

            <Frame x:Name="siteAutomationFrame" Style="{StaticResource frameStyle}">
                <Picker x:Name="ddlSiteAutomation" Title="SITE AUTOMATION" Style="{StaticResource pickerStyle}" >
                    <Picker.Items>
                        <x:String>Automation1</x:String>
                        <x:String>Automation2</x:String>
                        <x:String>Automation3</x:String>
                    </Picker.Items>
                </Picker>
            </Frame>
        </StackLayout>
    </Grid>
</ContentPage>

--
CS Code -

public MainPage()
        {
            InitializeComponent();
            LoadAnimate();
        }
 private void LoadAnimate()
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                var xPosition = 0.5;
                var currentPosition = 0.0;
                while (currentPosition < xPosition)
                {
                    await Task.Delay(1);
                    currentPosition += 0.04;

                    AbsoluteLayout.SetLayoutBounds(processOrderFrame, new Rectangle(currentPosition, 0.5, 0.2, 0.2));
                }

            });
        }

Body:
There are many solutions which can implement it .

For example , you could use AbsoluteLayout and change the position of Frame

<AbsoluteLayout BackgroundColor="White" AbsoluteLayout.LayoutBounds="0,1,1,1">
    <!--  -->
    <Frame x:Name="lookupsFrame" BackgroundColor="Olive" AbsoluteLayout.LayoutBounds="0.00,0.5,0.2,0.2" AbsoluteLayout.LayoutFlags="All">

          //...

    </Frame>

</AbsoluteLayout>

private async void Button_Clicked(object sender, EventArgs e)
    {
        Device.BeginInvokeOnMainThread(async () =>
        {

            var xPosition = 0.5;
            var currentPosition = 0.0;
            while (currentPosition < xPosition)
            {
                await Task.Delay(1);
                currentPosition += 0.04;

                AbsoluteLayout.SetLayoutBounds(lookupsFrame, new Rectangle(currentPosition, 0.5, 0.2,0.2));
            }

        });
    }


问:
how to redirect after successful login and block pages without login in reactjs?
I am using axios to get data and login but after login i need to redirect to dashboard component and prevent going back and block entering without login.
Currently using window.location.href method but i need in react method.

My login Function is:

```<code>getLoginDetails(){
    var input = document.getElementById("userInput").value;
    var pass = document.getElementById("userPassword").value;
      axios.post(' http:api here', {
      email:input,
      pin: pass
    })
    .then(function (response) {
      var status = response.data.status;
      if(status === 'success'){
        window.location.href="/dashboard";
      }else{
        alert("Invalid Userid or Password");
      }
    })
    .catch(function (error) {
      console.log(error);
    });

  }
</code>```

My button is :

```<code><Button
          className="login-button"
          color={"#36b0ff"}
          variant="primary"

          onClick={this.getLoginDetails}
        >
          Login
        </Button>
</code>```

Kindly help me out.Redirect Tag and props are shoeing error.

答:
One simple solution would be to check user status in both login and dashboard components (this might not be a good idea if you have a complicated authentication flow).

login component:

class Login extends Component{
    componentDidMount(){
        const isLoggedin = checkLogin();
        if(isLoggedin)
            this.props.history.push('/dashboard');
    }
}
export default withRouter(Login)
```

<p>and your dashboard:  </p>

```class Dash extends Component{
    componentDidMount(){
        const isLoggedin = checkLogin();
        if(!isLoggedin)
            this.props.history.push('/login');
    }
}
```

<p>considering that you store your token in local storage after user loges in:  </p>

<pre class="lang-js prettyprint-override"><code>checkLogin(){
    //you can retrieve your token and verify it in your own way.
    const token = window.localStorage.getItem('token')
    if(!token)
        return false
    return true
}
</code>```

Body:
I am using axios to get data and login but after login i need to redirect to dashboard component and prevent going back and block entering without login.
Currently using window.location.href method but i need in react method.

My login Function is:

getLoginDetails(){
    var input = document.getElementById("userInput").value;
    var pass = document.getElementById("userPassword").value;
      axios.post(' http:api here', {
      email:input,
      pin: pass
    })
    .then(function (response) {
      var status = response.data.status;
      if(status === 'success'){
        window.location.href="/dashboard";
      }else{
        alert("Invalid Userid or Password");
      }
    })
    .catch(function (error) {
      console.log(error);
    });

  }

My button is :

<Button
          className="login-button"
          color={"#36b0ff"}
          variant="primary"

          onClick={this.getLoginDetails}
        >
          Login
        </Button>

Kindly help me out.Redirect Tag and props are shoeing error.

Body:
One simple solution would be to check user status in both login and dashboard components (this might not be a good idea if you have a complicated authentication flow).

login component:

class Login extends Component{
    componentDidMount(){
        const isLoggedin = checkLogin();
        if(isLoggedin)
            this.props.history.push('/dashboard');
    }
}
export default withRouter(Login)

and your dashboard:

class Dash extends Component{
    componentDidMount(){
        const isLoggedin = checkLogin();
        if(!isLoggedin)
            this.props.history.push('/login');
    }
}

considering that you store your token in local storage after user loges in:

checkLogin(){
    //you can retrieve your token and verify it in your own way.
    const token = window.localStorage.getItem('token')
    if(!token)
        return false
    return true
}