问:
Escape Character Cannot Working in ReactJS Map Looping
I have file call ArrayCustomer.js contains ARRAY like this:

```<code>const ArrayCustomer = [
  {
    index:1,
    kondisi: 'Daftar Baru',
    badge: 'badge btn-warning',
  },
  {
    index:2,
    kondisi: 'Pelanggan dibawah 10m<sup>3</sup>',
    badge: 'badge btn-secondary',
  },
]

export default ArrayCustomer
</code>```

then I Import that Array to my Component call EditCustomer.js
and in form input I loop use map for showing kondisi like this:

```<code><FormGroup>
  <Label for="status">Status Pelanggan</Label>
  <Input
    required
    value={this.state.status}
    onChange={this.handleChange}
    type="select"
    name="status"
    id="status"
  >
    ArrayCustomer.map(item => (
    <option value={item.index}>{item.kondisi}</option>) ) }
  </Input>
</FormGroup>;

</code>```

but the Escape Character Does'nt showing as HTML/JSX Tag.
I Stack because of this, I hope you can help me. Thanks.

答:
You need to use dangerouslySetInnerHTML to render HTML strings in React elements.

decode the HTML string with this function.

```<code>const decodeString = str => {
  var element = document.createElement("div");
  element.innerHTML = str;
  return element.childNodes.length === 0
    ? ""
    : String(element.childNodes[0].nodeValue);
};
</code>```

Update map method, use the decodeString method while adding to element.

```<code>ArrayCustomer.map(item => (
  <option
    value={item.index}
    dangerouslySetInnerHTML={{ __html: decodeString(item.kondisi) }}
  ></option>
));
</code>```

Body:
I have file call ArrayCustomer.js contains ARRAY like this:

const ArrayCustomer = [
  {
    index:1,
    kondisi: 'Daftar Baru',
    badge: 'badge btn-warning',
  },
  {
    index:2,
    kondisi: 'Pelanggan dibawah 10m3',
    badge: 'badge btn-secondary',
  },
]

export default ArrayCustomer

then I Import that Array to my Component call EditCustomer.js
and in form input I loop use map for showing kondisi like this:

<FormGroup>
  Status Pelanggan
  <Input
    required
    value={this.state.status}
    onChange={this.handleChange}
    type="select"
    name="status"
    id="status"
  >
    ArrayCustomer.map(item => (
    <option value={item.index}>{item.kondisi}</option>) ) }
  </Input>
</FormGroup>;

but the Escape Character Does'nt showing as HTML/JSX Tag.
I Stack because of this, I hope you can help me. Thanks.

Body:
You need to use dangerouslySetInnerHTML to render HTML strings in React elements.

decode the HTML string with this function.

const decodeString = str => {
  var element = document.createElement("div");
  element.innerHTML = str;
  return element.childNodes.length === 0
    ? ""
    : String(element.childNodes[0].nodeValue);
};

Update map method, use the decodeString method while adding to element.

ArrayCustomer.map(item => (
  <option
    value={item.index}
    dangerouslySetInnerHTML={{ __html: decodeString(item.kondisi) }}
  ></option>
));


来源: stackexchange

问:
Issues with what appears to be never ending loops when calling functions in switch statement (even if function contains no loop)
I am trying to make a really simple text menu of sorts using switch statements for a class assignment. The issue is when calling the various functions I've made in the different cases of the switch statement, the never seem to end.

Considering the same issue seems to be happening to all the functions in my switch statement I think it might have something to do with the switch statement itself and not the individual functions although I honestly don't know at this point.

Disclaimer: I know I have tons of other issues with my code, but im just trying to pick a big one for simplicity. I would appreciate advice on other parts of my code aswell. (Also its not done yet as you can probably see by the unfinished cases)

Example output:

```<code>
==================
1. Admission's Office
2. Student
3. End Program
==================
Enter your choice: 1

Enter the password: 123

******************
1. Add a new student
2. Add new students from a file
3. Drop a student
4. View one students info
5. View all students info
******************
Enter your choice: 1

Enter the first name: First Name

Enter the last name: Last Name

Enter the gender: m

Enter the first name: It should only ask me once

Enter the last name: Why is this looping?

Enter the gender: ????

Enter the first name:
Enter the last name: ???????

Enter the gender: a

Enter the first name: ^C
</code>```

Code

//main.cpp
int main() {
  Student stuAr[SIZE];
  int choice, password, userInput;
  int numStu = 0;
  bool valid;

  do {
    userMenu();
    cin>>choice;
    cout<<endl;

    switch(choice){
    case 1:
      cout<<"Enter the password: ";
      cin>>password;
      cout<<endl;

      valid = checkPass(password);
      if (valid) {
        adminMenu();
        cin>>choice;
        cout<<endl;

        do {
          switch(choice) {
          case 1:
            addStu(stuAr, numStu);
            break;

          case 2:
            addStuFile(stuAr, numStu);
            break;

          case 3:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            dropStu(stuAr, numStu, userInput);
            break;

          case 4:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            viewStu(stuAr, numStu, userInput);
            break;

          case 5:
            viewAllStu(stuAr, numStu);
            break;
          }
        }while(choice != 6);
      }
      else {
        cout<<"The password is wrong."<<endl;
      }
      break;

    case 2:

      break;
    }
  }while(choice != 3);

  return 0;
```

<pre class="lang-cpp prettyprint-override"><code>//still main.cpp
//addStu function for case 1 of the nested switch statement
void addStu(Student stuAr[], int& numStu) {
  cin.ignore();
  cout<<"Enter the first name: ";
  stuAr[numStu].setFN();
  cout<<endl;

  //cin.ignore();
  cout<<"Enter the last name: ";
  stuAr[numStu].setLN();
  cout<<endl;

  cout<<"Enter the gender: ";
  stuAr[numStu].setGender();
  cout<<endl;

  numStu++;
  return;
}
</code>```

答: You never change choice in the inner do..while loop, and therefore the condition choice != 6 will always be true, unless you enter it in the first time.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to make a really simple text menu of sorts using switch statements for a class assignment. The issue is when calling the various functions I've made in the different cases of the switch statement, the never seem to end.

Considering the same issue seems to be happening to all the functions in my switch statement I think it might have something to do with the switch statement itself and not the individual functions although I honestly don't know at this point.

Disclaimer: I know I have tons of other issues with my code, but im just trying to pick a big one for simplicity. I would appreciate advice on other parts of my code aswell. (Also its not done yet as you can probably see by the unfinished cases)

Example output:

==================
1. Admission's Office
2. Student
3. End Program
==================
Enter your choice: 1

Enter the password: 123

******************
1. Add a new student
2. Add new students from a file
3. Drop a student
4. View one students info
5. View all students info
******************
Enter your choice: 1

Enter the first name: First Name

Enter the last name: Last Name

Enter the gender: m

Enter the first name: It should only ask me once

Enter the last name: Why is this looping?

Enter the gender: ????

Enter the first name:
Enter the last name: ???????

Enter the gender: a

Enter the first name: ^C

Code

//main.cpp
int main() {
  Student stuAr[SIZE];
  int choice, password, userInput;
  int numStu = 0;
  bool valid;

  do {
    userMenu();
    cin>>choice;
    cout<<endl;

    switch(choice){
    case 1:
      cout<<"Enter the password: ";
      cin>>password;
      cout<<endl;

      valid = checkPass(password);
      if (valid) {
        adminMenu();
        cin>>choice;
        cout<<endl;

        do {
          switch(choice) {
          case 1:
            addStu(stuAr, numStu);
            break;

          case 2:
            addStuFile(stuAr, numStu);
            break;

          case 3:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            dropStu(stuAr, numStu, userInput);
            break;

          case 4:
            cout<<"Enter the student ID: ";
            cin>>userInput;
            cout<<endl;
            viewStu(stuAr, numStu, userInput);
            break;

          case 5:
            viewAllStu(stuAr, numStu);
            break;
          }
        }while(choice != 6);
      }
      else {
        cout<<"The password is wrong."<<endl;
      }
      break;

    case 2:

      break;
    }
  }while(choice != 3);

  return 0;

//still main.cpp
//addStu function for case 1 of the nested switch statement
void addStu(Student stuAr[], int& numStu) {
  cin.ignore();
  cout<<"Enter the first name: ";
  stuAr[numStu].setFN();
  cout<<endl;

  //cin.ignore();
  cout<<"Enter the last name: ";
  stuAr[numStu].setLN();
  cout<<endl;

  cout<<"Enter the gender: ";
  stuAr[numStu].setGender();
  cout<<endl;

  numStu++;
  return;
}


问:
need a tool or editor to read SAS files for free
Need a free editor or tool to read/open .sas7bat or .wpd files.Trying to open/read a sas files.I don`t have SAS installed </p>

<p>tried using sublime and notepad++ </p>

答: You can use this free tool: www.clinbay.com/datasly which allows to open SAS datasets in .sas7bdat and XPT formats, and also export them to Excel format as well.</p>

Body:
Need a free editor or tool to read/open .sas7bat or .wpd files.Trying to open/read a sas files.I don`t have SAS installed

tried using sublime and notepad++


问:
Open Street Map for Android and iOS
I want to draw some polygons on maps(OSM) from the coordinates (please check the image below). I have checked out a few links and stackoverflow but not found the exact what I want. I need open-source SDK for both platforms (Android + iOS).

- skobbler (paid)

- mapbox.com (paid)

- https://help.openstreetmap.org/questions/8066/ios-android-sdk

- route-me (very old no maintain)

- routing-using-openstreetmap-data-in-ios

- open-street-maps-api-for-android (here android solution only)

When I draw OSM polygon in the our native map, it draws a different
  location on the map view.

Thanks for reading. Any help will be appreciated.:)

答:
My our Investigation:

When I draw OSM polygon in our native map, it draws a different location on the map view.

We've selected the Nasr City police station.

POINT (31.341296458117728 30.068688243368403) value has been saved in our DB. We used our native MKMapView for drawn polygon and it shows a different location compare to this. Same behavior in the android (Google map) too.

We investigate the same place on the google map shows a slightly different position for this value. Please check the image below.

 URL Generated by Google maps.

Now, I tried to reverse and used 30.068688243368403, 31.341296458117728 value on the same map it's working fine.

Output:

Title: Open Street Map for Android and iOS


问:
Installing Rails on Mac OS X 10.6 (SL)
I've just gone to installed RoR on my snow leopard mac.. and found the rails gem was already installed..

is this normal? Does it need updating?

Does this get installed along with textmate?

答:
I found an incredibly well written install guide at The Pragmatic Studio called Installing Ruby 1.9 and Rails 3 on Mac OS X.  It took about an hour to follow, including installing several prerequisites.

I'm hesitant to mess too much with OSX's native installation of ruby/rails, lest things get broken by an Apple system update, so I was very excited to learn about RVM (Ruby Version Manager) which is a cool tool for switching between different ruby/rails installations.  The Pragmatic Studio tutorial walks you through installing rvm.

There are a few glitches with the guide, which I'll list here:

Git: I just installed git itself.  You do not need to set up a github account.

Git: You may need to manually add /usr/local/git/bin to your PATH.  (They don't explicitly tell you to)

RVM: The protocol for the rvm-install-head URL should be https, not http

RVM: The installer complained a lot, but it worked anyway.

RVM: The newly installed ruby 1.9.2 didn't activate until I ran 'rvm 1.9.2' in step 8

All told, this seems like a GREAT approach, and I'm really impressed with their install guide!

ContentLicense: CC BY-SA 2.5

Title: Installing Rails on Mac OS X 10.6 (SL)

ContentLicense: CC BY-SA 3.0


问:
DotCMS page API does not return "layout" field
I want to use the Layout-as-a-Service (LaaS) feature of DotCMS. This approach is documented in
 https://dotcms.com/blog/post/more-than-a-headless-cms-layout-as-a-service-in-dotcms and also
in https://github.com/fmontes/dotcms-page.

Both articles suggest, that the DotCMS page API should return a field called "layout" in the response, e.g. to http://localhost:8080/api/v1/page/json/test-page

test-page is a page, which is using a standard template. By standard template, I mean template created with "Template Designer", with a 20% sidebar on the left, one 100% width column, both containing "Blank container".

No matter what I try, the "layout" field is never part of the response. All I get is this:

```<code>{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "numberContents": 2,
    "page": ...,
    "site": ...,
    "template": ...,
    "viewAs": ...  },
  "messages": [],
  "i18nMessagesMap": {},
  "permissions": []
}
</code>```

I tried DotCMS version 5.2.0 and also 5.2.3.
Is this perhaps a feature of the Enterprise edition only?

Edit: What I expect:

```<code>{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "layout": {
      "width": "responsive",
      "title": "mytemplate1",
      "header": true,
      "footer": true,
      "body": {
        "rows": [
          {
            "columns": [
              {
                "containers": [
                  {
                    "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
                    "uuid": "1582123997023"
                  }
                ],
                "widthPercent": 100,
                "leftOffset": 1,
                "styleClass": null,
                "preview": false,
                "width": 12,
                "left": 0
              }
            ],
            "styleClass": null
          }
        ]
      },
      "sidebar": {
        "containers": [
          {
            "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
            "uuid": "1582123991866"
          }
        ],
        "location": "left",
        "width": "small",
        "widthPercent": 20,
        "preview": false
      }
    }
    ...
</code>```

答:
Nevermind, I found the answer myself.

I checked the source code. In com.dotmarketing.portlets.htmlpageasset.business.render.page.HTMLPageAssetRenderedBuilder#build there is following piece of code:

```<code>        final TemplateLayout layout = template != null && template.isDrawed() && !LicenseManager.getInstance().isCommunity()
                ? DotTemplateTool.themeLayout(template.getInode()) : null;
</code>```

So the answer is, that you can use LaaS promoted by DotCMS only if you have a non-community licence.

Body:
I want to use the Layout-as-a-Service (LaaS) feature of DotCMS. This approach is documented in
 https://dotcms.com/blog/post/more-than-a-headless-cms-layout-as-a-service-in-dotcms and also
in https://github.com/fmontes/dotcms-page.

Both articles suggest, that the DotCMS page API should return a field called "layout" in the response, e.g. to http://localhost:8080/api/v1/page/json/test-page

test-page is a page, which is using a standard template. By standard template, I mean template created with "Template Designer", with a 20% sidebar on the left, one 100% width column, both containing "Blank container".

No matter what I try, the "layout" field is never part of the response. All I get is this:

{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "numberContents": 2,
    "page": ...,
    "site": ...,
    "template": ...,
    "viewAs": ...  },
  "messages": [],
  "i18nMessagesMap": {},
  "permissions": []
}

I tried DotCMS version 5.2.0 and also 5.2.3.
Is this perhaps a feature of the Enterprise edition only?

Edit: What I expect:

{
  "errors": [],
  "entity": {
    "canCreateTemplate": true,
    "containers": ...,
    "layout": {
      "width": "responsive",
      "title": "mytemplate1",
      "header": true,
      "footer": true,
      "body": {
        "rows": [
          {
            "columns": [
              {
                "containers": [
                  {
                    "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
                    "uuid": "1582123997023"
                  }
                ],
                "widthPercent": 100,
                "leftOffset": 1,
                "styleClass": null,
                "preview": false,
                "width": 12,
                "left": 0
              }
            ],
            "styleClass": null
          }
        ]
      },
      "sidebar": {
        "containers": [
          {
            "identifier": "b5ea1513-7653-4602-a729-97cd8dd099b6",
            "uuid": "1582123991866"
          }
        ],
        "location": "left",
        "width": "small",
        "widthPercent": 20,
        "preview": false
      }
    }
    ...

Body:
Nevermind, I found the answer myself.

I checked the source code. In com.dotmarketing.portlets.htmlpageasset.business.render.page.HTMLPageAssetRenderedBuilder#build there is following piece of code:

        final TemplateLayout layout = template != null && template.isDrawed() && !LicenseManager.getInstance().isCommunity()
                ? DotTemplateTool.themeLayout(template.getInode()) : null;

So the answer is, that you can use LaaS promoted by DotCMS only if you have a non-community licence.


问:
how to mock namedJdbcTemplate to get two different result which are being used two times in one function
in my class namedJdbcTemplate is being used twice in single function to get different result. but mocking it only gives one result. how to prepare test case for it ?

my class:

```<code>public void Getsomething(){

Result1 = namedJdbcTemplate.queryForObject(
            "SomeSQLString1", params, String.class);

Result2 = namedJdbcTemplate.queryForObject(
    "SomeSQLString2", params, String.class);
</code>```

Test Class:

```<code>@Test
public void getNewRecordsTest2(){

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
            Mockito.any(String.class))).thenReturn(Result1);

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result2);

    /**calling actual*/
    SomeClass.Getsomething();

}
</code>```

i tried to call it twice but it will hold only one result.

mockito.doreturn fails to give any result and calls real method inside function, provide null result

```<code>    @Test
public void getNewRecordsTest2(){

Mockito.doReturn(Result1).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

Mockito.doReturn(Result2).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

    /**calling actual*/
    SomeClass.Getsomething();

}
</code>```

答: Here is a nice tutorial about this</p>

Body:
in my class namedJdbcTemplate is being used twice in single function to get different result. but mocking it only gives one result. how to prepare test case for it ?

my class:

public void Getsomething(){

Result1 = namedJdbcTemplate.queryForObject(
            "SomeSQLString1", params, String.class);

Result2 = namedJdbcTemplate.queryForObject(
    "SomeSQLString2", params, String.class);

Test Class:

@Test
public void getNewRecordsTest2(){

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
            Mockito.any(String.class))).thenReturn(Result1);

Mockito.when(namedJdbcTemplate.queryForObject(Mockito.anyString(), Mockito.any(MapSqlParameterSource.class),
        Mockito.any(String.class))).thenReturn(Result2);

    /**calling actual*/
    SomeClass.Getsomething();

}

i tried to call it twice but it will hold only one result.

mockito.doreturn fails to give any result and calls real method inside function, provide null result

    @Test
public void getNewRecordsTest2(){

Mockito.doReturn(Result1).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

Mockito.doReturn(Result2).when(namedJdbcTemplate).queryForObject("SomeSQLString1", params, String.class);

    /**calling actual*/
    SomeClass.Getsomething();

}

Body: Here is a nice tutorial about this


问:
How to delete a whole substring on backspace key press in angular 8/ javascript?
I have a requirement in which I want to delete the whole substring when I press back space.

Issue 1 -

Eg. If I have following text in my input -
@User A is saying hi to @User B

Now if I do a backspace, the whole @User A or @User B should be deleted on backspace key press.

Issue 2 -

I have a list of users (Eg. @User A, @User B, @User C... etc) which are substrings that should be deleted on single back space press.
So how to determine that on backspace press it is a substring which is present in my list of users.

Please suggest how can I do this in javascript / angular approach

答:
Check this out - https://stackblitz.com/edit/angular-kx3uds

Following is the algorithm:

Add KeyDown event handler. Check if keycode is Backspace

Find the position of @ from cursor in backward direction

Once found, find the substring between position at step #2 and cursor

Check if this string is present in a predefined array of users

If yes, then preventDefault operation and update the model to remove the found username.

Please use above code just as a reference. There may be some edge cases, bugs in this code. Please test it thoroughly before using in production.


问:
Replace all without a regex where can I use the G
So I have the following:

```<code>var token = '[token]';
var tokenValue = 'elephant';
var string = 'i have a beautiful [token] and i sold my [token]';
string = string.replace(token, tokenValue);
</code>```

The above will only replace the first [token] and leave the second on alone.

If I were to use regex I could use it like

```<code>string = string.replace(/[token]/g, tokenValue);
</code>```

And this would replace all my [tokens]

However I don't know how to do this without the use of //

答:
Unfortunately since Javascript's string replace() function doesn't let you start from a particular index, and there is no way to do in-place modifications to strings it is really hard to do this as efficiently as you could in saner languages.

.split().join() isn't a good solution because it involves the creation of a load of strings (although I suspect V8 does some dark magic to optimise this).

Calling replace() in a loop is a terrible solution because replace starts its search from the beginning of the string every time. This is going to lead to O(N^2) behaviour! It also has issues with infinite loops as noted in the answers here.

A regex is probably the best solution if your replacement string is a compile time constant, but if it isn't then you can't really use it. You should absolutely not try and convert an arbitrary string into a regex by escaping things.

One reasonable approach is to build up a new string with the appropriate replacements:

```<code>function replaceAll(input: string, from: string, to: string): string {
  const fromLen = from.length;
  let output = "";
  let pos = 0;
  for (;;) {
    let matchPos = input.indexOf(from, pos);
    if (matchPos === -1) {
      output += input.slice(pos);
      break;
    }
    output += input.slice(pos, matchPos);
    output += to;
    pos = matchPos + fromLen;
  }
  return output;
}
</code>```

I benchmarked this against all the other solutions (except calling replace() in a loop which is going to be terrible) and it came out slightly faster than a regex, and about twice as fast as split/join.

Edit: This is almost the same method as Stefan Steiger's answer which I totally missed for some reason. However his answer still uses .join() for some reason which makes it 4 times slower than mine.

Body:
So I have the following:

var token = '[token]';
var tokenValue = 'elephant';
var string = 'i have a beautiful [token] and i sold my [token]';
string = string.replace(token, tokenValue);

The above will only replace the first [token] and leave the second on alone.

If I were to use regex I could use it like

string = string.replace(/[token]/g, tokenValue);

And this would replace all my [tokens]

However I don't know how to do this without the use of //

Body:
Unfortunately since Javascript's string replace() function doesn't let you start from a particular index, and there is no way to do in-place modifications to strings it is really hard to do this as efficiently as you could in saner languages.

.split().join() isn't a good solution because it involves the creation of a load of strings (although I suspect V8 does some dark magic to optimise this).

Calling replace() in a loop is a terrible solution because replace starts its search from the beginning of the string every time. This is going to lead to O(N^2) behaviour! It also has issues with infinite loops as noted in the answers here.

A regex is probably the best solution if your replacement string is a compile time constant, but if it isn't then you can't really use it. You should absolutely not try and convert an arbitrary string into a regex by escaping things.

One reasonable approach is to build up a new string with the appropriate replacements:

function replaceAll(input: string, from: string, to: string): string {
  const fromLen = from.length;
  let output = "";
  let pos = 0;
  for (;;) {
    let matchPos = input.indexOf(from, pos);
    if (matchPos === -1) {
      output += input.slice(pos);
      break;
    }
    output += input.slice(pos, matchPos);
    output += to;
    pos = matchPos + fromLen;
  }
  return output;
}

I benchmarked this against all the other solutions (except calling replace() in a loop which is going to be terrible) and it came out slightly faster than a regex, and about twice as fast as split/join.

Edit: This is almost the same method as Stefan Steiger's answer which I totally missed for some reason. However his answer still uses .join() for some reason which makes it 4 times slower than mine.


问:
Draggable UIView does not move smoothly and is only draggable for a little distance (Video included)
The video: https://www.youtube.com/watch?v=8_xCTJAld9Y&feature=youtu.be
. Here you can see my issue, and I do not know what exactly is wrong. I cant move it like I want.

I have a draggable UIView, which has a custom class:

```<code>import UIKit

class UIViewDraggable: UIView {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.isUserInteractionEnabled = true
}

override init(frame: CGRect) {
    super.init(frame: frame)

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first;
    let location = touch?.location(in: self.superview);
    if(location != nil)
    {
    self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    }
}
</code>```

I create the UIView with a button tap:

```<code>@IBAction func buttonAddSubviewTextTapped(_ sender: UIButton) {

    let label = UIView()
    label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
    label.center = CGPoint(x: 160, y: 285)
    label.backgroundColor = .red
    self.viewImagePreview.addSubview(label)
    self.viewImagePreview.bringSubviewToFront(label)

}
</code>```

How can I implement a fully smoothly draggable UIView?

Final Solution to make button created view draggable within its parentview:

```<code>@IBAction func buttonAddSubviewTextTapped(_ sender: UIButton) {

    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedView(_:)))

    let label = UIView()
    label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
    label.center = CGPoint(x: 160, y: 285)
    label.backgroundColor = .red
    label.isUserInteractionEnabled = true
    label.addGestureRecognizer(panGesture)
    self.viewImagePreview.addSubview(label)
    self.viewImagePreview.bringSubviewToFront(label)

}

// Function to drag a view
@objc func draggedView(_ sender: UIPanGestureRecognizer) {

    guard let createdView = sender.view else {return}
    createdView.bringSubviewToFront(viewImagePreview)

    if sender.state == .began || sender.state == .changed {

        let point = sender.location(in: self.viewImagePreview)
        if let parentView = self.viewImagePreview {

            let superBounds = CGRect(x: parentView.bounds.origin.x, y: parentView.bounds.origin.y, width: parentView.bounds.size.width - 2, height: parentView.bounds.size.height - 2)

            if (superBounds.contains(point)) {
                let translation = sender.translation(in: parentView)
                createdView.center = CGPoint(x: createdView.center.x + translation.x, y: createdView.center.y + translation.y)
                sender.setTranslation(CGPoint.zero, in: parentView)

            }
        }
    }
}
</code>```

答:
Add a panGesture to your View and then based on the touch location, updated your view.center

```<code>let pan = UIPanGestureRecognizer(target: self, action: #selector(panView))
self.addGestureRecognizer(pan)
</code>```

then use it as:

```<code>@objc func panView(pan: UIPanGestureRecognizer) {

    let location = pan.location(in: self.superView) // get pan location

    switch pan.state {
    case .began:
        print("began")
    case .changed:
        self.center = location
        // updated your frames here
    default:
        print("nothing")
    }
 }
</code>```

Also for your case,

try replacing

```<code>self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
</code>```

to

```<code>self.center = location
</code>```

Body:
The video: https://www.youtube.com/watch?v=8_xCTJAld9Y&feature=youtu.be
. Here you can see my issue, and I do not know what exactly is wrong. I cant move it like I want.

I have a draggable UIView, which has a custom class:

import UIKit

class UIViewDraggable: UIView {

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    self.isUserInteractionEnabled = true
}

override init(frame: CGRect) {
    super.init(frame: frame)

}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch = touches.first;
    let location = touch?.location(in: self.superview);
    if(location != nil)
    {
    self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    }
}

I create the UIView with a button tap:

@IBAction func buttonAddSubviewTextTapped(_ sender: UIButton) {

    let label = UIView()
    label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
    label.center = CGPoint(x: 160, y: 285)
    label.backgroundColor = .red
    self.viewImagePreview.addSubview(label)
    self.viewImagePreview.bringSubviewToFront(label)

}

How can I implement a fully smoothly draggable UIView?

Final Solution to make button created view draggable within its parentview:

@IBAction func buttonAddSubviewTextTapped(_ sender: UIButton) {

    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(draggedView(_:)))

    let label = UIView()
    label.frame = CGRect(x: 0, y: 0, width: 200, height: 21)
    label.center = CGPoint(x: 160, y: 285)
    label.backgroundColor = .red
    label.isUserInteractionEnabled = true
    label.addGestureRecognizer(panGesture)
    self.viewImagePreview.addSubview(label)
    self.viewImagePreview.bringSubviewToFront(label)

}

// Function to drag a view
@objc func draggedView(_ sender: UIPanGestureRecognizer) {

    guard let createdView = sender.view else {return}
    createdView.bringSubviewToFront(viewImagePreview)

    if sender.state == .began || sender.state == .changed {

        let point = sender.location(in: self.viewImagePreview)
        if let parentView = self.viewImagePreview {

            let superBounds = CGRect(x: parentView.bounds.origin.x, y: parentView.bounds.origin.y, width: parentView.bounds.size.width - 2, height: parentView.bounds.size.height - 2)

            if (superBounds.contains(point)) {
                let translation = sender.translation(in: parentView)
                createdView.center = CGPoint(x: createdView.center.x + translation.x, y: createdView.center.y + translation.y)
                sender.setTranslation(CGPoint.zero, in: parentView)

            }
        }
    }
}

Body:
Add a panGesture to your View and then based on the touch location, updated your view.center

let pan = UIPanGestureRecognizer(target: self, action: #selector(panView))
self.addGestureRecognizer(pan)

then use it as:

@objc func panView(pan: UIPanGestureRecognizer) {

    let location = pan.location(in: self.superView) // get pan location

    switch pan.state {
    case .began:
        print("began")
    case .changed:
        self.center = location
        // updated your frames here
    default:
        print("nothing")
    }
 }

Also for your case,

try replacing

self.frame.origin = CGPoint(x: location!.x-self.frame.size.width/2, y: location!.y-self.frame.size.height/2);

to

self.center = location


问:
How to delete the image from the storage in laravel?
I am currently trying to delete an image when a user updates his/her post before publishing.

Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.

Here is my controller

```<code>public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}
</code>```

I used:

File::delete(public_path('storage/image'.$isExist['image']));

but it didn't do the job

my delete function

```<code>       public function deletePost($id){
        $post = Post::where('id',$id)->first();
//        dd($post);
        if(!$post){
            return response()->json([
                'status' => '500',
                'error' => 'post not found'
            ]);
        }
        Storage::disk('public')->delete('/storage/image'. $post['image']);
        Post::where('id', $id)->delete();
        return response()->json([
            'status'=> '200',
            'response'=> 'Post successfully deleted'
        ]);
    }
</code>```

my storage path snapshot

答:
If you look at laravel file-system documentation you will see there are multiple Disk laravel support. you can used Storage Facades to delete a file from Storage like this

```<code>use Illuminate\Support\Facades\Storage;
Storage::disk('local')->delete('folder_path/file_name.jpg');
</code>```

path should be like this for public directory.

```<code> Storage::disk('local')->delete('public/image/'.$filename);
</code>```

Body:
I am currently trying to delete an image when a user updates his/her post before publishing.

Everything works fine, the image is changed in the database and post page, but I want to delete the previous image.

Here is my controller

public function updatePost(Request $request){
    $data = $request->all();
    $postid = $request['id'];
    $isExist = Post::where('id', $postid)->first();
    if($isExist){
        if ($request->hasFile('image')) {

            $file = $request->File('image');
            //Get filename with extension
            $fileNameToStoreWithExt = $file[0]->getClientOriginalName();
            //Get just filename
            $filename = pathinfo($fileNameToStoreWithExt, PATHINFO_FILENAME);
            //Get just ext
            $extension = $file[0]->getClientOriginalExtension();
            //File to store
            $fileNameToStore = $filename . '_' . time() . '.' . $extension;
            //Upload Image
            $path = $file[0]->storeAs('image', $fileNameToStore);
            $file[0]->move('storage/image', $fileNameToStore);
            File::delete(public_path('storage/image'.$isExist['image']));
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content'],
                'image' => $path
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }else{
            Post::where('id', $postid)->update([
                'title' => $data['title'],
                'category' => $data['category'],
                'content' => $data['content']
            ]);
            return response()->json([
                'status'=>'200',
                'response'=> 'successfully updated'
            ]);
        }
    }else{
        return response()->json([
            'error'=> 'post does not exist'
        ]);
    }
}

I used:

File::delete(public_path('storage/image'.$isExist['image']));

but it didn't do the job

my delete function

       public function deletePost($id){
        $post = Post::where('id',$id)->first();
//        dd($post);
        if(!$post){
            return response()->json([
                'status' => '500',
                'error' => 'post not found'
            ]);
        }
        Storage::disk('public')->delete('/storage/image'. $post['image']);
        Post::where('id', $id)->delete();
        return response()->json([
            'status'=> '200',
            'response'=> 'Post successfully deleted'
        ]);
    }

my storage path snapshot

Body:
If you look at laravel file-system documentation you will see there are multiple Disk laravel support. you can used Storage Facades to delete a file from Storage like this

use Illuminate\Support\Facades\Storage;
Storage::disk('local')->delete('folder_path/file_name.jpg');

path should be like this for public directory.

 Storage::disk('local')->delete('public/image/'.$filename);


问:
Python post request with Verification token
I've taken a look at many of the other responses on stackoverflow and have watched a few lengthy youtube videos and have yet to stumble on information that would render a solution to my problem. I've used post to login and scrape in other instances, just not when there's been a request token. Perhaps someone can take a look? I'll include the post parameters in a picture. It should be noted that the __RequestVerificationToken changes every time I login.

```<code>import requests

payload = {
'Email': 'dfo.msdi-idsm.mpo@dfo-mpo.gc.ca',
'Password': 'notrealpassword',
'__RequestVerificationToken': 'RuOal6rKBCWdjNy_15nTS9duFSkM586yGD3LxlWrlGzBB3Noaha9hAm3-tMq9HPvvMstDL8BZ8PvQLPutsreSeGwQOzK1MMwl76Q2c7n1zo1',
}

URL = 'http://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/Account/Login'
Pacific = 'https://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/FGP?SearchString=Pacific'

with requests.session() as c:
    c.post(URL, data=payload)
    r = c.get(Pacific)
    print r.content
</code>```

答:
That token looks like a CSRF token. You should add the cookie containing the __RequestVerificaionToken to the request and see if it works.

```<code>import requests

payload = {
'Email': 'dfo.msdi-idsm.mpo@dfo-mpo.gc.ca',
'Password': 'notrealpassword',
'__RequestVerificationToken': 'RuOal6rKBCWdjNy_15nTS9duFSkM586yGD3LxlWrlGzBB3Noaha9hAm3-tMq9HPvvMstDL8BZ8PvQLPutsreSeGwQOzK1MMwl76Q2c7n1zo1',
}

cookies = {
'__RequestVerificationToken': 'your token',
}

URL = 'http://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/Account/Login'
Pacific = 'https://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/FGP?SearchString=Pacific'

with requests.session() as c:
    c.post(URL, data=payload, cookies=cookies)
    r = c.get(Pacific)
    print r.content
</code>```

Body:
I've taken a look at many of the other responses on stackoverflow and have watched a few lengthy youtube videos and have yet to stumble on information that would render a solution to my problem. I've used post to login and scrape in other instances, just not when there's been a request token. Perhaps someone can take a look? I'll include the post parameters in a picture. It should be noted that the __RequestVerificationToken changes every time I login.

import requests

payload = {
'Email': 'dfo.msdi-idsm.mpo@dfo-mpo.gc.ca',
'Password': 'notrealpassword',
'__RequestVerificationToken': 'RuOal6rKBCWdjNy_15nTS9duFSkM586yGD3LxlWrlGzBB3Noaha9hAm3-tMq9HPvvMstDL8BZ8PvQLPutsreSeGwQOzK1MMwl76Q2c7n1zo1',
}

URL = 'http://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/Account/Login'
Pacific = 'https://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/FGP?SearchString=Pacific'

with requests.session() as c:
    c.post(URL, data=payload)
    r = c.get(Pacific)
    print r.content

Body:
That token looks like a CSRF token. You should add the cookie containing the __RequestVerificaionToken to the request and see if it works.

import requests

payload = {
'Email': 'dfo.msdi-idsm.mpo@dfo-mpo.gc.ca',
'Password': 'notrealpassword',
'__RequestVerificationToken': 'RuOal6rKBCWdjNy_15nTS9duFSkM586yGD3LxlWrlGzBB3Noaha9hAm3-tMq9HPvvMstDL8BZ8PvQLPutsreSeGwQOzK1MMwl76Q2c7n1zo1',
}

cookies = {
'__RequestVerificationToken': 'your token',
}

URL = 'http://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/Account/Login'
Pacific = 'https://gisd.dfo-mpo.gc.ca/DFO_WebServiceManager/FGP?SearchString=Pacific'

with requests.session() as c:
    c.post(URL, data=payload, cookies=cookies)
    r = c.get(Pacific)
    print r.content


问:
how to check 2D array for duplicates
I am trying to remove duplicates from my 2D array but no success.

Here is what I am doing any idea where am making mistake?

function Remove_duplicates_from_2d_array(data_array) {
  if (data_array.length > 0) {
    let unique_index_counter = 0;
    // loop on target array
    for (var a = 0; a < data_array.length; a++) {
      var unique_array = data_array[unique_index_counter];

      if (a === unique_index_counter) {
        continue;
      }
      console.log('comparing index: ' + a + ' ( ' + data_array[a] + ' ) -- index: ' + a + ' ( ' + data_array[a] + ' )');
      if (data_array[a].sort().join(',') === unique_array.sort().join(',')) {
        console.log('match it index ' + a + ' - ' + unique_index_counter);
        // same arrays
        data_array.splice(a, 1);
        a = 0; // reset for loop as splice will rebuilt array
      }
      // a will be equal to data_array length incase there is no match found
      if (a === data_array.length) {
        unique_index_counter++;
      }
   if(unique_index_counter != data_array.length) {
  a = 0; // reset for loop because we have not checked all items
   }
    }

    return data_array;
  } else {
    return [];
  }
}

var a1 = [1, 2, 3];
b1 = [4, 4, 5];
c1 = [3, 4, 5];
d1 = [4, 4, 5];
var data_array = [];
data_array.push(a1);
data_array.push(b1);
data_array.push(c1);
data_array.push(d1);
console.log('original array.');
console.log(data_array);

var r = Remove_duplicates_from_2d_array(data_array);
console.log('unique array.');
console.log(r);  // [[1,2,3],[4,4,5],[3,4,5]]```

答:
here is my fixed simple version of duplicate remover based on for loop </p>

```<code>function Remove_duplicates_from_2d_array(data_array) {
    var unique_array = [];
  if (data_array.length > 0) {
    let unique_index_counter = 0;
    // loop on target array
    for (var a = 0; a < data_array.length; a++) {
      // if have same indexs , skip
      if (a === unique_index_counter) {
         continue;
      }
        // compare both indexes
      if (data_array[unique_index_counter].join(',') == data_array[a].join(',') ) {
            data_array.splice(a, 1);  // remove that a index
            a = 0; // reset for loop as splice will rebuilt array
            continue;
      }
      // a will be equal to data_array length incase there is no match found
      else if ( (data_array.length != 0 && a == data_array.length - 1)  ) {
        unique_array.push(data_array[unique_index_counter]);  // push unique index to unique array
        data_array.splice(unique_index_counter, 1);  // remove that a index
        a = 0; // reset for loop as splice will rebuilt array
      }
    } // for end
     // by now one unique element will be still left in source arrays
     unique_array.push(data_array[0]);  // push unique index to unique array

    return unique_array;
  } else {
    return [];
  }
}

var a1 = [1, 2, 3];
b1 = [4, 4, 5];
c1 = [3, 4, 5];
d1 = [4, 4, 5];
var data_array = [];
data_array.push(a1);
data_array.push(b1);
data_array.push(c1);
data_array.push(d1);
console.log('original array.');
console.log(data_array);

var r = Remove_duplicates_from_2d_array(data_array);
console.log('unique array.');
console.log(r);  // [[1,2,3],[4,4,5],[3,4,5]]
</code>```

Title: how to check 2D array for duplicates

Body:
here is my fixed simple version of duplicate remover based on for loop

function Remove_duplicates_from_2d_array(data_array) {
    var unique_array = [];
  if (data_array.length > 0) {
    let unique_index_counter = 0;
    // loop on target array
    for (var a = 0; a < data_array.length; a++) {
      // if have same indexs , skip
      if (a === unique_index_counter) {
         continue;
      }
        // compare both indexes
      if (data_array[unique_index_counter].join(',') == data_array[a].join(',') ) {
            data_array.splice(a, 1);  // remove that a index
            a = 0; // reset for loop as splice will rebuilt array
            continue;
      }
      // a will be equal to data_array length incase there is no match found
      else if ( (data_array.length != 0 && a == data_array.length - 1)  ) {
        unique_array.push(data_array[unique_index_counter]);  // push unique index to unique array
        data_array.splice(unique_index_counter, 1);  // remove that a index
        a = 0; // reset for loop as splice will rebuilt array
      }
    } // for end
     // by now one unique element will be still left in source arrays
     unique_array.push(data_array[0]);  // push unique index to unique array

    return unique_array;
  } else {
    return [];
  }
}

var a1 = [1, 2, 3];
b1 = [4, 4, 5];
c1 = [3, 4, 5];
d1 = [4, 4, 5];
var data_array = [];
data_array.push(a1);
data_array.push(b1);
data_array.push(c1);
data_array.push(d1);
console.log('original array.');
console.log(data_array);

var r = Remove_duplicates_from_2d_array(data_array);
console.log('unique array.');
console.log(r);  // [[1,2,3],[4,4,5],[3,4,5]]


问:
Assign a unique 4 digit number to a list of ids using python
I have a list of ids that i want to give a 4 digit unique number for each of them .

For example :

```<code>driver id = ['5c73d1238472750067e86c6d','5a0d5513494c09001491c118']
unique id = ['1234' , '5897']
</code>```

Is there a package i can use for this?

答:
```<code>import random
import string

def get_id():
    return ''.join(random.choice(string.digits) for n in range(4))
driver_id = [1, 2, 3, 4]
unique_id=[]
while len(unique_id)!=len(driver_id):
    id = get_id()
    if id not in unique_id:
        unique_id.append(id)
print(unique_id)
</code>```

Output:

```<code>['7518', '7806', '4654', '0677']
</code>```

Body:
I have a list of ids that i want to give a 4 digit unique number for each of them .

For example :

driver id = ['5c73d1238472750067e86c6d','5a0d5513494c09001491c118']
unique id = ['1234' , '5897']

Is there a package i can use for this?

Body:
import random
import string

def get_id():
    return ''.join(random.choice(string.digits) for n in range(4))
driver_id = [1, 2, 3, 4]
unique_id=[]
while len(unique_id)!=len(driver_id):
    id = get_id()
    if id not in unique_id:
        unique_id.append(id)
print(unique_id)

Output:

['7518', '7806', '4654', '0677']


问:
How to replace item in array?
Each item of this array is some number:

```<code>var items = Array(523,3452,334,31, ...5346);
</code>```

How to replace some item with a new one?

For example, we want to replace 3452 with 1010, how would we do this?

答:
Well if anyone is interresting on how to replace an object from its index in an array, here's a solution.

Find the index of the object by its id:

```<code>const index = items.map(item => item.id).indexOf(objectId)
</code>```

Replace the object using Object.assign() method:

```<code>Object.assign(items[index], newValue)
</code>```

Title: How to replace item in array?

Body:
Each item of this array is some number:

var items = Array(523,3452,334,31, ...5346);

How to replace some item with a new one?

For example, we want to replace 3452 with 1010, how would we do this?

Body:
Well if anyone is interresting on how to replace an object from its index in an array, here's a solution.

Find the index of the object by its id:

const index = items.map(item => item.id).indexOf(objectId)

Replace the object using Object.assign() method:

Object.assign(items[index], newValue)


问:
Assign AWK result to variable
This should be pretty straightfoward and I don't know why I am struggling with it.

I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.

```<code>INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';")
</code>```

At this point, INDEXCOUNT is equal to “COUNT ------- 0”

Now if I echo the following line I get the result I want -

```<code>echo $INDEXCOUNT | awk '{print $3}'
</code>```

How do I assign the value of $INDEXCOUNT | awk ‘{print $3}’ to a variable to check it in an “IF” statement?

For example:

```<code>RETURNCOUNT=$INDEXCOUNT | awk '{print $3}'
</code>```

答:
The following works correctly on bash:

```<code> a=$(echo '111 222 33' | awk '{print $3;}' )
 echo $a # result is "33"
</code>```

Another option would be to convert the string to an array:

```<code> a="111 222 333"
 b=($a)

 echo ${b[2]}  # returns 333
</code>```

Title: Assign AWK result to variable

Body:
This should be pretty straightfoward and I don't know why I am struggling with it.

I am running the following psql command from within a shell script in order to find out whether all indexes have been dropped before inserting data.

INDEXCOUNT=$(psql -p $dbPort -U enterprisedb -d main_db -c "select Count(*) from all_indexes where index_schema = 'enterprisedb';")

At this point, INDEXCOUNT is equal to “COUNT ------- 0”

Now if I echo the following line I get the result I want -

echo $INDEXCOUNT | awk '{print $3}'

How do I assign the value of $INDEXCOUNT | awk ‘{print $3}’ to a variable to check it in an “IF” statement?

For example:

RETURNCOUNT=$INDEXCOUNT | awk '{print $3}'

Body:
The following works correctly on bash:

 a=$(echo '111 222 33' | awk '{print $3;}' )
 echo $a # result is "33"

Another option would be to convert the string to an array:

 a="111 222 333"
 b=($a)

 echo ${b[2]}  # returns 333


问:
Return parameter failing in Serverless Azure Function in Python
I have created a project using azure-python serverless framework template.
When I try to run locally: serverless offline, I get following error:

cannot load the goodbye function: the following parameters are declared in function.json but not in Python: {'res'}

If I modify manually function.json and replace name value "res" of parameter with $return, everything works. However, this file is regenerated by framework. How to define this parameter as $return in function.json?

答:
You can modify your configuration file. If you specify the configuration file, you can modify the name from "res" to "$return" in it. If you didn't specify the configuration file, the configuration file should be serverless.yml|.yaml|.js|.json. Please refer to the screenshots below:

Here provide two links(screenshot1, screenshot2) for the screenshots above(but I can't find serverless.yml for python sample, the second screenshot is for nodejs), you can also find more information about serverless in these two links.

Hope it helps~


问:
Elixir integer list to string causes (UnicodeConversionError) invalid code point

The problem

I need to create a string interpolating a list of integers in it.

```<code>"""
SomeQuery {
  someQuery(articleIds: #{inspect article_ids}) {
    edges {
      node {
        id
      }
    }
  }
}
"""
</code>```

Failing example

For example, the list [725553234] makes the example above to fail:

```<code>article_ids = [725553234]

"""
SomeQuery {
  someQuery(articleIds: #{article_ids}) {
    edges {
      node {
        id
      }
    }
  }
}
"""
</code>```

```<code>** (exit) an exception was raised:
    ** (UnicodeConversionError) invalid code point 725553234
        (elixir) lib/list.ex:839: List.to_string/1
        (commsapp_api) lib/my_project/client.ex:70: CommsappApi.News.Clients.CommunicationMs.Client.articles_feed/3
</code>```

System

Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:8:8] [ds:8:8:10]
  [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Elixir 1.6.3 (compiled with OTP 20)

Tried solutions

It tried the following:

Using inspect is not working: articleIds: #{inspect(article_ids)}

Using the IO.inspect with the :char_lists opt with :as_list: IO.inspect(article_ids, char_lists: :as_lists

Trying to join the integer list as string with: articleIds: [#{Enum.join(article_ids, ", ")}]

Interpolating the integers parsed to string with: Enum.map(article_ids, &Integer.to_string/1) |> Enum.join(", ")

I tried using a single line instead of a multiline string, not working

Many things I don't remember after trying different solutions... >.<

Guesses

The problem comes when using the brackets in the string, Elixir treats the interporlation as a list and raises the error because it cannot find the codepoints.

Ideas?

Thanks in advance!

答:
By using Enum.join return string and separate integer by ","

```<code>Enum.join(list, ",")
</code>```

or using Enum.map return as list by changing every integer value to string

```<code>Enum.map(list, &Integer.to_string/1)
</code>```

list = [1, 2, 3, 4]

```<code>Enum.join(list, ",") -> "1,2,3,4"

Enum.map(list, &Integer.to_string/1) -> ["1", "2", "3", "4"]
</code>```

Body:
The problem

I need to create a string interpolating a list of integers in it.

"""
SomeQuery {
  someQuery(articleIds: #{inspect article_ids}) {
    edges {
      node {
        id
      }
    }
  }
}
"""

Failing example

For example, the list [725553234] makes the example above to fail:

article_ids = [725553234]

"""
SomeQuery {
  someQuery(articleIds: #{article_ids}) {
    edges {
      node {
        id
      }
    }
  }
}
"""

** (exit) an exception was raised:
    ** (UnicodeConversionError) invalid code point 725553234
        (elixir) lib/list.ex:839: List.to_string/1
        (commsapp_api) lib/my_project/client.ex:70: CommsappApi.News.Clients.CommunicationMs.Client.articles_feed/3

System

Erlang/OTP 20 [erts-9.3] [source] [64-bit] [smp:8:8] [ds:8:8:10]
  [async-threads:10] [hipe] [kernel-poll:false] [dtrace]

Elixir 1.6.3 (compiled with OTP 20)

Tried solutions

It tried the following:

Using inspect is not working: articleIds: #{inspect(article_ids)}

Using the IO.inspect with the :char_lists opt with :as_list: IO.inspect(article_ids, char_lists: :as_lists

Trying to join the integer list as string with: articleIds: [#{Enum.join(article_ids, ", ")}]

Interpolating the integers parsed to string with: Enum.map(article_ids, &Integer.to_string/1) |> Enum.join(", ")

I tried using a single line instead of a multiline string, not working

Many things I don't remember after trying different solutions... >.<

Guesses

The problem comes when using the brackets in the string, Elixir treats the interporlation as a list and raises the error because it cannot find the codepoints.

Ideas?

Thanks in advance!

Body:
By using Enum.join return string and separate integer by ","

Enum.join(list, ",")

or using Enum.map return as list by changing every integer value to string

Enum.map(list, &Integer.to_string/1)

list = [1, 2, 3, 4]

Enum.join(list, ",") -> "1,2,3,4"

Enum.map(list, &Integer.to_string/1) -> ["1", "2", "3", "4"]


问:
Password policy requirement regex
I need a regex to meet this password policy requirement
Minimum eight (8) characters
At least one number (0-9)
Any three of the following:
Lowercase
Uppercase
Number
Special character (   ! " # $ % & ' ( )
* + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ )

for now i am using this regex Minimum eight (8) characters

```<code>/^(?=.*\d)[ !#$%&()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$/
</code>```

This regex is not working as expected it is taking input of
testtest1 as a right match.It should take this test@test1,Testtest12 as a right input

答:
You need to change your lookahead part a bit.

```<code>^(?=.{8,})(?=.*[0-9].*)(.*[\!"#$%&'\(\)\*+,\-.\/:;<=>?@\[\\\]^_`{|}~].*){3,}
</code>```

(?=.{8,})     = minimum eight characters length (positive lookahead)

(?=.*[0-9].*) = at leats one number (positive lookahead)

(.*[\!"#$%&'\(\)\*+,\-.\/:;<=>?@\[\\\]^_{|}~].*){3,}` any character in your list somewhere at least three times

Title: Password policy requirement regex

Body:
I need a regex to meet this password policy requirement
Minimum eight (8) characters
At least one number (0-9)
Any three of the following:
Lowercase
Uppercase
Number
Special character (   ! " # $ % & ' ( )
* + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~ )

for now i am using this regex Minimum eight (8) characters

/^(?=.*\d)[ !#$%&()*+,.\/:;<=>?@[\]^`{|}~\w-]{8,}$/

This regex is not working as expected it is taking input of
testtest1 as a right match.It should take this test@test1,Testtest12 as a right input

Body:
You need to change your lookahead part a bit.

^(?=.{8,})(?=.*[0-9].*)(.*[\!"#$%&'\(\)\*+,\-.\/:;<=>?@\[\\\]^_`{|}~].*){3,}

(?=.{8,})     = minimum eight characters length (positive lookahead)

(?=.*[0-9].*) = at leats one number (positive lookahead)

(.*[\!"#$%&'\(\)\*+,\-.\/:;<=>?@\[\\\]^_{|}~].*){3,}` any character in your list somewhere at least three times


问:
Is there way to use Distinct in LINQ query syntax?
Is there way to rewrite:

```<code>var tbl = ds.TABLES;
var q = from c in tbl
        select c.TABLE_TYPE;
string s = "";
foreach (var item in q.Distinct())
{
    s += "[" + item + "]";
}
MessageBox.Show(s);
</code>```

So that the Distinct() call is in the LINQ query?

答:
In the search for a Distinct-function for LINQ upon finding this question and realizing it doesn't exist, my workaround is by using GroupBy().
The obvious problem is that the distinct-set doesn't contain all the data (say you have three fields but only want to distinct on two fields missing out on the value for the last field, but, then again, DISTINCT in t-sql works the same way).

LINQ-code (hence the Dump):

```<code>void Main()
{
    var gt = new GenerateThings();
    var dlist = gt.list();
    dlist.Dump();

    dlist.GroupBy(x => new {x.id, x.cat}).Dump();
}

public class model
{
    public int id {get;set;}
    public int cat {get;set;}
    public int type {get;set;}
}

public class GenerateThings
{
    public List<model>list()
    {
        var dlist = new List<model>();
        dlist.Add(createNew(1, 1, 1));
        dlist.Add(createNew(1, 1, 1));
        dlist.Add(createNew(1, 2, 1));
        dlist.Add(createNew(1, 2, 1));
        dlist.Add(createNew(1, 1, 2));
        dlist.Add(createNew(1, 1, 2));
        dlist.Add(createNew(1, 1, 2));
        return dlist;
    }
    private model createNew(int id, int cat, int type){
        return new model{
            id = id,
            cat = cat,
            type = type
        };
    }
}
</code>```

LINQ-dump result

Body:
Is there way to rewrite:

var tbl = ds.TABLES;
var q = from c in tbl
        select c.TABLE_TYPE;
string s = "";
foreach (var item in q.Distinct())
{
    s += "[" + item + "]";
}
MessageBox.Show(s);

So that the Distinct() call is in the LINQ query?

Body:
In the search for a Distinct-function for LINQ upon finding this question and realizing it doesn't exist, my workaround is by using GroupBy().
The obvious problem is that the distinct-set doesn't contain all the data (say you have three fields but only want to distinct on two fields missing out on the value for the last field, but, then again, DISTINCT in t-sql works the same way).

LINQ-code (hence the Dump):

void Main()
{
    var gt = new GenerateThings();
    var dlist = gt.list();
    dlist.Dump();

    dlist.GroupBy(x => new {x.id, x.cat}).Dump();
}

public class model
{
    public int id {get;set;}
    public int cat {get;set;}
    public int type {get;set;}
}

public class GenerateThings
{
    public List<model>list()
    {
        var dlist = new List<model>();
        dlist.Add(createNew(1, 1, 1));
        dlist.Add(createNew(1, 1, 1));
        dlist.Add(createNew(1, 2, 1));
        dlist.Add(createNew(1, 2, 1));
        dlist.Add(createNew(1, 1, 2));
        dlist.Add(createNew(1, 1, 2));
        dlist.Add(createNew(1, 1, 2));
        return dlist;
    }
    private model createNew(int id, int cat, int type){
        return new model{
            id = id,
            cat = cat,
            type = type
        };
    }
}

LINQ-dump result


问:
trouble installing flask_cors and pillow on mac
I'm very new to python and just downloaded Anaconda and installed Pycharm. Now that all this is installed I'm stuck with Flask_cors and Pillow, which are needed for a project.
You can see the error in the screenshot below.

I've tried to install via pip command in terminal, and also specifying the target folder (like described in another post) or updating Flask and Pillow via Anaconda, nothing seems to work.

FYI I'm running Mac OS 10.12.6

Thanks for your help!

答:
Looks like you're using anaconda. So, I'd suggest you start from scratch, make a new environment and follow this route:

Deactive your old conda environment

```<code>conda deactivate
</code>```

Make a new conda environment

```<code>conda create -n myenv python=3.7
</code>```

Activate your new environment

```<code>conda activate myenv
</code>```

Install your dependencies. Since it's a conda environment, you should use conda commands to install the dependencies. See here why.

```<code>conda install -c anaconda flask
conda install -c conda-forge flask-cors
conda install -c anaconda pillow
</code>```

Now try again.

Body:
Looks like you're using anaconda. So, I'd suggest you start from scratch, make a new environment and follow this route:

Deactive your old conda environment

conda deactivate

Make a new conda environment

conda create -n myenv python=3.7

Activate your new environment

conda activate myenv

Install your dependencies. Since it's a conda environment, you should use conda commands to install the dependencies. See here why.

conda install -c anaconda flask
conda install -c conda-forge flask-cors
conda install -c anaconda pillow

Now try again.


问:
Disable mouse scroll middle click event with jQuery
I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.

Here is my code :

$('a').on('mousedown', function(e) {
  if (e.which === 2) {
    console.log('Disabled');
    return false;
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
 click here </code>```

答:
try the code below, thanks :</p>

```<code><a href="#dontwanttoopen"  id="link_click">click here </a>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js">
</script>

<script>
var el = document.getElementById('link_click');
el.onmousedown = mouse_down;

function mouse_down() {
alert('mouse_down() called');
return false;
}
</script>
</code>```

Body:
I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.

Here is my code :

$('a').on('mousedown', function(e) {
  if (e.which === 2) {
    console.log('Disabled');
    return false;
  }
});

 click here

Body:
try the code below, thanks :

<a href="#dontwanttoopen"  id="link_click">click here </a>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js">
</script>

<script>
var el = document.getElementById('link_click');
el.onmousedown = mouse_down;

function mouse_down() {
alert('mouse_down() called');
return false;
}
</script>


问:
I have a list of the following structure and need to return data from it
The list is like this-

```<code>[(a,{1:True,2:False}),(b,{1:False,2:True})........]
</code>```

Now I need to return the numbers which are true for one or more letter inputs.

Sample input-
a

Sample output-
1

Sample input-
a,b

Sample output-
1,2(since 1 is true for A and 2 is true for B I need to return both)

It is basically a list of tuples in which there are also dictionaries.

答:
I think you need to set up your initial data structure differently.
But let's roll with what you have.

An extended example list l could be:

```<code>>>> l = [('a', {1: True, 2: False}), ('b', {1: False, 2: True}),
        ('c', {1: False, 2: False, 3: False}),
        ('d', {1: True, 2: True, 3: False, 4: True})]
</code>```

Under the assumption that all your tuples are 2-tuples, that can be turned into a dict:

```<code>>>> d = dict(l)
>>> d
{'a': {1: True, 2: False}, 'c': {1: False, 2: False, 3: False},
 'b': {1: False, 2: True}, 'd': {1: True, 2: True, 3: False, 4: True}}
</code>```

Then, define the letters of interest:

```<code>letters = 'abcdef'
</code>```

Note that c has only False values, while e and f don't even exist. All three should thus result in an empty list.

Now, we can obtain the results in a nested list comprehension:

```<code>>>> [[key for key, value in d.get(letter, {}).items() if value] for letter in letters]
[[1], [2], [], [1, 2, 4], [], []]
</code>```

In case you just want a single list of the numbers, flatten this nested list:

```<code>>>> result = [[key for key, value in d.get(letter, {}).items() if value] for letter in letters]
>>> [item for sublist in result for item in sublist]
[1, 2, 1, 2, 4]
</code>```

And for unique numbers, make it a set:

```<code>>>> set([item for sublist in result for item in sublist])
set([1, 2, 4])
</code>```

Body:
The list is like this-

[(a,{1:True,2:False}),(b,{1:False,2:True})........]

Now I need to return the numbers which are true for one or more letter inputs.

Sample input-
a

Sample output-
1

Sample input-
a,b

Sample output-
1,2(since 1 is true for A and 2 is true for B I need to return both)

It is basically a list of tuples in which there are also dictionaries.

Body:
I think you need to set up your initial data structure differently.
But let's roll with what you have.

An extended example list l could be:

>>> l = [('a', {1: True, 2: False}), ('b', {1: False, 2: True}),
        ('c', {1: False, 2: False, 3: False}),
        ('d', {1: True, 2: True, 3: False, 4: True})]

Under the assumption that all your tuples are 2-tuples, that can be turned into a dict:

>>> d = dict(l)
>>> d
{'a': {1: True, 2: False}, 'c': {1: False, 2: False, 3: False},
 'b': {1: False, 2: True}, 'd': {1: True, 2: True, 3: False, 4: True}}

Then, define the letters of interest:

letters = 'abcdef'

Note that c has only False values, while e and f don't even exist. All three should thus result in an empty list.

Now, we can obtain the results in a nested list comprehension:

>>> [[key for key, value in d.get(letter, {}).items() if value] for letter in letters]
[[1], [2], [], [1, 2, 4], [], []]

In case you just want a single list of the numbers, flatten this nested list:

>>> result = [[key for key, value in d.get(letter, {}).items() if value] for letter in letters]
>>> [item for sublist in result for item in sublist]
[1, 2, 1, 2, 4]

And for unique numbers, make it a set:

>>> set([item for sublist in result for item in sublist])
set([1, 2, 4])


问:
Install vue/cli and vue/cli-service-global through package.json?
Each time I install/build my vue.js project from scratch (e.g. in a new/fresh git clone) I run:

```<code>npm install -g @vue/cli
npm install -g @vue/cli-service-global
npm install
</code>```

Is is possible to move:

```<code>@vue/cli
@vue/cli-service-global
</code>```

into my package.json file so they will get installed along side my other dependencies and I can just run:

```<code>npm install
</code>```

to prepare my project?

Or are both:

```<code>@vue/cli
@vue/cli-service-global
</code>```

"special" in the sense that they are not project specific dependencies but more like system wide tools like npm, node, git etc?

答:
In your package.json under scripts you need to add preinstall script which will execute preinstall scripts every time you do npm install ,
as follow:

```<code>  "scripts": {
    "preinstall": "npm i -g @vue/cli @vue/cli-service-global"
  }

</code>```

Body:
Each time I install/build my vue.js project from scratch (e.g. in a new/fresh git clone) I run:

npm install -g @vue/cli
npm install -g @vue/cli-service-global
npm install

Is is possible to move:

@vue/cli
@vue/cli-service-global

into my package.json file so they will get installed along side my other dependencies and I can just run:

npm install

to prepare my project?

Or are both:

@vue/cli
@vue/cli-service-global

"special" in the sense that they are not project specific dependencies but more like system wide tools like npm, node, git etc?

Body:
In your package.json under scripts you need to add preinstall script which will execute preinstall scripts every time you do npm install ,
as follow:

  "scripts": {
    "preinstall": "npm i -g @vue/cli @vue/cli-service-global"
  }


问:
Angular Material Drag and Drop multi row list
I have a list of items which I need do order. To do so, I'd like to drag and drop.

I'm using Angular Materials list solution, but my list waps to a new line (flex-wrap)
When I have multiple rows, it doesn't put the items in where they sholud be.

Heres an example; https://stackblitz.com/edit/angular-dnd-list-multirow

Does anyone know how to make this work?

Thanks.

答:
The problem if you use an unique cdkDropList is that when you drag all the items reorder. I suggest an aproximation that consist in make a cdkDropList for each item

```<code><div #contenedor class="categories" [style.width]="option" cdkDropListGroup>
    <ng-container *ngFor="let item of items;let i=index">
        <div class="categories-item" cdkDropList
    cdkDropListOrientation="horizontal"
    [cdkDropListData]="{item:item,index:i}" (cdkDropListDropped)="drop($event)" >
            <div class="inner"  cdkDrag>
        <div class="example-custom-placeholder" *cdkDragPlaceholder></div>
        {{item}}
        </div>
        </div>
    </ng-container>
</div>
</code>```

where

```<code>  drop(event: CdkDragDrop<any>) {
    this.items[event.previousContainer.data.index]=event.container.data.item
    this.items[event.container.data.index]=event.previousContainer.data.item
  }
</code>```

See that the "data" of the cdkDropList  is an object {item:item,index:i} and it's not the clasic drop event that interchange elements, just change the array items

stackblitz

Body:
The problem if you use an unique cdkDropList is that when you drag all the items reorder. I suggest an aproximation that consist in make a cdkDropList for each item

<div #contenedor class="categories" [style.width]="option" cdkDropListGroup>
    <ng-container *ngFor="let item of items;let i=index">
        <div class="categories-item" cdkDropList
    cdkDropListOrientation="horizontal"
    [cdkDropListData]="{item:item,index:i}" (cdkDropListDropped)="drop($event)" >
            <div class="inner"  cdkDrag>
        <div class="example-custom-placeholder" *cdkDragPlaceholder></div>
        {{item}}
        </div>
        </div>
    </ng-container>
</div>

where

  drop(event: CdkDragDrop<any>) {
    this.items[event.previousContainer.data.index]=event.container.data.item
    this.items[event.container.data.index]=event.previousContainer.data.item
  }

See that the "data" of the cdkDropList  is an object {item:item,index:i} and it's not the clasic drop event that interchange elements, just change the array items

stackblitz


问:
How to run dataiku as a docker container?
I am trying to run dataiku image as a docker container.
The docker image of dataiku is https://hub.docker.com/r/dataiku/dss
The setup runs fine, but when signing for the free edition of dataiku, I need to login through the username password.

I have tried running the dataiku image interactive mode, but does not help me in that case.

Can someone help me in how to run dataiku on docker?

答: admin/admin is the default username/password.</p>


问:
To create a battery symbol in bootstrap4
I want a battery level indicator such that :-
1. I should able to change the level of battery based on the percentage values I am getting.
2. And I should able to change the level of battery level based on the percentage value like if it is below 20% then it is should indicate red color and for other levels other colors.

I know we can create through Html but it not so attractive one.

答:
This might help and give you an idea.</p>

```<code><!DOCTYPE html>
<html>
<style>
#div1 {
  font-size:48px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>

<div id="div1" class="fa"></div>

<script>
function chargebattery() {
  var a;
  a = document.getElementById("div1");
  a.innerHTML = "";
  setTimeout(function () {
      a.innerHTML = "";
    }, 1000);
  setTimeout(function () {
      a.innerHTML = "";
    }, 2000);
  setTimeout(function () {
      a.innerHTML = "";
    }, 3000);
  setTimeout(function () {
      a.innerHTML = "";
    }, 4000);
}
chargebattery();
setInterval(chargebattery, 5000);
</script>

<p>This example demonstrates how to use an icon library to make an animated effect.</p>
</body>
</html>
</code>```

Body:
This might help and give you an idea.

<!DOCTYPE html>
<html>
<style>
#div1 {
  font-size:48px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<body>

<div id="div1" class="fa"></div>

<script>
function chargebattery() {
  var a;
  a = document.getElementById("div1");
  a.innerHTML = "&#xf244;";
  setTimeout(function () {
      a.innerHTML = "&#xf243;";
    }, 1000);
  setTimeout(function () {
      a.innerHTML = "&#xf242;";
    }, 2000);
  setTimeout(function () {
      a.innerHTML = "&#xf241;";
    }, 3000);
  setTimeout(function () {
      a.innerHTML = "&#xf240;";
    }, 4000);
}
chargebattery();
setInterval(chargebattery, 5000);
</script>

<p>This example demonstrates how to use an icon library to make an animated effect.</p>
</body>
</html>


问:
How to make the rest of the code wait until zipfile finishes compiling files
I'm writing a script that compresses multiple files and then uploads the zip file into Google Drive. I managed to do both of these actions separately but when I do them together the uploading begins before the files have been zipped.

```<code># final part of the creating zip file process:
with zipfile.ZipFile(zipFileName+".zip", "w") as zf:
    for f in myFiles:
        zf.write(f)
        print(f)

# last part of the uploading process
file_name = (zipFileName+'.zip')
metadata = {'name': file_name,
            'mimeType': None
            }

res = DRIVE.files().create(body=metadata, media_body=file_name).execute()
if res:
    print('Uploaded "%s" (%s)' % (file_name, res['mimeType']))
</code>```

My hypothetical solution is to make the zipfile process wait but I'm not sure how to go about that.

答:
This is essentially what worked for me:

```<code>zipFileName = input("What do you want to call the zip file?: ")
try:
    zipTheFiles(zipFileName)
except:
    print("Failed to zip the files")
else:
    shipIt(zipFileName)
</code>```

I split the code into two functrions and placed them in a try,except,else statement

Body:
I'm writing a script that compresses multiple files and then uploads the zip file into Google Drive. I managed to do both of these actions separately but when I do them together the uploading begins before the files have been zipped.

# final part of the creating zip file process:
with zipfile.ZipFile(zipFileName+".zip", "w") as zf:
    for f in myFiles:
        zf.write(f)
        print(f)

# last part of the uploading process
file_name = (zipFileName+'.zip')
metadata = {'name': file_name,
            'mimeType': None
            }

res = DRIVE.files().create(body=metadata, media_body=file_name).execute()
if res:
    print('Uploaded "%s" (%s)' % (file_name, res['mimeType']))

My hypothetical solution is to make the zipfile process wait but I'm not sure how to go about that.

Body:
This is essentially what worked for me:

zipFileName = input("What do you want to call the zip file?: ")
try:
    zipTheFiles(zipFileName)
except:
    print("Failed to zip the files")
else:
    shipIt(zipFileName)

I split the code into two functrions and placed them in a try,except,else statement


问:
How to creating device to Google IoT core by Android Application?
I'm porting the following GCP IoT core function to Android Studio Gradle project.

createDeviceWithRs256

https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/iot/api-client/manager/src/main/java/com/example/cloud/iot/examples/DeviceRegistryExample.java

And when I just call this function, the application will  crash.

```<code>    GoogleCredential credential =
            GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
</code>```

Is there I have no GCP credentials inside the App?

--

This is my setting for the gradle file

```<code>// My Platform is Android 7.0
defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 24
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
}

dependencies {
    ...
    implementation 'com.google.api-client:google-api-client:1.30.8'
    implementation 'com.google.apis:google-api-services-cloudiot:v1-rev94-1.25.0'
    ...
}
</code>```

And the error log is:

```<code>--------- beginning of crash
2020-02-20 15:13:52.964 15387-15387/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 15387
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
        at java.net.Socket.connect(Socket.java:586)
        at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
        at com.android.okhttp.Connection.connectSocket(Connection.java:1455)
        at com.android.okhttp.Connection.connect(Connection.java:1413)
        at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1707)
        at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:133)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:466)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:503)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:148)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:84)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1012)
        at com.google.api.client.googleapis.auth.oauth2.OAuth2Utils.runningOnComputeEngine(OAuth2Utils.java:87)
        at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.detectEnvironment(DefaultCredentialProvider.java:183)
        at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredentialUnsynchronized(DefaultCredentialProvider.java:110)
        at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:91)
        at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:217)
        at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:195)
        at com.example.myapplication.MainActivity.createDeviceWithRs256(MainActivity.java:980)
        at com.example.myapplication.MainActivity.register_button_on_click(MainActivity.java:1034)
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

答:
Caused by: android.os.NetworkOnMainThreadException

This indicates a network call.

You are trying to create this on main thread. Try moving to another thread by using an AsyncTask because network operations are not allowed on main thread.

Body:
I'm porting the following GCP IoT core function to Android Studio Gradle project.

createDeviceWithRs256

https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/iot/api-client/manager/src/main/java/com/example/cloud/iot/examples/DeviceRegistryExample.java

And when I just call this function, the application will  crash.

    GoogleCredential credential =
            GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());

Is there I have no GCP credentials inside the App?

--

This is my setting for the gradle file

// My Platform is Android 7.0
defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 24
    targetSdkVersion 29
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
}

dependencies {
    ...
    implementation 'com.google.api-client:google-api-client:1.30.8'
    implementation 'com.google.apis:google-api-services-cloudiot:v1-rev94-1.25.0'
    ...
}

And the error log is:

--------- beginning of crash
2020-02-20 15:13:52.964 15387-15387/com.example.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 15387
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
     Caused by: android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
        at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:333)
        at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:196)
        at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:356)
        at java.net.Socket.connect(Socket.java:586)
        at com.android.okhttp.internal.Platform.connectSocket(Platform.java:113)
        at com.android.okhttp.Connection.connectSocket(Connection.java:1455)
        at com.android.okhttp.Connection.connect(Connection.java:1413)
        at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:1707)
        at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:133)
        at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:466)
        at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:371)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:503)
        at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:130)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:148)
        at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:84)
        at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1012)
        at com.google.api.client.googleapis.auth.oauth2.OAuth2Utils.runningOnComputeEngine(OAuth2Utils.java:87)
        at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.detectEnvironment(DefaultCredentialProvider.java:183)
        at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredentialUnsynchronized(DefaultCredentialProvider.java:110)
        at com.google.api.client.googleapis.auth.oauth2.DefaultCredentialProvider.getDefaultCredential(DefaultCredentialProvider.java:91)
        at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:217)
        at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.getApplicationDefault(GoogleCredential.java:195)
        at com.example.myapplication.MainActivity.createDeviceWithRs256(MainActivity.java:980)
        at com.example.myapplication.MainActivity.register_button_on_click(MainActivity.java:1034)
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)


问:
Convert moment to format("H[h] m[m]") using moment but its showing invalid date
I'm trying to convert hours into H[h] m[m] format. However when the hours are exceeding 24 it's showing 'Invalid Date'. How can I convert it to the above format?

```<code>var totalHours = parseInt(row.work_duration_seconds) + parseInt(row.break_duration_seconds); //Output : 95122
row.totalHours = totalHours > 60 ? secondsTimeSpanToHMS(totalHours) : '0h'; //Output:  {_isAMomentObject: true, _i: "26:25:22", _f: "HH:mm:ss", _isUTC: false, _pf: {…}, …}
row.totalHours = moment(row.totalHours, 'HH:mm:ss').format("H[h] m[m]"); //Output: Invalid Date
</code>```

答:
Would this  help?</p>

```<code>var hours = 12.5;
moment.utc(hours*3600*1000).format('HH:mm');
//using utc mode. Ambiguous input is assumed to be UTC. Unambiguous input is adjusted to UTC

</code>```

Body:
I'm trying to convert hours into H[h] m[m] format. However when the hours are exceeding 24 it's showing 'Invalid Date'. How can I convert it to the above format?

var totalHours = parseInt(row.work_duration_seconds) + parseInt(row.break_duration_seconds); //Output : 95122
row.totalHours = totalHours > 60 ? secondsTimeSpanToHMS(totalHours) : '0h'; //Output:  {_isAMomentObject: true, _i: "26:25:22", _f: "HH:mm:ss", _isUTC: false, _pf: {…}, …}
row.totalHours = moment(row.totalHours, 'HH:mm:ss').format("H[h] m[m]"); //Output: Invalid Date

Body:
Would this  help?

var hours = 12.5;
moment.utc(hours*3600*1000).format('HH:mm');
//using utc mode. Ambiguous input is assumed to be UTC. Unambiguous input is adjusted to UTC


问:
Python for-loop repeatedly outputting the input() for every iteration of dictionary contact_emails(not what I want)
```<code>   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)
</code>```

The output I want is

```<code>s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf
</code>```

the output I get it

```<code>Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
</code>```

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

答:
You’re iterating over each contact in contact_emails, but the variable contact doesn’t appear in the print call. You can access the email using the name held in contact:

```<code>...
for contact in contact_email:
    print(contact_email[contact], 'is', contact)
</code>```

Remember that new_email and new_contact are assigned outside of the loop so do not change on each iteration.

Body:
   contact_emails = {

         'Sue Reyn' : 's.reyn@email.com',
         'Mike Filt': 'mike.filt@bmail.com',
         'Nate Arty': 'narty042@nmail.com'
             }

         new_contact = input()

         new_email = input()
         contact_emails[new_contact] = new_email

         for contact in contact_emails:
                      print(new_contact + ' is ' + new_email)

The output I want is

s.reyn@email.com is Sue Reyn
mike.filt@bmail.com is Mike Filt
narty042@nmail.com is Nate Arty
alf1@hmail.com is Alf

the output I get it

Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com
Alf is alf1@hmail.com

What am I doing wrong? How should I fix this code to make it output what I would like it to output?

Body:
You’re iterating over each contact in contact_emails, but the variable contact doesn’t appear in the print call. You can access the email using the name held in contact:

...
for contact in contact_email:
    print(contact_email[contact], 'is', contact)

Remember that new_email and new_contact are assigned outside of the loop so do not change on each iteration.


问:
How to manage offsets in KafkaItemReader used in spring batch job in case of any exception occurs in mid of reading messages
I am working on a Kafka based spring boot application for the first time. My requirement was to create an output file with all the records using spring batch. I created a spring batch job where integrated with a customized class which extends KafkaItemReader. I don't want to commit the offsets for now as i might need to go back read some records from already consumed offsets. My consumer config has these properties;

enable.auto.commit: false
auto-offset-reset: latest
group.id:

There are two scenarios->
1. A happy path, where i can read all the messages from kafka topic and transform them and then write them to an output file using above configuration.
2. I am getting an exception while reading thru' the messages, and i am not sure how to manage the offsets in such cases. Even if i go back to rest the offset, how to make sure it is the correct offset for messages. I dont persist the payload of message record anywhere except it goes to the spring batch output file.

答:
You need to use a persistent Job Repository for that and configure the KafkaItemReader to save its state. The state consists in the offset of each partition assigned to the reader and will be saved at chunk boundaries (aka at each transaction).

In a restart scenario, the reader will be initialized with the last offset for each partition from the execution context and resume where it left off.