问:
How to ignore the prefix api route in express for any action?
index.js

```<code>app.use('', routes);
</code>```

routes.js

```<code>app.get('/comments', (req, res) => {

});

app.get('/posts/:id/comments', (req, res) => {

});

app.post('/comments', (req, res) => {

});

app.delete('/comments/:id', (req, res) => {

});

app.put('/comments/:id', (req, res) => {

});
</code>```

I want to prefix all routes with '/comments/' except the one with the following full path: '/posts/:id/comments'. Is this possible to do without creating a new set of routes? I don't want to make another file with the name "routes2.js". I would like to use app.use('/comments/', routes); without having to create another set of routes so I can avoid repeating myself.

答:
you can try this in your
index.js

```<code> routes=require('path/to/routes.js')
  //move this route out of routes.js
 app.get('/posts/:id/comments', (req, res) => {

  });

 app.use('/comments', routes);
</code>```

and in your
routes.js

```<code>router=require('express').Router

router.get('/', (req, res) => {

});

router.post('/', (req, res) => {

});

router.delete('/', (req, res) => {

});

router.put('/', (req, res) => {

});

exports.module=router
</code>```

Body:
index.js

app.use('', routes);

routes.js

app.get('/comments', (req, res) => {

});

app.get('/posts/:id/comments', (req, res) => {

});

app.post('/comments', (req, res) => {

});

app.delete('/comments/:id', (req, res) => {

});

app.put('/comments/:id', (req, res) => {

});

I want to prefix all routes with '/comments/' except the one with the following full path: '/posts/:id/comments'. Is this possible to do without creating a new set of routes? I don't want to make another file with the name "routes2.js". I would like to use app.use('/comments/', routes); without having to create another set of routes so I can avoid repeating myself.

Body:
you can try this in your
index.js

 routes=require('path/to/routes.js')
  //move this route out of routes.js
 app.get('/posts/:id/comments', (req, res) => {

  });

 app.use('/comments', routes);

and in your
routes.js

router=require('express').Router

router.get('/', (req, res) => {

});

router.post('/', (req, res) => {

});

router.delete('/', (req, res) => {

});

router.put('/', (req, res) => {

});

exports.module=router


来源: stackexchange

问:
How could I modify django-tracking2 so users can opt out of tracking
I'm making a website right now and need to use django-tracking2 for analytics. Everything works but I would like to allow users to opt out and I haven't seen any options for that. I was thinking modifying the middleware portion may work but honestly, I don't know how to go about that yet since I haven't written middleware before.

I tried writing a script to check a cookie called no_track and if it wasn't set, I would set it to false for default tracking and if they reject, it sets no_track to True but I had no idea where to implement it (other than the middle ware, when I tried that the server told me to contact the administrator). I was thinking maybe I could use signals to prevent the user being tracked but then that would slow down the webpage since it would have to deal with preventing a new Visitor instance on each page (because it would likely keep making new instances since it would seem like a new user). Could I subclass the Visitor class and modify __init__ to do a check for the cookie and either let it save or don't.

Thanks for any answers, if I find a solution I'll edit the post or post and accept the answer just in case someone else needs this.

答:
I made a function in my tools file (holds all functions used throughout the project to make my life easier) to get and set a session key. Inside the VisitorTrackingMiddleware I used the function _should_track() and placed a check that looks for the session key (after _should_track() checks that sessions is installed and before all other checks), with the check_session() function in my tools file, if it doesn't exist, the function creates it with the default of True (Track the user until they accept or reject) and returns an HttpResponse (left over from trying the cookie method).

When I used the cookie method, the firefox console said the cookie will expire so I just switched to sessions another reason is that django-tracking2 runs on it.

It seems to work very well and it didn't have a very large impact on load times, every time a request is made, that function runs and my debug tells me if it's tracking me or not and all the buttons work through AJAX. I want to run some tests to see if this does indeed work and if so, maybe I'll submit a pull request to django-tracking2 just in case someone else wants to use it.

A Big advantage to this is that you can allow users to change their minds if they want or you can reprompt at user sign up depending on if they accepted or not. with the way check_session() is set up, I can use it in template tags and class methods as well.

ContentLicense: CC BY-SA 4.0


问:
Increment a key's value (+1) within a series of objects contained in an array that's held in useState
```<code>const = [items, setItems] = useState([{ name: "foo", wait: 1 }, { name: "bar", wait: 5 }])
</code>```

I need to increase the key's value, wait, by 1 for all objects inside items.

Here is my attempt so far...

```<code>setItems(items.map(e => [...e, e.wait++]))
</code>```

I get some crazy error... I'm not sure if I should use a spread operator or something close to what I have.

答:
map should return the object instead of array.

const items = [
  { name: "foo", wait: 1 },
  { name: "bar", wait: 5 },
];

const updated = items.map((item) => ({ ...item, wait: item.wait + 1 }));

// setItems(items.map(item => ({...item, wait: item.wait + 1})));

console.log(updated);```

Body:
const = [items, setItems] = useState([{ name: "foo", wait: 1 }, { name: "bar", wait: 5 }])

I need to increase the key's value, wait, by 1 for all objects inside items.

Here is my attempt so far...

setItems(items.map(e => [...e, e.wait++]))

I get some crazy error... I'm not sure if I should use a spread operator or something close to what I have.


问:
Any ideas about how to use CSS to emulate a messy stamp?
I'm interested in ways to render a span that to look something like one of these:

Here are the tricks I plan on using:

@font-face

-{moz/webkit/o}-transform:rotate

It's for a personal project so assuming the most modern CSS support is fine. Maybe border-images could help? I'd like to avoid image splicing all over the place -- if it really comes down to that I'll just skip the border all together and rely on a font for the look.

I'm just curious how the CSS gurus around here would approach this.

UPDATE

There is now a CSS property for this, mask-image. More here.

答:
You can achieve the distressed font effect by importing (http://www.font-face.com/) a font similar to http://www.fontspace.com/category/stamp.

I am not sure if you can do the border with plain CSS. You can add a distressed transparent overlay over your stamp which will make it look good, and will not require the custom font.

CSS can be used to create the double stamp border with CSS double border + outline. You need to make the outer border color white, and the inner and outline colors the same. The outline should be thicker than the border.

ContentLicense: CC BY-SA 3.0


问:
Clicking Outlook safelink protection links in emails seems to be executing the code twice
This is not really related on coding per-se, my project is in Laravel 7.1 but more in Outlook's security measurements.

Basically I have a function that sends an email which contains a button, it's a link with a token and a route in my Laravel project to perform something (in this case, the confirmation of an appointment cancellation). When the button is clicked it redirects the user to a page displaying a message saying that the appointment was cancelled successfully or that the token expired (because ofc doing the operation once ends up in removing the token from the database, so trying to do it again will fail and display the message).

This works as intended in testing environments, clicking the same button in Gmail or copying and pasting the link in the browser address bar.

But with Outlook and their masked links with safelink protection, is not working right, once the button is clicked it redirects the user to a expired token message, BUT the operations were performed as they should.
This happens because safelink is visiting the link and checking if it's secure before letting the user open a new tab, issue is that the "fake" visit is making my application to perform the actions as it normally should: (it cancels the appointment based on that token, and it removes the token from database), so by the moment the user is redirected that is counting as a second visit to the link and what the user is getting outputted is the expired token message, which is misleading of course.

This is basically a problem for any one time use links and that's probably affecting other applications out there.

This is a recent change from Microsoft though as this was working a couple months back, safelink is not something new but they introduced that new security feature. It may be happening with other mail providers too, but I just tested with Gmail which is not doing the same and it worked.

So I don't really know what could I do from my part to fix this, is there a way to detect if the click is not coming from a real user or something? are there measurements put in place by Laravel to overcome this?

Thanks in advance.

答: That behavior's been there for a while. The best you can do is to provide a link to a page where the user would have to explicitly click another link or a button. </p>


问:
How can I call a graphql lambda from another lambda in nodejs?
I created graphql lambda by following this instruction: https://www.apollographql.com/docs/apollo-server/deployment/lambda/
It works fine with API gateway. However, I need to call this lambda function from another lambda. I think I need to put ApolloClient in the other lambda function in order to send a graphql request. However, it doesn't work because I can't choose a right link for calling lambda.
So I am looking for how to build the graphql request programatically. I can send the request as an event to trigger the graphql lambda.

Is there a way to do that?

For example, if I have a mutation request like:

```<code> mutation sendMessage {
      sendMessage(text: "hello"){
      text
    }
</code>```

I need to find a way to convert the request to below payload:

```<code>{"id":"1","type":"start","payload":{"variables":{},"extensions":{},"operationName":"sendMessage","query":"mutation sendMessage {\\n  sendMessage(text: \\"hello\\") {\\n    text\\n    __typename\\n  }\\n}\\n"}}
</code>```

then I send this payload to the graphql lambda function

答:
You can use graphQL client to perform graphQL request via API Gateway endpoint using HTTP.

Given that you have an API Gateway endpoint pointing to the graphQL server, you can perform a graphQL request to that endpoint from another lambda.

GraphQL queries to the server is simply a regular POST request formatted in a certain way. So if you wanted, you could use any server-side HTTP client to perform that request. However, using a library like graphql-request makes it much simpler.

You can use graphql-request package to perform server-side graphQL requests.

```<code>import { request } from 'graphql-request'

const endpoint="https://your-api-gateway-endpoint";

const headers = {
  "x-api-key": 'api-gateway-key' // if your endpoint requires API key
};

const client = new GraphQLClient(endpoint, { headers });

const query = `{
  mutation sendMessage {
      sendMessage(text: "hello"){
      text
  }
}`;

const data = await client.request(query);
console.log(JSON.stringify(data, undefined, 2));

</code>```

Body:
I created graphql lambda by following this instruction: https://www.apollographql.com/docs/apollo-server/deployment/lambda/
It works fine with API gateway. However, I need to call this lambda function from another lambda. I think I need to put ApolloClient in the other lambda function in order to send a graphql request. However, it doesn't work because I can't choose a right link for calling lambda.
So I am looking for how to build the graphql request programatically. I can send the request as an event to trigger the graphql lambda.

Is there a way to do that?

For example, if I have a mutation request like:

 mutation sendMessage {
      sendMessage(text: "hello"){
      text
    }

I need to find a way to convert the request to below payload:

{"id":"1","type":"start","payload":{"variables":{},"extensions":{},"operationName":"sendMessage","query":"mutation sendMessage {\\n  sendMessage(text: \\"hello\\") {\\n    text\\n    __typename\\n  }\\n}\\n"}}

then I send this payload to the graphql lambda function

Body:
You can use graphQL client to perform graphQL request via API Gateway endpoint using HTTP.

Given that you have an API Gateway endpoint pointing to the graphQL server, you can perform a graphQL request to that endpoint from another lambda.

GraphQL queries to the server is simply a regular POST request formatted in a certain way. So if you wanted, you could use any server-side HTTP client to perform that request. However, using a library like graphql-request makes it much simpler.

You can use graphql-request package to perform server-side graphQL requests.

import { request } from 'graphql-request'

const endpoint="https://your-api-gateway-endpoint";

const headers = {
  "x-api-key": 'api-gateway-key' // if your endpoint requires API key
};

const client = new GraphQLClient(endpoint, { headers });

const query = `{
  mutation sendMessage {
      sendMessage(text: "hello"){
      text
  }
}`;

const data = await client.request(query);
console.log(JSON.stringify(data, undefined, 2));


问:
HTTPS Node JS POST issue
I'm using https for this POST request.

Could someone point out the issue here? I get undefined and no error message .

I tried wrapping the request before res.write with no success. I'm getting a

```<code>statusCode: 400
Bad Payload received by generic incoming webhook.
</code>```

Thanks!

connector.js

const https = require('https');

var dataString = {"text": "Hello World"};

const deets = {
    portal_trade_events: {
        host: "outlook.office.com",
        path: "/path",
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': dataString.text.length
        }
    }
};

const options = {
    hostname: deets.portal_trade_events.host,
    port: 443,
    path: deets.portal_trade_events.path,
    method: 'POST',
    headers: deets.portal_trade_events.headers
};

function post(options, data) {
    const req = https.request(options, (res) => {
        console.log(`statusCode: ${res.statusCode}`);

        res.on('data', (d) => {
            process.stdout.write(d)
        });
    });
    req.on('error', (error) => {
        console.error(error)
    });

    req.write(JSON.stringify(data));
    req.end()

}

post(options, dataString);```

答:
At the very least, your headers for content-length look wrong. You're sending the full JSON, not just the one text value.</p>

```<code>const https = require('https');

const data = JSON.stringify({
  text: 'Hello World'
});

const options = {
  hostname: 'outlook.office.com',
  port: 443,
  path: '/path',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);
  res.on('data', (d) => {
    process.stdout.write(d);
  });
});
req.on('error', (error) => {
  console.error(error);
});
req.write(data);
req.end();
</code>```

Title: HTTPS Node JS POST issue

Body:
I'm using https for this POST request.

Could someone point out the issue here? I get undefined and no error message .

I tried wrapping the request before res.write with no success. I'm getting a

statusCode: 400
Bad Payload received by generic incoming webhook.

Thanks!

connector.js

const https = require('https');

var dataString = {"text": "Hello World"};

const deets = {
    portal_trade_events: {
        host: "outlook.office.com",
        path: "/path",
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': dataString.text.length
        }
    }
};

const options = {
    hostname: deets.portal_trade_events.host,
    port: 443,
    path: deets.portal_trade_events.path,
    method: 'POST',
    headers: deets.portal_trade_events.headers
};

function post(options, data) {
    const req = https.request(options, (res) => {
        console.log(`statusCode: ${res.statusCode}`);

        res.on('data', (d) => {
            process.stdout.write(d)
        });
    });
    req.on('error', (error) => {
        console.error(error)
    });

    req.write(JSON.stringify(data));
    req.end()

}

post(options, dataString);

Body:
At the very least, your headers for content-length look wrong. You're sending the full JSON, not just the one text value.

const https = require('https');

const data = JSON.stringify({
  text: 'Hello World'
});

const options = {
  hostname: 'outlook.office.com',
  port: 443,
  path: '/path',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
};

const req = https.request(options, (res) => {
  console.log(`statusCode: ${res.statusCode}`);
  res.on('data', (d) => {
    process.stdout.write(d);
  });
});
req.on('error', (error) => {
  console.error(error);
});
req.write(data);
req.end();


问:
clang: error: linker command failed with exit code 1 (use -v to see invocation) - Undefined symbols for architecture x86_64:
What is wrong with declaration of the CellType? This is an implementation of linked list. listHead is a new empty linked list. Due to the usage listHead in other section of the code i tried to declare it as global variable.</p>

```<code>#include <iostream>

typedef struct CellType* Position;
typedef int ElementType;
struct CellType{
    ElementType value;
    Position next;
};

class List{
public:
    CellType* listHead;
    void makeNull();    //Create a new list
    void insertList(ElementType x, Position p); //Insert element to the list
    void deleteList(Position p);    //delete an element at position p
    Position first();   //get Position of first
    Position end();     //get Position of end
    Position next(Position p);  //get position of next
    void printList();   //print list
};

void List::makeNull(){
    listHead = new CellType;
    listHead -> next = NULL;
}

void List::insertList(ElementType x, Position p){
    Position temp;
    temp = p -> next;
    p->next = new CellType;
    p->value = x;
    p->next->next = temp;
}

void List::deleteList(Position p){
    p->next = p->next->next;
}

Position List::first(){
    return (listHead);
}

Position List::end(){
    Position p;
    p = listHead;
    while(p->next != NULL){
        p = p->next;
    }
    return(p);
}

Position List::next(Position p){
    return(p->next);
}
</code>```

答:
This issue is related to the os version updates and version of g++. I am using MacOS 10.15.5.

compiled again with g++ then linked successfully.

Body:
What is wrong with declaration of the CellType? This is an implementation of linked list. listHead is a new empty linked list. Due to the usage listHead in other section of the code i tried to declare it as global variable.

#include <iostream>

typedef struct CellType* Position;
typedef int ElementType;
struct CellType{
    ElementType value;
    Position next;
};

class List{
public:
    CellType* listHead;
    void makeNull();    //Create a new list
    void insertList(ElementType x, Position p); //Insert element to the list
    void deleteList(Position p);    //delete an element at position p
    Position first();   //get Position of first
    Position end();     //get Position of end
    Position next(Position p);  //get position of next
    void printList();   //print list
};

void List::makeNull(){
    listHead = new CellType;
    listHead -> next = NULL;
}

void List::insertList(ElementType x, Position p){
    Position temp;
    temp = p -> next;
    p->next = new CellType;
    p->value = x;
    p->next->next = temp;
}

void List::deleteList(Position p){
    p->next = p->next->next;
}

Position List::first(){
    return (listHead);
}

Position List::end(){
    Position p;
    p = listHead;
    while(p->next != NULL){
        p = p->next;
    }
    return(p);
}

Position List::next(Position p){
    return(p->next);
}


问:
Python Panda - Renaming Double Layer Names back to Single after using .AGG
When creating an output using .agg and specifying multiple functions, you end up creating a double layer name - so for example ["Points", "std"] which is the standard deviation of the variable Points.

However I want to merge this data back to master data set where everything is at the single level, how do I change this name back to something that's compatible like "Points_STD". Logically I have tried using .rename to reference as above but it just doesn't work.

Thanks in advance

So this bit works :

```<code>df_K = df4.groupby(["Team"]).agg({
            'Shots' : ['mean', 'std']
        }).reset_index()

df_K["STD2"] = df_K["Shots", "std"] / df_K["Shots", "mean"]
</code>```

This doesn't :

```<code>df_K.rename(columns = {"Shots", "std":'Shots_Std' }, inplace = True)
</code>```

p.s Picture as referred to in comments

答:
If you use .agg to separate each of them, it will not be multi-indexed.

```<code>import pandas as pd
import numpy as np
import io

data = '''
Team Player Shots
A a 2
A b 3
A c 5
B e 1
B f 6
B g 7
'''

df = pd.read_csv(io.StringIO(data), sep='\s+')

df_K = df.groupby(["Team"])['Shots'].agg(Shots_mean='mean', Shots_std='std')
df_K["STD2"] = df_K["Shots_std"] / df_K["Shots_mean"]

df_K.reset_index(inplace=True)

    Team    Shots_mean  Shots_std   STD2
0   A   3.333333    1.527525    0.458258
1   B   4.666667    3.214550    0.688832
</code>```

Body:
When creating an output using .agg and specifying multiple functions, you end up creating a double layer name - so for example ["Points", "std"] which is the standard deviation of the variable Points.

However I want to merge this data back to master data set where everything is at the single level, how do I change this name back to something that's compatible like "Points_STD". Logically I have tried using .rename to reference as above but it just doesn't work.

Thanks in advance

So this bit works :

df_K = df4.groupby(["Team"]).agg({
            'Shots' : ['mean', 'std']
        }).reset_index()

df_K["STD2"] = df_K["Shots", "std"] / df_K["Shots", "mean"]

This doesn't :

df_K.rename(columns = {"Shots", "std":'Shots_Std' }, inplace = True)

p.s Picture as referred to in comments

Body:
If you use .agg to separate each of them, it will not be multi-indexed.

import pandas as pd
import numpy as np
import io

data = '''
Team Player Shots
A a 2
A b 3
A c 5
B e 1
B f 6
B g 7
'''

df = pd.read_csv(io.StringIO(data), sep='\s+')

df_K = df.groupby(["Team"])['Shots'].agg(Shots_mean='mean', Shots_std='std')
df_K["STD2"] = df_K["Shots_std"] / df_K["Shots_mean"]

df_K.reset_index(inplace=True)

    Team    Shots_mean  Shots_std   STD2
0   A   3.333333    1.527525    0.458258
1   B   4.666667    3.214550    0.688832


问:
How to stop a SwiftUI Picker from reacting to touches outside its visible area?
I have in a View a Picker that I wish to limit to a defined height and width.  While the code below accomplishes that visually, the picker responds to tap actions outside of its area -- in some cases, responding to tap on a nearby button as if I were tapping to scroll the picker to the beginning or end of its values.  (The button doesn't respond to the tap; the picker does.  But this also occurs when tapping close to - but outside of - the Picker, where there is NO control.)

The picker seems to respond to touches both above, below, and to the side.  When the view is big enough (full screen, or 2/3 screen), the effect become less noticeable, but when the whole app is getting only 1/3 of the screen, and the picker's width -- as a function of the View's geometry -- becomes small, the other controls are also closer together, and it becomes very difficult to work with.

How can the Picker be made to ignore all touches outside of its visible area?

```<code>Picker(selection: self.$monthSelector, label: Text("Month")) {
   ForEach(0 ..< 12, id: \.self) {
      Text(self.monthNames()[$0])
         .foregroundColor(  Color.black )
      }
   }
      .labelsHidden()
       // THE FOLLOWING 2 STATEMENTS *IN CONJUNCTION* SEEM TO GIVE DESIRED Height/Width
      .fixedSize()
      .frame(maxWidth: geometry.size.width * 0.35, maxHeight: 100)
      .clipped()     // seems to accomplish nothing, visually or regarding touches
      .background(Color.white)
      .cornerRadius(10)
</code>```

Things I've considered:

Putting .clipped on the frame (suggested here). No effect.

This Question Not SwiftUI, and no real lead from it I could determine.

This Question Discusses expanding the tappable area of a button. Don't see a way to apply the key insight ("apply modifiers to the content of the button rather than to the button itself") to a Picker -- especially with regard to its height.

This Question Has no answer, and what I'm seeing with the picker seems well beyond the ~ 15 pts "margin of error" that the comment to that question seems to attribute.  Also, what I'm seeing with the Picker happens in both the simulator and also an actual device.

答:
Here is a solution. Tested with Xcode 11.4 / iOS 13.4.</p>

```<code>.compositingGroup() // << add this modifier above clipping !!!
.clipped()
</code>```

Body:
I have in a View a Picker that I wish to limit to a defined height and width.  While the code below accomplishes that visually, the picker responds to tap actions outside of its area -- in some cases, responding to tap on a nearby button as if I were tapping to scroll the picker to the beginning or end of its values.  (The button doesn't respond to the tap; the picker does.  But this also occurs when tapping close to - but outside of - the Picker, where there is NO control.)

The picker seems to respond to touches both above, below, and to the side.  When the view is big enough (full screen, or 2/3 screen), the effect become less noticeable, but when the whole app is getting only 1/3 of the screen, and the picker's width -- as a function of the View's geometry -- becomes small, the other controls are also closer together, and it becomes very difficult to work with.

How can the Picker be made to ignore all touches outside of its visible area?

Picker(selection: self.$monthSelector, label: Text("Month")) {
   ForEach(0 ..< 12, id: \.self) {
      Text(self.monthNames()[$0])
         .foregroundColor(  Color.black )
      }
   }
      .labelsHidden()
       // THE FOLLOWING 2 STATEMENTS *IN CONJUNCTION* SEEM TO GIVE DESIRED Height/Width
      .fixedSize()
      .frame(maxWidth: geometry.size.width * 0.35, maxHeight: 100)
      .clipped()     // seems to accomplish nothing, visually or regarding touches
      .background(Color.white)
      .cornerRadius(10)

Things I've considered:

Putting .clipped on the frame (suggested here). No effect.

This Question Not SwiftUI, and no real lead from it I could determine.

This Question Discusses expanding the tappable area of a button. Don't see a way to apply the key insight ("apply modifiers to the content of the button rather than to the button itself") to a Picker -- especially with regard to its height.

This Question Has no answer, and what I'm seeing with the picker seems well beyond the ~ 15 pts "margin of error" that the comment to that question seems to attribute.  Also, what I'm seeing with the Picker happens in both the simulator and also an actual device.

Body:
Here is a solution. Tested with Xcode 11.4 / iOS 13.4.

.compositingGroup() // << add this modifier above clipping !!!
.clipped()


问:
PHP mysql-7.2 cannot install on Ubuntu
Im trying to switch my server to PHP 7.2.
Ive got it working on Apache2, and its running fine.

The only issue is the MYSQL extension is not working.

I've commented these lines in php.ini

```<code>extension=mysqli
extension=pdo_mysql
</code>```

But it appears that I dont even have the mysqli extension in the first place.

I try installing it like so

```<code> sudo apt-get install php7.2-mysql
</code>```

But I just get this error

```<code>E: Unable to locate package php7.2-mysql
E: Couldn't find any package by regex 'php7.2-mysql'
</code>```

Ive tried running

```<code>sudo apt-get update
</code>```

Along with following the instructions here and installing some python packages
https://askubuntu.com/questions/1184367/how-to-install-php7-2-in-ubuntu-19-10

But nothing seems to work.
How do I get PHP7.2 working with MYSQL???

答:
php7.2-mysql exists in ubuntu-18.04/bionic only.

php-mysql maps to different versions, so maybe if your using later ubuntu version a >7.2 version will be retruned.

Title: PHP mysql-7.2 cannot install on Ubuntu

Body:
Im trying to switch my server to PHP 7.2.
Ive got it working on Apache2, and its running fine.

The only issue is the MYSQL extension is not working.

I've commented these lines in php.ini

extension=mysqli
extension=pdo_mysql

But it appears that I dont even have the mysqli extension in the first place.

I try installing it like so

 sudo apt-get install php7.2-mysql

But I just get this error

E: Unable to locate package php7.2-mysql
E: Couldn't find any package by regex 'php7.2-mysql'

Ive tried running

sudo apt-get update

Along with following the instructions here and installing some python packages
https://askubuntu.com/questions/1184367/how-to-install-php7-2-in-ubuntu-19-10

But nothing seems to work.
How do I get PHP7.2 working with MYSQL???


问:
Replacing a letter within a string - why is function not working?
the following function is supposed to be replacing instances of 't' with 'a' in a given string input. Not sure why it's not working - suggestions? Cheers</p>

```<code>const replaceLetter = (str) => {

  let newString = str.split(' ')

  for (let i = 0; i < newString.length; i++) {
    for (let j = 0; j < newString[i].length; j++){
      if (newString[i][j] === 't') {
        newString[i][j] = 'a'
      }
    }
  }
  return newString.join(' ')
}
</code>```

答:
The issue with the code is that you are trying to replace characters in a strings. You can't edit a string using that method. If you want to use that method, you can simplify the code by splitting the whole string into single characters.

Your Method:
1. Split the string into words
2. Look at each word one by one
3. Search for a "t" in each word individually
4. Convert to "a"
5. Turn the array into a string by array.join();
6. Return string

The first two steps can be simplified by splitting the string into individual characters
1. Split the string into single characters
2. Search for a "t"
3. Convert to "a"
4. Turn array into string by array.join();
5. Return string

This rendered as code is:

```<code>const replaceLetter = (str) => {
  //Split string into individual characters and make it editable via index method
  let newString = str.split("");
  //Read each character
  for (let i = 0; i < newString.length; i++) {
    //Check if it is a "t"
    if (newString[i] === 't') {
      //Replace it with an "a"
      newString[i] = 'a';
    }
  }
  //Convert the array back to a string
  return newString.join();
}
</code>```

That would allow editing of the string's individual characters and replacing instances of 't' with 'a' in a given string input.

Body:
the following function is supposed to be replacing instances of 't' with 'a' in a given string input. Not sure why it's not working - suggestions? Cheers

const replaceLetter = (str) => {

  let newString = str.split(' ')

  for (let i = 0; i < newString.length; i++) {
    for (let j = 0; j < newString[i].length; j++){
      if (newString[i][j] === 't') {
        newString[i][j] = 'a'
      }
    }
  }
  return newString.join(' ')
}

Body:
The issue with the code is that you are trying to replace characters in a strings. You can't edit a string using that method. If you want to use that method, you can simplify the code by splitting the whole string into single characters.

Your Method:
1. Split the string into words
2. Look at each word one by one
3. Search for a "t" in each word individually
4. Convert to "a"
5. Turn the array into a string by array.join();
6. Return string

The first two steps can be simplified by splitting the string into individual characters
1. Split the string into single characters
2. Search for a "t"
3. Convert to "a"
4. Turn array into string by array.join();
5. Return string

This rendered as code is:

const replaceLetter = (str) => {
  //Split string into individual characters and make it editable via index method
  let newString = str.split("");
  //Read each character
  for (let i = 0; i < newString.length; i++) {
    //Check if it is a "t"
    if (newString[i] === 't') {
      //Replace it with an "a"
      newString[i] = 'a';
    }
  }
  //Convert the array back to a string
  return newString.join();
}

That would allow editing of the string's individual characters and replacing instances of 't' with 'a' in a given string input.


问:
Is there a better way to check if a number is range of two numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

```<code>def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000
</code>```

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

答:
If the logic needs to be generalized then, some form of following function depending on the rounding off and range check can be used:

```<code>def checkRange(number):

   count = 0
   while int(number):
      number /= 10
      count += 1

   round_off = count - 1
   for i in range(count - round_off):
      number *= 10

   number = int(number)

   return int((10**(count - 1)) * (number))
</code>```

So basically, find number of digit the number have then count number of digits you want to preserve and generate the rounded number as a function of these two. Parameratization of the round off can be done as well as needed. We can also include offset as a function of number of digits minus required round off's.

Also from sample code, the lower bound is not required with method even further simplifying the code.

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

Body:
If the logic needs to be generalized then, some form of following function depending on the rounding off and range check can be used:

def checkRange(number):

   count = 0
   while int(number):
      number /= 10
      count += 1

   round_off = count - 1
   for i in range(count - round_off):
      number *= 10

   number = int(number)

   return int((10**(count - 1)) * (number))

So basically, find number of digit the number have then count number of digits you want to preserve and generate the rounded number as a function of these two. Parameratization of the round off can be done as well as needed. We can also include offset as a function of number of digits minus required round off's.

Also from sample code, the lower bound is not required with method even further simplifying the code.


问:
PHP, cURL post to login to WordPress
I am working on a project for a client which needs an automatic login from a link click.

I'm using a handshake page to do this with the following code:

```<code>$username = "admin";
$password = "blog";
$url = "http://wordpressblogURL/";
$cookie = "cookie.txt";

$postdata = "log=" . $username . "&pwd=" . $password . "&wp-submit=Log%20In&redirect_to=" . $url . "blog/wordpress/wp-admin/&testcookie=1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url . "blog/wordpress/wp-login.php");

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url . "blog/wordpress/wp-login.php");

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch);
echo $result;

exit;
</code>```

This works fine. It logs me in great.

The problem is that I believe WordPress keys off of the URL.

To elaborate, my handshake page (which logs me in) is in the "blog" directory and my WordPress application is in the "wordpress" directory which sits inside the "blog" directory. The URL in the browser says ..blog/handshake.php. However, it has the Admin section of WordPress in the browser window. WordPress Admin links now do not function correctly, because the URL is in the ../blog directory when it needs to be in the ..blog/wordpress/wp-admin directory.

Is there a way in cURL to make it so that the URL in the browser reflects the actual page?

Should I be using FSockOPen instead?

答:
Here is the code that worked for me:

The key change is that I removed the parameter called "testcookie" from my post string.

Note: add your website instead of "mywordpress" and username and password in the below code

```<code>$curl = curl_init();

//---------------- generic cURL settings start ----------------
$header     = array(
      "Referer: https://mywordpress/wp-login.php",
"Origin: https://mywordpress",
"Content-Type: application/x-www-form-urlencoded",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15"
      );

curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookies.txt');
//---------------- generic cURL settings end ----------------

$url = 'https://mywordpress/wp-login.php';
curl_setopt($curl, CURLOPT_URL, $url);

$post = 'log=username&pwd=password&wp-submit=Log+In&redirect_to=https%3A%2F% mywordpress%2Fwp-admin%2F';
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);

$output = curl_exec($curl);

curl_close ($curl);

echo ($output)
</code>```

Title: PHP, cURL post to login to WordPress

Body:
I am working on a project for a client which needs an automatic login from a link click.

I'm using a handshake page to do this with the following code:

$username = "admin";
$password = "blog";
$url = "http://wordpressblogURL/";
$cookie = "cookie.txt";

$postdata = "log=" . $username . "&pwd=" . $password . "&wp-submit=Log%20In&redirect_to=" . $url . "blog/wordpress/wp-admin/&testcookie=1";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url . "blog/wordpress/wp-login.php");

curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6");
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt ($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt ($ch, CURLOPT_REFERER, $url . "blog/wordpress/wp-login.php");

curl_setopt ($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt ($ch, CURLOPT_POST, 1);
$result = curl_exec ($ch);
curl_close($ch);
echo $result;

exit;

This works fine. It logs me in great.

The problem is that I believe WordPress keys off of the URL.

To elaborate, my handshake page (which logs me in) is in the "blog" directory and my WordPress application is in the "wordpress" directory which sits inside the "blog" directory. The URL in the browser says ..blog/handshake.php. However, it has the Admin section of WordPress in the browser window. WordPress Admin links now do not function correctly, because the URL is in the ../blog directory when it needs to be in the ..blog/wordpress/wp-admin directory.

Is there a way in cURL to make it so that the URL in the browser reflects the actual page?

Should I be using FSockOPen instead?

Body:
Here is the code that worked for me:

The key change is that I removed the parameter called "testcookie" from my post string.

Note: add your website instead of "mywordpress" and username and password in the below code

$curl = curl_init();

//---------------- generic cURL settings start ----------------
$header     = array(
      "Referer: https://mywordpress/wp-login.php",
"Origin: https://mywordpress",
"Content-Type: application/x-www-form-urlencoded",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15"
      );

curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_COOKIESESSION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, 'cookies.txt');
curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookies.txt');
//---------------- generic cURL settings end ----------------

$url = 'https://mywordpress/wp-login.php';
curl_setopt($curl, CURLOPT_URL, $url);

$post = 'log=username&pwd=password&wp-submit=Log+In&redirect_to=https%3A%2F% mywordpress%2Fwp-admin%2F';
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $post);

$output = curl_exec($curl);

curl_close ($curl);

echo ($output)


问:
trying to call method of inner class from outerclass object
I'd like to understand how nested class work.

Say I have an outer class which has a field that is a linked list of inner class object.

Then I create an object of the outer class and tries to call the method defined in the inner class from a node in the linked list in the outer class.

It doesn't seem to work and here is the code:
THE FOLLOWING IS PART OF A HOMEWORK, HEAVILY MODIFIED IT WILL BE, PLEASE DON'T COPY THANK YOU!

```<code>public class Svec {
    Node head;
    public class Node {
        public Object data;
        public int index;
        public Node next;

        Node(Object d, int indexx){
            data=d;
            index= indexx;
        }
        public String toString()
        {
            return "Im a node";
        }
        public int getIndex()
        {
            return this.index;
        }
    }

    public Svec(int length) {
        head= new Node(null,0);
        Node currNode = this.head, prev =null;
        for(int i =1 ;i<length;i++)
        {
            prev=currNode;
            currNode.next = new Node(null,i);
            currNode=currNode.next;
        }
    }
    public Object get(int index) {
        Node currNode = this.head;

        while(currNode != null && currNode.index != index)
            currNode=currNode.next;

        if(currNode != null)
            return currNode;
        else
            return null;
    }

    public static void main(String[] args)
    {
        Svec example1= new Svec(10);

        System.out.println((example1.get(0)).getIndex());
    }

}
</code>```

The last line in the main method is the error.

答:
Svec.get() returns an Object. Objects have no getIndex() method. Either change that method to return a Node, or cast it to a Node prior to calling getIndex() on it.

```<code>Node result = (Node) example1.get(0);
System.out.println(result.getIndex());
</code>```

Body:
I'd like to understand how nested class work.

Say I have an outer class which has a field that is a linked list of inner class object.

Then I create an object of the outer class and tries to call the method defined in the inner class from a node in the linked list in the outer class.

It doesn't seem to work and here is the code:
THE FOLLOWING IS PART OF A HOMEWORK, HEAVILY MODIFIED IT WILL BE, PLEASE DON'T COPY THANK YOU!

public class Svec {
    Node head;
    public class Node {
        public Object data;
        public int index;
        public Node next;

        Node(Object d, int indexx){
            data=d;
            index= indexx;
        }
        public String toString()
        {
            return "Im a node";
        }
        public int getIndex()
        {
            return this.index;
        }
    }

    public Svec(int length) {
        head= new Node(null,0);
        Node currNode = this.head, prev =null;
        for(int i =1 ;i<length;i++)
        {
            prev=currNode;
            currNode.next = new Node(null,i);
            currNode=currNode.next;
        }
    }
    public Object get(int index) {
        Node currNode = this.head;

        while(currNode != null && currNode.index != index)
            currNode=currNode.next;

        if(currNode != null)
            return currNode;
        else
            return null;
    }

    public static void main(String[] args)
    {
        Svec example1= new Svec(10);

        System.out.println((example1.get(0)).getIndex());
    }

}

The last line in the main method is the error.

Body:
Svec.get() returns an Object. Objects have no getIndex() method. Either change that method to return a Node, or cast it to a Node prior to calling getIndex() on it.

Node result = (Node) example1.get(0);
System.out.println(result.getIndex());


问:
Parsley-rails form not submitting rails 5. Works on other forms
I am trying to use parsley-rails validation on some forms in my rails app. Problem is that it works perfectly on some forms and doesn't submit on other forms.

I've tried adding required true to all form elements. I have also used different variations of "data-parsley-validate" => true, "data-parsley-validate" => "". Nothing seems to work. Here is the code to the form that works.

```<code>= simple_form_for(([@place, @place.reviews.build]), html: {"data-parsley-validate" => true}) do |f|
 %p= "Please rate your experience"
  .rating-form
  %hr
  = f.input :comment, input_html: {maxlength: 1000, rows: 10}, label: "Please describe your experience at the location", hint: "Enter a brief description of your experience", error: "You must provide a description for this review.", required: true
  %hr
  = f.submit "Review this place", :class => "btn btn-primary btn-large"

:javascript
  $('.rating-form').raty({
    path: '/assets',
    scoreName: 'review[rating]'
  });
</code>```

However, I'm unable to submit this form after validation:

```<code>= simple_form_for(@place, html: {class: "form-group", "data-parsley-validate" => true}) do |f|

 = f.error_notification
  .form-inputs
    = f.input :name, label: "Please enter the name of your place", hint: "eg. Papa Chris's Pizza.", required: true
    = f.label :Select_a_category
    %br
    = f.collection_select :category_id, Category.all, :id, :name, prompt: "Please choose a category", required: true
    %br
    = f.input :short_description, label: "Please enter a short description of your place", hint: "eg. Papa Chris's Pizza.", required: true
    = f.input :description, as: :trix_editor, input_html: {maxlength: 1000, rows: 10}, label: "Please describe your place", hint: "Enter a brief description of your place", required: true
    = f.attachment_field :place_images_files, direct: true, multiple: true
    = f.simple_fields_for :locations do |location|
      = location.input :address, label: "Please enter the address of your place", hint: "eg. Lumumba Drive", required: true
      = location.input :city, label: "Please enter the city of your promotion", hint: "eg. Tema", required: true
    = f.input :phone, label: "Please enter your phone number", hint: "eg. 030 412 3123", :input_html => { :maxlength => 10, :"data-mask" => "999 999 9999" }, required: true
    = f.input :mobile_number,label: "Please enter your mobile number", hint: "eg. 020 111 2222", :input_html => { :maxlength => 10, :"data-mask" => "999 999 9999" }, required: true
    = f.input :website,label: "Please enter your website", hint: "eg. papajohns.com"
  .form-actions
    = f.button :submit, class: "btn btn-large btn-primary"
</code>```

Here is my application.js file:

```<code>//= require rails-ujs
//= require jquery3
//= require jquery-ui
//= require ./jquery.raty.js
//= require jquery.timepicker.js
//= require jquery-mask-plugin
//= require jquery.slick
//= require parsley
//= require refile
//= require trix
//= require popper
//= require bootstrap-sprockets
//= require leaflet
//= require dropzone
//= require underscore
//= require masonry/jquery.masonry
//= require_tree .
</code>```

My application.css

```<code> *= require leaflet
 *= require 'masonry/transitions'
 *= require_tree
 *= require_self
 *= require trix
 *= require jquery-ui
 *= require jquery.timepicker.css
 *= require dropzone/dropzone
 *= require parsley
 */
</code>```

Nothing shows in the console and web inspector. The submit button just won't work.

答:
Apparently Trix is triggering parsley validation on a disabled input.  See this Trix issue.  The solution is to add
'data-parsley-excluded="[disabled]"
to your form, like this:</p>

```<code><form data-parsley-validate data-parsley-excluded="[disabled]">
  <trix-editor></trix-editor>
  <input type="submit">
</form>
</code>```

Body:
I am trying to use parsley-rails validation on some forms in my rails app. Problem is that it works perfectly on some forms and doesn't submit on other forms.

I've tried adding required true to all form elements. I have also used different variations of "data-parsley-validate" => true, "data-parsley-validate" => "". Nothing seems to work. Here is the code to the form that works.

= simple_form_for(([@place, @place.reviews.build]), html: {"data-parsley-validate" => true}) do |f|
 %p= "Please rate your experience"
  .rating-form
  %hr
  = f.input :comment, input_html: {maxlength: 1000, rows: 10}, label: "Please describe your experience at the location", hint: "Enter a brief description of your experience", error: "You must provide a description for this review.", required: true
  %hr
  = f.submit "Review this place", :class => "btn btn-primary btn-large"

:javascript
  $('.rating-form').raty({
    path: '/assets',
    scoreName: 'review[rating]'
  });

However, I'm unable to submit this form after validation:

= simple_form_for(@place, html: {class: "form-group", "data-parsley-validate" => true}) do |f|

 = f.error_notification
  .form-inputs
    = f.input :name, label: "Please enter the name of your place", hint: "eg. Papa Chris's Pizza.", required: true
    = f.label :Select_a_category
    %br
    = f.collection_select :category_id, Category.all, :id, :name, prompt: "Please choose a category", required: true
    %br
    = f.input :short_description, label: "Please enter a short description of your place", hint: "eg. Papa Chris's Pizza.", required: true
    = f.input :description, as: :trix_editor, input_html: {maxlength: 1000, rows: 10}, label: "Please describe your place", hint: "Enter a brief description of your place", required: true
    = f.attachment_field :place_images_files, direct: true, multiple: true
    = f.simple_fields_for :locations do |location|
      = location.input :address, label: "Please enter the address of your place", hint: "eg. Lumumba Drive", required: true
      = location.input :city, label: "Please enter the city of your promotion", hint: "eg. Tema", required: true
    = f.input :phone, label: "Please enter your phone number", hint: "eg. 030 412 3123", :input_html => { :maxlength => 10, :"data-mask" => "999 999 9999" }, required: true
    = f.input :mobile_number,label: "Please enter your mobile number", hint: "eg. 020 111 2222", :input_html => { :maxlength => 10, :"data-mask" => "999 999 9999" }, required: true
    = f.input :website,label: "Please enter your website", hint: "eg. papajohns.com"
  .form-actions
    = f.button :submit, class: "btn btn-large btn-primary"

Here is my application.js file:

//= require rails-ujs
//= require jquery3
//= require jquery-ui
//= require ./jquery.raty.js
//= require jquery.timepicker.js
//= require jquery-mask-plugin
//= require jquery.slick
//= require parsley
//= require refile
//= require trix
//= require popper
//= require bootstrap-sprockets
//= require leaflet
//= require dropzone
//= require underscore
//= require masonry/jquery.masonry
//= require_tree .

My application.css

 *= require leaflet
 *= require 'masonry/transitions'
 *= require_tree
 *= require_self
 *= require trix
 *= require jquery-ui
 *= require jquery.timepicker.css
 *= require dropzone/dropzone
 *= require parsley
 */

Nothing shows in the console and web inspector. The submit button just won't work.

Body:
Apparently Trix is triggering parsley validation on a disabled input.  See this Trix issue.  The solution is to add
'data-parsley-excluded="[disabled]"
to your form, like this:

<form data-parsley-validate data-parsley-excluded="[disabled]">
  <trix-editor></trix-editor>
  <input type="submit">
</form>


问:
Can you get all positive numbers in python?
So I am playing around in python and I thought:

"Is there a built in list or function that already has infinite numbers, if not how could I build one?"

I did some research and found...
Nothing
That is why I am here!
If you don't know what I mean it would be this but infinite:

b = [1,2,3,4,5,6,7,8,9]

etc;

If there is please tell me! Thank you!
Edit: Thank you!

答:
```<code>from itertools import count

for i in count(1):
    print(i)
</code>```

<p>its infinite though so it might take a while to run </p>

Body:
from itertools import count

for i in count(1):
    print(i)

its infinite though so it might take a while to run


问:
leaflet input search outside of the div map (re-make)
i have a little problem, i'm working on Leaflet maps and i have no idea how could i do that my input search, shows the same results as the input search inside the map, i have looking for answers and some examples, even in the same leaflet documentation, and i cant find anything clear, i hope you can help me with this. the Js code, creates the input search on the map but i need to do my input search outside the map does the same.

<input id="search" type="search" class="sb-search-input" name="Search" autocomplete="off" placeholder="Enter your search term..." id="search" required=""/>

```

<pre class="lang-js prettyprint-override"><code>
      let map = L.map("mapid").setView([-33.45, -70.666667], 4);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '© OpenStreetMap contributors',
}).addTo(map);

var searchText = L.esri.Geocoding.geosearch().addTo(map);

//adding layer groups on the search control
var results = L.layerGroup().addTo(map);

searchText.on("results", function (data) {
  results.clearLayers();

  for (var i = data.results.length - 1; i >= 0; i--) {
    results.addLayer(L.marker(data.results[i].latlng));

    console.log(data.results[i].latlng);
  }
});

</code>```

答:
well thanks everyone hahah, i could do it, but the problem now is that disorder my bootstrap, well anyway here it's the solution.</p>

```<code>var searchText = L.esri.BootstrapGeocoder.search({
 //here we call the input id.
  inputTag: 'search',
  placeholder: 'ex. LAX',
}).addTo(map);
//adding layer groups on the search control
var results = L.layerGroup().addTo(map);

searchText.on('results', function(data){

  results.clearLayers();

  for (var i = data.results.length - 1; i >= 0; i--) {

    results.addLayer(L.marker(data.results[i].latlng));
    console.log(data.results[i].latlng);
  }
})
</code>```

Body:
i have a little problem, i'm working on Leaflet maps and i have no idea how could i do that my input search, shows the same results as the input search inside the map, i have looking for answers and some examples, even in the same leaflet documentation, and i cant find anything clear, i hope you can help me with this. the Js code, creates the input search on the map but i need to do my input search outside the map does the same.

<input id="search" type="search" class="sb-search-input" name="Search" autocomplete="off" placeholder="Enter your search term..." id="search" required=""/>

      let map = L.map("mapid").setView([-33.45, -70.666667], 4);

L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
  attribution:
    '© OpenStreetMap contributors',
}).addTo(map);

var searchText = L.esri.Geocoding.geosearch().addTo(map);

//adding layer groups on the search control
var results = L.layerGroup().addTo(map);

searchText.on("results", function (data) {
  results.clearLayers();

  for (var i = data.results.length - 1; i >= 0; i--) {
    results.addLayer(L.marker(data.results[i].latlng));

    console.log(data.results[i].latlng);
  }
});

Body:
well thanks everyone hahah, i could do it, but the problem now is that disorder my bootstrap, well anyway here it's the solution.

var searchText = L.esri.BootstrapGeocoder.search({
 //here we call the input id.
  inputTag: 'search',
  placeholder: 'ex. LAX',
}).addTo(map);
//adding layer groups on the search control
var results = L.layerGroup().addTo(map);

searchText.on('results', function(data){

  results.clearLayers();

  for (var i = data.results.length - 1; i >= 0; i--) {

    results.addLayer(L.marker(data.results[i].latlng));
    console.log(data.results[i].latlng);
  }
})


问:
Material UI Autocomplete custom renderInput
I'm following various examples from https://material-ui.com/components/autocomplete/ to create a custom autocomplete. I'm trying to use the renderInput property to use a custom input component. All of the examples I find use the TextField component, but I'd like to use a regular input component.

Problem is, the options are never displayed. I've created a demonstration here (swap renderInput with renderInputWORKING to see working version):

https://codesandbox.io/s/epic-johnson-oxy7b?file=/src/App.tsx

with the following code in renderInput:

```<code> const renderInput = (params: AutocompleteRenderInputParams) => {
    console.log(params);
    const { InputLabelProps, inputProps, InputProps } = params;
    return (
      <div>
        <label {...InputLabelProps}>foo</label>
        <input {...InputProps} {...inputProps} />
      </div>
    );
  };
</code>```

How can I use the <input /> component for renderInput prop on <Autocomplete />?

答:
UPDATE

The 4.10.1 release of Material-UI (on June 1, 2020) included a new example in the documentation for this exact case: https://material-ui.com/components/autocomplete/#custom-input.

Pull request: https://github.com/mui-org/material-ui/pull/21257

The most useful example to look at in the documentation is the Customized Autocomplete example which uses InputBase instead of TextField. This example contains the following code for renderInput:

```<code>         renderInput={(params) => (
            <InputBase
              ref={params.InputProps.ref}
              inputProps={params.inputProps}
              autoFocus
              className={classes.inputBase}
            />
          )}
</code>```

The InputProps passed to TextField are placed on a div that wraps the <input>, so most of those props are not appropriate to put directly on the <input> element as you were. In the code above from the documentation example, you can see that it only uses one thing from params.InputProps which is the ref. This ref is used for controlling the anchor element for the listbox of options. A ref is also placed on the <input> itself, but that ref is used for very different purposes. With your code, only one of those refs was getting used.

Below is a working example (based on the Combo Box example since your sandbox has a lot of other customizations that aren't directly related to this question) that uses <input> instead of TextField:

```<code>import React from "react";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <div ref={params.InputProps.ref}>
          <label {...params.InputLabelProps}>My Label </label>
          <input {...params.inputProps} autoFocus />
        </div>
      )}
    />
  );
}
</code>```

Body:
I'm following various examples from https://material-ui.com/components/autocomplete/ to create a custom autocomplete. I'm trying to use the renderInput property to use a custom input component. All of the examples I find use the TextField component, but I'd like to use a regular input component.

Problem is, the options are never displayed. I've created a demonstration here (swap renderInput with renderInputWORKING to see working version):

https://codesandbox.io/s/epic-johnson-oxy7b?file=/src/App.tsx

with the following code in renderInput:

 const renderInput = (params: AutocompleteRenderInputParams) => {
    console.log(params);
    const { InputLabelProps, inputProps, InputProps } = params;
    return (

        foo
        <input {...InputProps} {...inputProps} />

    );
  };

How can I use the <input /> component for renderInput prop on <Autocomplete />?

Body:
UPDATE

The 4.10.1 release of Material-UI (on June 1, 2020) included a new example in the documentation for this exact case: https://material-ui.com/components/autocomplete/#custom-input.

Pull request: https://github.com/mui-org/material-ui/pull/21257

The most useful example to look at in the documentation is the Customized Autocomplete example which uses InputBase instead of TextField. This example contains the following code for renderInput:

         renderInput={(params) => (
            <InputBase
              ref={params.InputProps.ref}
              inputProps={params.inputProps}
              autoFocus
              className={classes.inputBase}
            />
          )}

The InputProps passed to TextField are placed on a div that wraps the <input>, so most of those props are not appropriate to put directly on the <input> element as you were. In the code above from the documentation example, you can see that it only uses one thing from params.InputProps which is the ref. This ref is used for controlling the anchor element for the listbox of options. A ref is also placed on the <input> itself, but that ref is used for very different purposes. With your code, only one of those refs was getting used.

Below is a working example (based on the Combo Box example since your sandbox has a lot of other customizations that aren't directly related to this question) that uses <input> instead of TextField:

import React from "react";
import Autocomplete from "@material-ui/lab/Autocomplete";

export default function ComboBox() {
  return (
    <Autocomplete
      id="combo-box-demo"
      options={top100Films}
      getOptionLabel={option => option.title}
      style={{ width: 300 }}
      renderInput={params => (
        <div ref={params.InputProps.ref}>
          <label {...params.InputLabelProps}>My Label </label>
          <input {...params.inputProps} autoFocus />
        </div>
      )}
    />
  );
}


问:
extend functionality of UIAlertView?
I am using a UIAlertView with a message Peer Disconnected.Back ground works/remaining codes are working without dismiss it.there is a button called Continue. I need to work the remaining codes only after the continue button click.
and also I need to Quit my application in cancel button click.can any one tell me a good way to do it.

My Code is:

```<code>UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];
</code>```

答:
try this:-</p>

```<code>UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];

- (void)alertView:(UIAlertView *)alert didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0)
    {
NSLog(@"cancel clicked");
    }
    else if(buttonIndex==1)
    {
NSLog(@"continue clicked");
    }
    }
</code>```

Title: extend functionality of UIAlertView?

Body:
I am using a UIAlertView with a message Peer Disconnected.Back ground works/remaining codes are working without dismiss it.there is a button called Continue. I need to work the remaining codes only after the continue button click.
and also I need to Quit my application in cancel button click.can any one tell me a good way to do it.

My Code is:

UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];

Body:
try this:-

UIAlertView *alertView;
alertView = [[UIAlertView alloc] initWithTitle:@"Peer Disconnected!" message:nil delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"Continue", nil];
[alertView show];
[alertView release];

- (void)alertView:(UIAlertView *)alert didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex==0)
    {
NSLog(@"cancel clicked");
    }
    else if(buttonIndex==1)
    {
NSLog(@"continue clicked");
    }
    }


问:
A logical condiditon in "with" operator doesn't work
I have this code:

```<code>  def edit(conn, params) do
    with m1 <- Repo.get(Model1, params["model1_id"]),
      m2 <- Repo.get(Model2, params["model2_id"]),
      !is_nil(m1) and !is_nil(m2)
    do
      # 1
      res = !is_nil(m1) and !is_nil(m2)
      IO.puts("***** res: #{res}")                              # ===> false

      IO.puts("***** m1: #{Kernel.inspect(m1)}")                # ===> prints a struct
      IO.puts("***** m1 is_nil: #{is_nil(m1)}")                 # ===> false

      IO.puts("***** m2: #{Kernel.inspect(m2)}")                # ===> nil
      IO.puts("***** m2 is_nil: #{is_nil(m2)}")                 # ===> true

    else
      #2
      _ -> raise ArgumentError, "not found"
    end
  end
</code>```

The flow #1 gets executed even though m2 is nil. How can it be? How to fix it?
Goal - ensure that m1 and m2 aren't nil and then execute the flow #1.

答:
I find myself using with only in specific situations, and in those it really helps, mostly when it's some set of operations that resemble a "pipe", as in, you need results from previous steps in the next one, but are really heterogeneous and you don't have or doesn't make sense to create some token structure to hold transformations and error (similar to an ecto changeset).

In those cases, if knowing the failing step is needed I find wrapping the with statements on a tagged tuple helps, since then you can match on the specific tag having failed. Besides that, you aren't really using idiomatic code because you're using with just as an assignment expression, if you use pattern matching then it becomes more readable and in my opinion more idiomatic. With your example that would mean:

with {_, %Model1{} = m1} <- {Model1, Repo.get(Model1, params["model1_id"])},
     {_, %Model2{} = m2} <- {Model2, Repo.get(Model2, params["model2_id"])}
       do
          # we have both m1 and m2 and they are respectively instances of Model1 and Model2
          # do something with them
          {:ok, {m1, m2}}
else
     {Model1, _} ->
            #failed fetching Model1
            {:error, :no_model1}
     {Model2, _} ->
            #failed fetching Model2
            {:error, :no_model2}
end
```

<p>Pattern matching on exactly the structure you want, and knowing that Repo.get will return either a schema struct or nil, makes it so that you don't have to check if it's nil, if it's not the schema struct it will be nil (unless you're using Repo.get with a select clause where you return something else ofc).</p>

<p>Remember that accessing <code>params["some_key"]</code> might return <code>nil</code> and that would throw an exception when trying to do <code>Repo.get</code>, so you could add two more statements with the conditions for the id and also enabling you to return the id's in case they weren't found, assuming that the id's are numerical ids (if binary change the <code>is_integer</code> to <code>is_binary</code>):</p>

<pre class="lang-elixir prettyprint-override"><code>with {_, id1} when is_integer(id1) <- {:id1, Map.get(params, "model1_id")},
     {_, id2} when is_integer(id2) <- {:id2, Map.get(params, "model2_id")},
     {_, _, %Model1{} = m1} <- {Model1, id1, Repo.get(Model1, id1)},
     {_, _, %Model2{} = m2} <- {Model2, id2, Repo.get(Model2, id2)}
       do
          # we have both m1 and m2 and they are respectively instances of Model1 and Model2
          # do something with them
          {:ok, {m1, m2}}
else
     {id_type, id_value} when id_type in [:id1, :id2] ->
            # one of the id params wasn't an integer
            {:error, {:unexpected_id, id_type, id_value}}
     {Model1, id, _} ->
            # failed fetching Model1
            {:error, {:no_model1, id}}
     {Model2, id, _} ->
            # failed fetching Model2
            {:error, {:no_model2, id}}
end
</code>```

There's probably some better handling of the params to be done, like verifying them before reaching this stage in execution, and if that is done then you could probably go with a case statement since it's only 2 "cases":

case Repo.get(Model1, valid_id_1) do
    %Model1{} = model1 ->

       case Repo.get(Model2, valid_id_2) do
           %Model2{} = model2 -> {:ok, {model1, model2}}
           nil -> {:error, {:no_model2, valid_id_2}}
       end

    nil -> {:error, {:no_model1, valid_id_1}}
end
```

Body:
I have this code:

  def edit(conn, params) do
    with m1 <- Repo.get(Model1, params["model1_id"]),
      m2 <- Repo.get(Model2, params["model2_id"]),
      !is_nil(m1) and !is_nil(m2)
    do
      # 1
      res = !is_nil(m1) and !is_nil(m2)
      IO.puts("***** res: #{res}")                              # ===> false

      IO.puts("***** m1: #{Kernel.inspect(m1)}")                # ===> prints a struct
      IO.puts("***** m1 is_nil: #{is_nil(m1)}")                 # ===> false

      IO.puts("***** m2: #{Kernel.inspect(m2)}")                # ===> nil
      IO.puts("***** m2 is_nil: #{is_nil(m2)}")                 # ===> true

    else
      #2
      _ -> raise ArgumentError, "not found"
    end
  end

The flow #1 gets executed even though m2 is nil. How can it be? How to fix it?
Goal - ensure that m1 and m2 aren't nil and then execute the flow #1.

Body:
I find myself using with only in specific situations, and in those it really helps, mostly when it's some set of operations that resemble a "pipe", as in, you need results from previous steps in the next one, but are really heterogeneous and you don't have or doesn't make sense to create some token structure to hold transformations and error (similar to an ecto changeset).

In those cases, if knowing the failing step is needed I find wrapping the with statements on a tagged tuple helps, since then you can match on the specific tag having failed. Besides that, you aren't really using idiomatic code because you're using with just as an assignment expression, if you use pattern matching then it becomes more readable and in my opinion more idiomatic. With your example that would mean:

with {_, %Model1{} = m1} <- {Model1, Repo.get(Model1, params["model1_id"])},
     {_, %Model2{} = m2} <- {Model2, Repo.get(Model2, params["model2_id"])}
       do
          # we have both m1 and m2 and they are respectively instances of Model1 and Model2
          # do something with them
          {:ok, {m1, m2}}
else
     {Model1, _} ->
            #failed fetching Model1
            {:error, :no_model1}
     {Model2, _} ->
            #failed fetching Model2
            {:error, :no_model2}
end

Pattern matching on exactly the structure you want, and knowing that Repo.get will return either a schema struct or nil, makes it so that you don't have to check if it's nil, if it's not the schema struct it will be nil (unless you're using Repo.get with a select clause where you return something else ofc).

Remember that accessing params["some_key"] might return nil and that would throw an exception when trying to do Repo.get, so you could add two more statements with the conditions for the id and also enabling you to return the id's in case they weren't found, assuming that the id's are numerical ids (if binary change the is_integer to is_binary):

with {_, id1} when is_integer(id1) <- {:id1, Map.get(params, "model1_id")},
     {_, id2} when is_integer(id2) <- {:id2, Map.get(params, "model2_id")},
     {_, _, %Model1{} = m1} <- {Model1, id1, Repo.get(Model1, id1)},
     {_, _, %Model2{} = m2} <- {Model2, id2, Repo.get(Model2, id2)}
       do
          # we have both m1 and m2 and they are respectively instances of Model1 and Model2
          # do something with them
          {:ok, {m1, m2}}
else
     {id_type, id_value} when id_type in [:id1, :id2] ->
            # one of the id params wasn't an integer
            {:error, {:unexpected_id, id_type, id_value}}
     {Model1, id, _} ->
            # failed fetching Model1
            {:error, {:no_model1, id}}
     {Model2, id, _} ->
            # failed fetching Model2
            {:error, {:no_model2, id}}
end

There's probably some better handling of the params to be done, like verifying them before reaching this stage in execution, and if that is done then you could probably go with a case statement since it's only 2 "cases":

case Repo.get(Model1, valid_id_1) do
    %Model1{} = model1 ->

       case Repo.get(Model2, valid_id_2) do
           %Model2{} = model2 -> {:ok, {model1, model2}}
           nil -> {:error, {:no_model2, valid_id_2}}
       end

    nil -> {:error, {:no_model1, valid_id_1}}
end


答: change public Object get(int index) { to public Node get(int index) { and it should work.

Title: trying to call method of inner class from outerclass object


答:
itertools.count produces an iterator over arbitrary, infinite numbers. It's not a sequence (you can't index it, you can only iterate each instance once), but you can keep going forever.

Actually running it to completion will take infinite time of course, so it's typically paired with something that limits it, e.g. itertools.islice, zip-ing with a finite iterable, etc.

Title: Can you get all positive numbers in python?

Body:
So I am playing around in python and I thought:

"Is there a built in list or function that already has infinite numbers, if not how could I build one?"

I did some research and found...
Nothing
That is why I am here!
If you don't know what I mean it would be this but infinite:

b = [1,2,3,4,5,6,7,8,9]

etc;

If there is please tell me! Thank you!
Edit: Thank you!


问:
How to loop through an array, find elements from a mongoose collection to return a new array
I have an array of object id's.

I need to loop through the elements of this array and perform the below operation.

```<code>var commObj;
commentArray.forEach(
    (comment)=>{
        if(comment.parents.length>1){
            Comment.findById(comment.parents[comment.parents.length-2]).exec(
                (err, foundComment)=>{
                    if(!err){
                        commObj = foundComment;
                        if(! commObj.replies){
                            commObj.replies =[];
                        }
                        commObj.replies.push(comment);
                    }else{
                        console.log(err);
                    }
                })
        }
    }
)
return res.status(200).json(commObj);
</code>```

I am seeing that the commObj variable is returned as undefined. I can see that this is happening because of the async nature of the action that I am doing inside the forEach loop. However, I could not figure out a way to return commObj.

答:
In deed, forEach is not usable for loop async operations. Use for-of instead like:</p>

```<code>var commObj;

for (let comment of commentArray) {
  if(comment.parents.length>1){
...
</code>```

Body:
I have an array of object id's.

I need to loop through the elements of this array and perform the below operation.

var commObj;
commentArray.forEach(
    (comment)=>{
        if(comment.parents.length>1){
            Comment.findById(comment.parents[comment.parents.length-2]).exec(
                (err, foundComment)=>{
                    if(!err){
                        commObj = foundComment;
                        if(! commObj.replies){
                            commObj.replies =[];
                        }
                        commObj.replies.push(comment);
                    }else{
                        console.log(err);
                    }
                })
        }
    }
)
return res.status(200).json(commObj);

I am seeing that the commObj variable is returned as undefined. I can see that this is happening because of the async nature of the action that I am doing inside the forEach loop. However, I could not figure out a way to return commObj.

Body:
In deed, forEach is not usable for loop async operations. Use for-of instead like:

var commObj;

for (let comment of commentArray) {
  if(comment.parents.length>1){
...


问:
Scope Search in Laravel returning all results from empty request()
I am working with Scope Search and cannot figure out why my ternary operator is working like it is.

I have the following in my view:

```<code><form action='/search-results' method='GET'>

{{ csrf_field() }}

<div style="background-color:white">

<div class="container py-5">
    <div class="input-group custom-search-form md-form mt-0">
                <input type="text" class="form-control" name="city" placeholder="City...">
                <input type="text" class="form-control" name="search" placeholder="Search...">
                <span class="input-group-btn">
    <button class="btn btn-default-sm" type="submit">
        Submit
    </button>
</div>
</div>
</div>
</form>
</code>```

I have the following in my Controller:

```<code>    public function index()
{

    {
        //The search() function is accessed using 'scopeSearch' within NPIData Model

        $providers = NPIData::lookup()->orderBy('NPI')->paginate(20);

        return view('inc.searchresults', compact('providers'));
    }
</code>```

I have the following in my NPIData model:

```<code>    public function scopeLookup($query)
{

    //this says if the request is NOT empty, return $query (which would be an empty query), otherwise return $query with all the conditions listed

    return empty(request())  ? $query :  $query->where('NPI', 'like', '%'.request()->search.'%')
                                                ->where('Entity Type Code', '=', '1')
                                                ->where('Provider Business Mailing Address City Name', '=', request()->zip)
                                                ->orWhere('Provider First Name', 'like', '%'.request()->search.'%')
                                                ->orWhere('Provider Last Name (Legal Name)', 'like', '%'.request()->search.'%');

                                            }
</code>```

}

When a search term is entered in both the 'city' and 'search' text inputs, the $query executes correctly.  However, if one or both inputs are left blank, the $query returns everything from my NPIData table.  If one or both inputs are left blank, I want my $query to return nothing so the search results are blank.  I assume I have to change something in the second part of my ternary operator but cannot figure out what that should be.

答:
You can use where 1 < 0 which is pretty standard way to get empty result

public function scopeLookup($query)
{
    //this says if the request is NOT empty, return $query (which would be an empty query), otherwise return $query with all the conditions listed

    return empty(request()) ? $query->whereRaw('1 < 0') : $query->where('NPI', 'like', '%'.request()->search.'%')
        ->where('Entity Type Code', '=', '1')
        ->where('Provider Business Mailing Address City Name', '=', request()->zip)
        ->orWhere('Provider First Name', 'like', '%'.request()->search.'%')
        ->orWhere('Provider Last Name (Legal Name)', 'like', '%'.request()->search.'%');
}
```

Body:
I am working with Scope Search and cannot figure out why my ternary operator is working like it is.

I have the following in my view:

<form action='/search-results' method='GET'>

{{ csrf_field() }}

                <input type="text" class="form-control" name="city" placeholder="City...">
                <input type="text" class="form-control" name="search" placeholder="Search...">

    <button class="btn btn-default-sm" type="submit">
        Submit
    </button>

</form>

I have the following in my Controller:

    public function index()
{

    {
        //The search() function is accessed using 'scopeSearch' within NPIData Model

        $providers = NPIData::lookup()->orderBy('NPI')->paginate(20);

        return view('inc.searchresults', compact('providers'));
    }

I have the following in my NPIData model:

    public function scopeLookup($query)
{

    //this says if the request is NOT empty, return $query (which would be an empty query), otherwise return $query with all the conditions listed

    return empty(request())  ? $query :  $query->where('NPI', 'like', '%'.request()->search.'%')
                                                ->where('Entity Type Code', '=', '1')
                                                ->where('Provider Business Mailing Address City Name', '=', request()->zip)
                                                ->orWhere('Provider First Name', 'like', '%'.request()->search.'%')
                                                ->orWhere('Provider Last Name (Legal Name)', 'like', '%'.request()->search.'%');

                                            }

}

When a search term is entered in both the 'city' and 'search' text inputs, the $query executes correctly.  However, if one or both inputs are left blank, the $query returns everything from my NPIData table.  If one or both inputs are left blank, I want my $query to return nothing so the search results are blank.  I assume I have to change something in the second part of my ternary operator but cannot figure out what that should be.


问:
Codeigniter 4 cookies issue not able to set
This is my controller code.  I am not able to set and get the cookies in Codeigniter 4.</p>

```<code>helper('cookie');
$this->response->set_cookie('forgetpwd',$token, time() + (3600),"/",site_url());
print_r($this->request->get_cookie('forgetpwd'));
die();
</code>```

答:
From php.net - https://www.php.net/manual/en/function.setcookie.php

Cookies will not become visible until the next loading of a page that
  the cookie should be visible for. To test if a cookie was successfully
  set, check for the cookie on a next loading page before the cookie
  expires. Expire time is set via the expires parameter. A nice way to
  debug the existence of cookies is by simply calling
  print_r($_COOKIE);.

Body:
This is my controller code.  I am not able to set and get the cookies in Codeigniter 4.

helper('cookie');
$this->response->set_cookie('forgetpwd',$token, time() + (3600),"/",site_url());
print_r($this->request->get_cookie('forgetpwd'));
die();


问:
Variable inside if statement in javaScript
I wonder why my first code doesn't work and the second does. I thought they're basically the same....
Looks like var inside if statement doesn't seem to be processed as expected. Could anyone please clarify why it doesn't work?

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}
```

<hr>

<pre class="lang-js prettyprint-override"><code>var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var arrayLength = myFarm.length;

for (var j = 0; j < arrayLength; j++) {

    console.log(myFarm[j]);

    if (myFarm[j].charAt(0) === "c" || myFarm[j].charAt(0) === "o") {

        alert("Starts with a c or an o!");
    }

}
</code>```

答:
Issue with the first code -
Value of i initialised and incremented in the "for loop" corresponding to myFarm array. so i refers to the actual indexes of the array inside the "for loop", that's where letterCheck and alert condition has to go. Not outside of the "for loop" where i is undefined.</p>

Body:
I wonder why my first code doesn't work and the second does. I thought they're basically the same....
Looks like var inside if statement doesn't seem to be processed as expected. Could anyone please clarify why it doesn't work?

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var letterCheck = myFarm[i].charAt(0);

for (var i = 0; i < myFarm.length; i++) {
    console.log(i);
}

if (letterCheck === "c" || letterCheck === "o") {
    alert("Starts with 'c' or 'o'!");
}

var myFarm = ["chickens", "pigs", "cows", "horses", "ostriches"];
var arrayLength = myFarm.length;

for (var j = 0; j < arrayLength; j++) {

    console.log(myFarm[j]);

    if (myFarm[j].charAt(0) === "c" || myFarm[j].charAt(0) === "o") {

        alert("Starts with a c or an o!");
    }

}


问:
Connecting to docker mongo db image
I'm trying to use these instructions to try to run the mongodb docker image in a container.

I'm able to run the image:

```<code>(virtual) anonymous@anonymous:~/PycharmProjects/PostDekko/climbticks-flaskmongoangul$ sudo docker container ls
CONTAINER ID        IMAGE                                COMMAND                  CREATED             STATUS              PORTS                    NAMES
431a9d693f48        mongo:bionic                         "docker-entrypoint.s…"   24 minutes ago      Up 24 minutes       27017/tcp                climbticks-mongodb
f12d227dcdd8        climbticks-flaskmongoangul_web_dev   "python3.8 index.py"     3 hours ago         Up 3 hours          0.0.0.0:4000->4000/tcp   climbticks-flaskmongoangul_web_dev_1
</code>```

My project is in the 2nd container, and the mongodb image is container_id 431a9d693f48. I can also access the logs, so I know it runs.

From their instructions:

The MongoDB server in the image listens on the standard MongoDB port,
  27017, so connecting via Docker networks will be the same as
  connecting to a remote mongod. The following example starts another
  MongoDB container instance and runs the mongo command line client
  against the original MongoDB container from the example above,
  allowing you to execute MongoDB statements against your database
  instance:

```<code>> $ docker run -it --network some-network --rm mongo mongo --host
> some-mongo test
</code>```

... where some-mongo is the name of your original mongo container.

However.... I don't understand what my "network" is supposed to be. I think that the network argument, from docker's perspective, means a network id. If I run:

```<code>(virtual) anonymous@anonymous:~/PycharmProjects/PostDekko/climbticks-flaskmongoangul$ sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
7fbed634dbdf        bridge              bridge              local
0843e5ae6173        host                host                local
6b3c8eb4b216        none                null                local
cc3d76f1f109        web_dev             bridge              local
</code>```

I get 4 network ids. web_dev is my project's (webserver) container. If I try any of the 4, I get:

```<code>(virtual) anonymous@anonymous:~/PycharmProjects/PostDekko/climbticks-flaskmongoangul$ sudo docker run -it --network cc3d76f1f109 --rm mongo mongo --host climbticks-mongodb test
MongoDB shell version v4.2.7
connecting to: mongodb://climbticks-mongodb:27017/test?compressors=disabled&gssapiServiceName=mongodb
2020-05-31T01:55:08.771+0000 E  QUERY    [js] Error: couldn't connect to server climbticks-mongodb:27017, connection attempt failed: HostNotFound: Could not find address for climbticks-mongodb:27017: SocketException: Host not found (authoritative) :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
2020-05-31T01:55:08.779+0000 F  -        [main] exception: connect failed
2020-05-31T01:55:08.779+0000 E  -        [main] exiting with code 1
</code>```

I also tried various expressions for localhost (0.0.0.0, localhost, etc.) even though that didn't make sense to me.

So.... how do I find what the network is supposed to be?

EDIT: although if I connect to my DB in the shell:

```<code>sudo docker exec -it climbticksmongodb bash
</code>```

then I can talk to it. So the DB is live. I really just need to figure the network issue, it seems.

答:
When you start a container, it starts in the default bridge network, so without specifying any network attached to your containers, they will not be able to connect to each other.

There are several ways to make them interact with each other. You could create a network and then attach both of them.

For example:

```<code>docker network create -d bridge my-bridge-network
</code>```

Then attach it with --network my-bridge-network to both docker run commands.

Or attach it to a running container with docker <container> attach <network>

This is also a problem docker-compose fixes, you are able to run various containers with the same network attached.

Another method is to use the special DNS host.docker.internal which is essentially the containers host localhost. So if you do a docker run mongo -p 27017:27017 and you want to connect in another container you can connect to host.docker.internal:27017 which is your port 27017 bind to the mongo container 27017.

More detailed information on docker documentation:

https://docs.docker.com/network/network-tutorial-standalone/

Title: Connecting to docker mongo db image

Body:
I'm trying to use these instructions to try to run the mongodb docker image in a container.

I'm able to run the image:

(virtual) anonymous@anonymous:~/PycharmProjects/PostDekko/climbticks-flaskmongoangul$ sudo docker container ls
CONTAINER ID        IMAGE                                COMMAND                  CREATED             STATUS              PORTS                    NAMES
431a9d693f48        mongo:bionic                         "docker-entrypoint.s…"   24 minutes ago      Up 24 minutes       27017/tcp                climbticks-mongodb
f12d227dcdd8        climbticks-flaskmongoangul_web_dev   "python3.8 index.py"     3 hours ago         Up 3 hours          0.0.0.0:4000->4000/tcp   climbticks-flaskmongoangul_web_dev_1

My project is in the 2nd container, and the mongodb image is container_id 431a9d693f48. I can also access the logs, so I know it runs.

From their instructions:

The MongoDB server in the image listens on the standard MongoDB port,
  27017, so connecting via Docker networks will be the same as
  connecting to a remote mongod. The following example starts another
  MongoDB container instance and runs the mongo command line client
  against the original MongoDB container from the example above,
  allowing you to execute MongoDB statements against your database
  instance:

> $ docker run -it --network some-network --rm mongo mongo --host
> some-mongo test

... where some-mongo is the name of your original mongo container.

However.... I don't understand what my "network" is supposed to be. I think that the network argument, from docker's perspective, means a network id. If I run:

(virtual) anonymous@anonymous:~/PycharmProjects/PostDekko/climbticks-flaskmongoangul$ sudo docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
7fbed634dbdf        bridge              bridge              local
0843e5ae6173        host                host                local
6b3c8eb4b216        none                null                local
cc3d76f1f109        web_dev             bridge              local

I get 4 network ids. web_dev is my project's (webserver) container. If I try any of the 4, I get:

(virtual) anonymous@anonymous:~/PycharmProjects/PostDekko/climbticks-flaskmongoangul$ sudo docker run -it --network cc3d76f1f109 --rm mongo mongo --host climbticks-mongodb test
MongoDB shell version v4.2.7
connecting to: mongodb://climbticks-mongodb:27017/test?compressors=disabled&gssapiServiceName=mongodb
2020-05-31T01:55:08.771+0000 E  QUERY    [js] Error: couldn't connect to server climbticks-mongodb:27017, connection attempt failed: HostNotFound: Could not find address for climbticks-mongodb:27017: SocketException: Host not found (authoritative) :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
2020-05-31T01:55:08.779+0000 F  -        [main] exception: connect failed
2020-05-31T01:55:08.779+0000 E  -        [main] exiting with code 1

I also tried various expressions for localhost (0.0.0.0, localhost, etc.) even though that didn't make sense to me.

So.... how do I find what the network is supposed to be?

EDIT: although if I connect to my DB in the shell:

sudo docker exec -it climbticksmongodb bash

then I can talk to it. So the DB is live. I really just need to figure the network issue, it seems.

Body:
When you start a container, it starts in the default bridge network, so without specifying any network attached to your containers, they will not be able to connect to each other.

There are several ways to make them interact with each other. You could create a network and then attach both of them.

For example:

docker network create -d bridge my-bridge-network

Then attach it with --network my-bridge-network to both docker run commands.

Or attach it to a running container with docker <container> attach <network>

This is also a problem docker-compose fixes, you are able to run various containers with the same network attached.

Another method is to use the special DNS host.docker.internal which is essentially the containers host localhost. So if you do a docker run mongo -p 27017:27017 and you want to connect in another container you can connect to host.docker.internal:27017 which is your port 27017 bind to the mongo container 27017.

More detailed information on docker documentation:

https://docs.docker.com/network/network-tutorial-standalone/