问:
How to receive images with the Telegram API?
Is it possible to receive images (and store it on the server) which was sent by any user to the bot?

If a image was sent, I receive this JSON post. This is a link to the Telegram Bot-API description. I don't know if it's possible to receive the whole image or not: https://core.telegram.org/bots/api#available-types

```<code>{"update_id":XXXXX,
"message":{"message_id":2222,"from":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"chat":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"date":1435704055,"forward_from":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"forward_date":1435703471,"photo":[{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABI5s-WWq46dqiR0AAgI","file_size":998,"width":51,"height":90},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABHax4HvxYqktiB0AAgI","file_size":9912,"width":180,"height":320},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABNzzDwp3sT2whx0AAgI","file_size":41020,"width":450,"height":800},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABE0Gg-AefJ7Yhh0AAgI","file_size":66058,"width":720,"height":1280}]}}
</code>```

答:
The accepted answer is fine. But here's an answer in more detail. There are three main steps involved before you can get an actual image file. 1) Request from Telegram the file_id. 2) Load a Guzzle client. 3) Request from Telegram the file_path. Pay close attention to the different URL paths below.

```<code>// get file id
$id = $update['message']['photo'][0]['file_id'];
$file_id = "https://api.telegram.org/bot" .
 config('app.telegram_api_key') . "/getFile?file_id=" . $id;

// guzzle client
$guzzle_client = new GuzzleClient();
$request = $guzzle_client->get($file_id);
$response = json_decode($request->getBody(),true);

// get file path
$file_url = "https://api.telegram.org/file/bot" .
 config('app.telegram_api_key') . "/" . $response['result']['file_path'];
</code>```

Body:
Is it possible to receive images (and store it on the server) which was sent by any user to the bot?

If a image was sent, I receive this JSON post. This is a link to the Telegram Bot-API description. I don't know if it's possible to receive the whole image or not: https://core.telegram.org/bots/api#available-types

{"update_id":XXXXX,
"message":{"message_id":2222,"from":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"chat":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"date":1435704055,"forward_from":{"id":XXXXX,"first_name":"Christoph","last_name":"XXXXX"},"forward_date":1435703471,"photo":[{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABI5s-WWq46dqiR0AAgI","file_size":998,"width":51,"height":90},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABHax4HvxYqktiB0AAgI","file_size":9912,"width":180,"height":320},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABNzzDwp3sT2whx0AAgI","file_size":41020,"width":450,"height":800},{"file_id":"AgADAgADmaoxG9KknwF4O978o3EMqb_EWSoABE0Gg-AefJ7Yhh0AAgI","file_size":66058,"width":720,"height":1280}]}}

Body:
The accepted answer is fine. But here's an answer in more detail. There are three main steps involved before you can get an actual image file. 1) Request from Telegram the file_id. 2) Load a Guzzle client. 3) Request from Telegram the file_path. Pay close attention to the different URL paths below.

// get file id
$id = $update['message']['photo'][0]['file_id'];
$file_id = "https://api.telegram.org/bot" .
 config('app.telegram_api_key') . "/getFile?file_id=" . $id;

// guzzle client
$guzzle_client = new GuzzleClient();
$request = $guzzle_client->get($file_id);
$response = json_decode($request->getBody(),true);

// get file path
$file_url = "https://api.telegram.org/file/bot" .
 config('app.telegram_api_key') . "/" . $response['result']['file_path'];


来源: stackexchange

问:
mongodump and mongorestore on PythonAnywhere
I am using PythonAnywhere to host my web application. Using Mongodb as my database. Now my task is to take backup periodically and restore specific version of mongodb whenever I want.

To do it on local(windows machine), it is pretty easy. Install Mongodb utilities and execute command

```<code>mongodump --mongodbConnectionString   //From location where this executable is stored
mongorestore --mongodbConnectionString
</code>```

Now my challenge is to do it from PythonAnywhere. Here how should I use these utilities?

I have Linux executables for mongodb from mongodb site, I extracted bin folder from it, it look like below

Now I moved this bin folder to PythonAnywhere and tried to execute mongodump command

```<code>~/../applications/mongodb-linux-x86_64-ubuntu1404-3.4.0/bin$ ./mongodump mongodbConnectionString
</code>```

it failed with below error

bash: ./mongodump: Permission denied

My question is how to do mongodump and mongorestore from PythonAnywhere? My final goal is to do periodic backup of mongodb database

答:
You need to setup correctly MongoDB binaries inside PythonAnywhere.

Normally, execution fails due wrong permissions.

```<code>Make sure:
- You have execution permissions (chmod u+x file)
- Binnaries have proper owner    (chown user file)
- Binnaries have proper group    (chgrp group file)
</code>```

Note: You need to be sudoer to grant such permissions

ContentLicense: CC BY-SA 4.0

Body:
I am using PythonAnywhere to host my web application. Using Mongodb as my database. Now my task is to take backup periodically and restore specific version of mongodb whenever I want.

To do it on local(windows machine), it is pretty easy. Install Mongodb utilities and execute command

mongodump --mongodbConnectionString   //From location where this executable is stored
mongorestore --mongodbConnectionString

Now my challenge is to do it from PythonAnywhere. Here how should I use these utilities?

I have Linux executables for mongodb from mongodb site, I extracted bin folder from it, it look like below

Now I moved this bin folder to PythonAnywhere and tried to execute mongodump command

~/../applications/mongodb-linux-x86_64-ubuntu1404-3.4.0/bin$ ./mongodump mongodbConnectionString

it failed with below error

bash: ./mongodump: Permission denied

My question is how to do mongodump and mongorestore from PythonAnywhere? My final goal is to do periodic backup of mongodb database

Body:
You need to setup correctly MongoDB binaries inside PythonAnywhere.

Normally, execution fails due wrong permissions.

Make sure:
- You have execution permissions (chmod u+x file)
- Binnaries have proper owner    (chown user file)
- Binnaries have proper group    (chgrp group file)

Note: You need to be sudoer to grant such permissions


问:
How to check if given parameter is cv::noArray()?
I want to implement a function that takes an image as optional parameter.
In case an image is passed, I want to use it - otherwise I want to calculate a default value. In the OpenCV library cv::noArray() is used for this purpose.
Something like this:

void doStuff(cv::InputArray candidatesMap = cv::noArray())
{
    // initialize candidatesMap if not given
    if(candidatesMap is cv::noArray())  // <-- Need help here
    {
        candidatesMap = createCandidatesMap();
    }

    // ... more code using candidatesMap
}
```

How can I programmatically check if the optional parameter is given or defaults to cv::noArray().

Since I didn't find any documentation, it might be helpful for others as well.

答:
You can do the following to check if an cv::InputArray was assigned to cv::noArray():

```<code>void doStuff(cv::InputOutputArray candidatesMap = cv::noArray())
{
    // initialize candidatesMap if not given
    if(candidatesMap.empty())
    {
        candidatesMap = createCandidatesMap();
    }

    // ... more code using candidatesMap
}
</code>```

Body:
I want to implement a function that takes an image as optional parameter.
In case an image is passed, I want to use it - otherwise I want to calculate a default value. In the OpenCV library cv::noArray() is used for this purpose.
Something like this:

void doStuff(cv::InputArray candidatesMap = cv::noArray())
{
    // initialize candidatesMap if not given
    if(candidatesMap is cv::noArray())  // <-- Need help here
    {
        candidatesMap = createCandidatesMap();
    }

    // ... more code using candidatesMap
}

How can I programmatically check if the optional parameter is given or defaults to cv::noArray().

Since I didn't find any documentation, it might be helpful for others as well.

Body:
You can do the following to check if an cv::InputArray was assigned to cv::noArray():

void doStuff(cv::InputOutputArray candidatesMap = cv::noArray())
{
    // initialize candidatesMap if not given
    if(candidatesMap.empty())
    {
        candidatesMap = createCandidatesMap();
    }

    // ... more code using candidatesMap
}


问:
Scrapy-splash no results at "Server listening on http://0.0.0.0:8050"
I'm on Windows 10 Home Edition using Docker tool box (my BIOS configuration doesn't allow me to install Linux)

When I run

```<code>docker run -it -p 8050:8050 --rm scrapinghub/splash
</code>```

I receive the log message Server listening on http://0.0.0.0:8050, as it should be in normal cases. But when I go to the address at my Chrome, the only thing that returns is ERR_ADDRESS_INVALID, not possible to access the page.

I have tried the following solutions to this problem:

Changing the SPLASH_URL on my settings.py according to my Docker IP adress;

Adding new ports to my docker run, such as 5023:5023 and 8051:8051.

I imagine that this is the kind of problem which I need to investigate its caused by myself. But I have tried everything that I could find on the Internet.

答:
You don't need to change any settings.

If you launch docker terminal, it shows the correct ip address at the very first, right after the whale drawing.

```<code>                       ##         .
              ## ## ##        ==
           ## ## ## ## ##    ===
       /"""""""""""""""""\___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
       \______ o           __/
         \    \         __/
          \____\_______/

docker is configured to use the default machine with IP 192.168.99.102
For help getting started, check out the docs at https://docs.docker.com
</code>```

So in my case the ip was 192.168.99.102.

If I visit 192.168.99.102:8050 on chrome, splash works.

Body:
I'm on Windows 10 Home Edition using Docker tool box (my BIOS configuration doesn't allow me to install Linux)

When I run

docker run -it -p 8050:8050 --rm scrapinghub/splash

I receive the log message Server listening on http://0.0.0.0:8050, as it should be in normal cases. But when I go to the address at my Chrome, the only thing that returns is ERR_ADDRESS_INVALID, not possible to access the page.

I have tried the following solutions to this problem:

Changing the SPLASH_URL on my settings.py according to my Docker IP adress;

Adding new ports to my docker run, such as 5023:5023 and 8051:8051.

I imagine that this is the kind of problem which I need to investigate its caused by myself. But I have tried everything that I could find on the Internet.

Body:
You don't need to change any settings.

If you launch docker terminal, it shows the correct ip address at the very first, right after the whale drawing.

                       ##         .
              ## ## ##        ==
           ## ## ## ## ##    ===
       /"""""""""""""""""\___/ ===
  ~~~ {~~ ~~~~ ~~~ ~~~~ ~~~ ~ /  ===- ~~~
       \______ o           __/
         \    \         __/
          \____\_______/

docker is configured to use the default machine with IP 192.168.99.102
For help getting started, check out the docs at https://docs.docker.com

So in my case the ip was 192.168.99.102.

If I visit 192.168.99.102:8050 on chrome, splash works.


问:
XmlWriter - disposable
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();
```

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

答:
It could potentially cause memory issues if there would be an exception in

```<code>// Do stuff
</code>```

In this scenario, the Close method would not be executed.
Using statement is a syntactic sugar around try-finally blocks. It calls Dispose in finally block even there was an exception

XmlWriter.Dispose calls Close method behind the scene

Title: XmlWriter - disposable

Body:
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

Body:
It could potentially cause memory issues if there would be an exception in

// Do stuff

In this scenario, the Close method would not be executed.
Using statement is a syntactic sugar around try-finally blocks. It calls Dispose in finally block even there was an exception

XmlWriter.Dispose calls Close method behind the scene


问:
Can't get contents of tkinter Entry widget in Python 3
I'm starting out in Python 3 and I am having problems getting a value back from a tkinter widget. When I run my code I get a 'name edtGetMe is not defined' error. Can anyone see where I am going wrong?

```<code>from tkinter import *

# Define the class that forms my window.
class Window(Frame):

def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master
    self.init_window()

# Init the class.
def init_window(self):
    # Place widgets on the window.
    self.pack(fill=BOTH, expand=1)

    # Quit button.
    btnCancel = Button (self, text="Cancel", command=self.cancel_out)
    btnCancel.place (x=10, y=120)

    # Action button.
    btnAction = Button (self, text="Set Text", command=self.action)
    btnAction.place (x=100, y=120)

    # The Editboxes.
    edtGetMe = Entry (self)
    edtSetMe = Entry (self)
    edtGetMe.place (y=10, x=10, width=380, height=100)
    edtSetMe.place (y=155, x=10, width=380, height=100)

def cancel_out(self):
    exit()

def action (self):
    # Get the entry from the GetMe box.
    self.usrText = edtGetMe.get()
    # Stuff it into the other box.
    edtSetMe.insert(self.usrText)

def main():
     root = Tk()

# Size of window.
root.geometry("400x300")

# Start Window Class.
app = Window(root)
root.mainloop()
</code>```

if name == "main":
    main()

答:
First I replaced edtGetMe by self.edtGetMe and same for edtSetMe, so these variables are accessible from all the class functions. Then I added "insert" in your line self.edtSetMe.insert("insert", self.usrText). You also had indentation problems.

Try this :

```<code>from tkinter import *

# Define the class that forms my window.
class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    # Init the class.
    def init_window(self):
        # Place widgets on the window.
        self.pack(fill=BOTH, expand=1)

        # Quit button.
        btnCancel = Button (self, text="Cancel", command=self.cancel_out)
        btnCancel.place (x=10, y=120)

        # Action button.
        btnAction = Button (self, text="Set Text", command=self.action)
        btnAction.place (x=100, y=120)

        # The Editboxes.
        self.edtGetMe = Entry (self)
        self.edtSetMe = Entry (self)
        self.edtGetMe.place (y=10, x=10, width=380, height=100)
        self.edtSetMe.place (y=155, x=10, width=380, height=100)

    def cancel_out(self):
        exit()

    def action (self):
        # Get the entry from the GetMe box.
        self.usrText = self.edtGetMe.get()
        # Stuff it into the other box.
        self.edtSetMe.insert("insert", self.usrText)

def main():
    root = Tk()

    # Size of window.
    root.geometry("400x300")

    # Start Window Class.
    app = Window(root)
    root.mainloop()

if __name__ == '__main__':
    main()
</code>```

Body:
I'm starting out in Python 3 and I am having problems getting a value back from a tkinter widget. When I run my code I get a 'name edtGetMe is not defined' error. Can anyone see where I am going wrong?

from tkinter import *

# Define the class that forms my window.
class Window(Frame):

def __init__(self, master=None):
    Frame.__init__(self, master)
    self.master = master
    self.init_window()

# Init the class.
def init_window(self):
    # Place widgets on the window.
    self.pack(fill=BOTH, expand=1)

    # Quit button.
    btnCancel = Button (self, text="Cancel", command=self.cancel_out)
    btnCancel.place (x=10, y=120)

    # Action button.
    btnAction = Button (self, text="Set Text", command=self.action)
    btnAction.place (x=100, y=120)

    # The Editboxes.
    edtGetMe = Entry (self)
    edtSetMe = Entry (self)
    edtGetMe.place (y=10, x=10, width=380, height=100)
    edtSetMe.place (y=155, x=10, width=380, height=100)

def cancel_out(self):
    exit()

def action (self):
    # Get the entry from the GetMe box.
    self.usrText = edtGetMe.get()
    # Stuff it into the other box.
    edtSetMe.insert(self.usrText)

def main():
     root = Tk()

# Size of window.
root.geometry("400x300")

# Start Window Class.
app = Window(root)
root.mainloop()

if name == "main":
    main()

Body:
First I replaced edtGetMe by self.edtGetMe and same for edtSetMe, so these variables are accessible from all the class functions. Then I added "insert" in your line self.edtSetMe.insert("insert", self.usrText). You also had indentation problems.

Try this :

from tkinter import *

# Define the class that forms my window.
class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    # Init the class.
    def init_window(self):
        # Place widgets on the window.
        self.pack(fill=BOTH, expand=1)

        # Quit button.
        btnCancel = Button (self, text="Cancel", command=self.cancel_out)
        btnCancel.place (x=10, y=120)

        # Action button.
        btnAction = Button (self, text="Set Text", command=self.action)
        btnAction.place (x=100, y=120)

        # The Editboxes.
        self.edtGetMe = Entry (self)
        self.edtSetMe = Entry (self)
        self.edtGetMe.place (y=10, x=10, width=380, height=100)
        self.edtSetMe.place (y=155, x=10, width=380, height=100)

    def cancel_out(self):
        exit()

    def action (self):
        # Get the entry from the GetMe box.
        self.usrText = self.edtGetMe.get()
        # Stuff it into the other box.
        self.edtSetMe.insert("insert", self.usrText)

def main():
    root = Tk()

    # Size of window.
    root.geometry("400x300")

    # Start Window Class.
    app = Window(root)
    root.mainloop()

if __name__ == '__main__':
    main()


问:
busybox dns resolve not works in some nodes in kuberenetes
I am deploy 3 busybox(1.28.3) in 3 nodes in kubernetes cluster(v1.15.2),each node contain a pod , this is my yaml:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: busybox-deployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: busybox
    spec:
      restartPolicy: Always
      containers:
      - name: busybox
        command:
        - sleep
        - "3600"
        image: busybox:1.28.3
</code>```

when I login to each pod and execute nslookup:

```<code>nslookup kubernetes.default.svc.cluster.local
</code>```

only one node response correct:

```<code>/ # nslookup kubernetes.default.svc.cluster.local
Server:    10.254.0.2
Address 1: 10.254.0.2 kube-dns.kube-system.svc.cluster.local

Name:      kubernetes.default.svc.cluster.local
Address 1: 10.254.0.1 kubernetes.default.svc.cluster.local
</code>```

the other 2 node response like this:

```<code>/ # nslookup kubernetes.default.svc.cluster.local
Server:    10.254.0.2
Address 1: 10.254.0.2

nslookup: can't resolve 'kubernetes.default.svc.cluster.local'
</code>```

why the CoreDNS(1.3.1) not works in some nodes?

答:
There could be multiple issues for this. Some common troubleshooting steps are:

Checking local DNS configuration

Checking core-dns pods and its logs

You can follow the DNS resolution debugging (https://kubernetes.io/docs/tasks/administer-cluster/dns-debugging-resolution/) page for detailed troubleshooting guide.

Body:
I am deploy 3 busybox(1.28.3) in 3 nodes in kubernetes cluster(v1.15.2),each node contain a pod , this is my yaml:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: busybox-deployment
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: busybox
    spec:
      restartPolicy: Always
      containers:
      - name: busybox
        command:
        - sleep
        - "3600"
        image: busybox:1.28.3

when I login to each pod and execute nslookup:

nslookup kubernetes.default.svc.cluster.local

only one node response correct:

/ # nslookup kubernetes.default.svc.cluster.local
Server:    10.254.0.2
Address 1: 10.254.0.2 kube-dns.kube-system.svc.cluster.local

Name:      kubernetes.default.svc.cluster.local
Address 1: 10.254.0.1 kubernetes.default.svc.cluster.local

the other 2 node response like this:

/ # nslookup kubernetes.default.svc.cluster.local
Server:    10.254.0.2
Address 1: 10.254.0.2

nslookup: can't resolve 'kubernetes.default.svc.cluster.local'

why the CoreDNS(1.3.1) not works in some nodes?


问:
How to remove the back button in the header react native
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

```<code>import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};
</code>```

How can I remove the button back?

答:
set  headerLeft: null in the navigation Options. and this will remove the back button from the head as I did in the last line of code.

```<code> import React from 'react';
    import { View } from 'react-native';

    export const TrucksScreen = () => {
        return (
            <View>
               ....
            </View>
        );
    });

    TrucksScreen.navigationOptions = {
        headerTitle: 'Trucks Screen',
        headerLeft: null,
    };
</code>```

I hope it will help. Ask for doubts

Body:
I want to remove the button back, but leave the header.

My component is as follows. I want to leave the title, and I don’t need the back button.

import React from 'react';
import { View } from 'react-native';

export const TrucksScreen = () => {
    return (
        <View>
           ....
        </View>
    );
});

TrucksScreen.navigationOptions = {
    headerTitle: 'Trucks Screen',
};

How can I remove the button back?

Body:
set  headerLeft: null in the navigation Options. and this will remove the back button from the head as I did in the last line of code.

 import React from 'react';
    import { View } from 'react-native';

    export const TrucksScreen = () => {
        return (
            <View>
               ....
            </View>
        );
    });

    TrucksScreen.navigationOptions = {
        headerTitle: 'Trucks Screen',
        headerLeft: null,
    };

I hope it will help. Ask for doubts


问:
making unequal array control
I have an array ,vehicle owners and tools are available, there is no stability in the array there are three car owners,vehicles they own show. in short; I have 3 car owners and I wanted to show on the page which of these three vehicles are ford, male, scania

code it gives me
enter image description here

i want to do
enter image description here

```<code><?php
$vehicles = array(

    array(
     "vehicleowner" =>("john"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

    array(
     "vehicleowner" =>("alex"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

     array(
     "vehicleowner" =>("Robert"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

 );

echo '<table border="1">
<thead>
<tr>
<td>vehicleowner</td>
<td>Ford</td>
<td>Scania</td>
<td>Man</td>
';

foreach($vehicles as $i => $value){
     // echo "```";
    // print_r($value);

    $ford = $value["vehicles"][$i]["id"]==1;

    if($ford){ $fordd = $value["vehicles"][$i]["brand"];}

    $scania = $value["vehicles"][$i]["id"]==2;
    if($scania){ $scaniaa = $value["vehicles"][$i]["brand"];}

    $man = $value["vehicles"][$i]["id"]==3;
    if($man){ $mann = $value["vehicles"][$i]["brand"];}

?>

 <?php echo $value["vehicleowner"]?>
 <?php echo isset($fordd) ? $fordd : '-';?>
 <?php echo isset($scaniaa) ? $scaniaa : '-';?>
 <?php echo isset($mann) ? $mann : '-';?>

<?php } ?>
```

答:
Add tags yourself</p>

```<code>    $store = [];
    $unique = [];
    foreach ($vehicles as $object) {
        foreach ($object['vehicles'] as $vehicle) {
            $unique[$vehicle['model']] = true;
            $store[$object['vehicleowner']][$vehicle['model']] = $vehicle['brand'];
        }
    }
    foreach ($store as $owner => $cars) {
        echo $owner;
        foreach ($unique as $column => $_) {
            echo $cars[$column] ?? '-';
        }
    }
</code>```

Title: making unequal array control

Body:
I have an array ,vehicle owners and tools are available, there is no stability in the array there are three car owners,vehicles they own show. in short; I have 3 car owners and I wanted to show on the page which of these three vehicles are ford, male, scania

code it gives me
enter image description here

i want to do
enter image description here

<?php
$vehicles = array(

    array(
     "vehicleowner" =>("john"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

    array(
     "vehicleowner" =>("alex"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

     array(
     "vehicleowner" =>("Robert"),
     "vehicles" =>array(
     array(
      "id" =>(1),
      "model" =>("ford"),
      "brand"   =>(1830),
     ),
     array(
      "model" =>("scania"),
      "id" =>(2),
      "brand"   =>("r400"),
     ),
     array(
      "id" =>(3),
      "model" =>("man"),
      "brand"   =>("tgx"),
     )
     ),
     ),

 );

echo '

vehicleowner
Ford
Scania
Man
';

foreach($vehicles as $i => $value){
     // echo "
";
    // print_r($value);

    $ford = $value["vehicles"][$i]["id"]==1;

    if($ford){ $fordd = $value["vehicles"][$i]["brand"];}

    $scania = $value["vehicles"][$i]["id"]==2;
    if($scania){ $scaniaa = $value["vehicles"][$i]["brand"];}

    $man = $value["vehicles"][$i]["id"]==3;
    if($man){ $mann = $value["vehicles"][$i]["brand"];}

?>

 <?php echo $value["vehicleowner"]?>
 <?php echo isset($fordd) ? $fordd : '-';?>
 <?php echo isset($scaniaa) ? $scaniaa : '-';?>
 <?php echo isset($mann) ? $mann : '-';?>

<?php } ?>

Body:
Add tags yourself

    $store = [];
    $unique = [];
    foreach ($vehicles as $object) {
        foreach ($object['vehicles'] as $vehicle) {
            $unique[$vehicle['model']] = true;
            $store[$object['vehicleowner']][$vehicle['model']] = $vehicle['brand'];
        }
    }
    foreach ($store as $owner => $cars) {
        echo $owner;
        foreach ($unique as $column => $_) {
            echo $cars[$column] ?? '-';
        }
    }


问:
Can't display a map api in phonegap
Greetings I tried to integrate http://mapas.sapo.pt/api in android with phonegap but all that I was getting was a Blank Space.

I am noob into phone gap and I would be very please if someone could give me a little explanation why does it happen ;)

thanks in advance

答:
I had a similar problem when rendering a Google Map in a phonegap app.  It turned out that the navigator.geolocation.getCurrentPosition was not working properly (phonegap 0.9.5, android 3).

To fix the problem I added Geolocation.usePhoneGap() in the deviceready callback:

```<code>function onDeviceReady() {
      Geolocation.usePhoneGap()
}

function onLoad() {
      document.addEventListener("deviceready", onDeviceReady, false);
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Can't display a map api in phonegap

Body:
I had a similar problem when rendering a Google Map in a phonegap app.  It turned out that the navigator.geolocation.getCurrentPosition was not working properly (phonegap 0.9.5, android 3).

To fix the problem I added Geolocation.usePhoneGap() in the deviceready callback:

function onDeviceReady() {
      Geolocation.usePhoneGap()
}

function onLoad() {
      document.addEventListener("deviceready", onDeviceReady, false);
}

ContentLicense: CC BY-SA 3.0


问:
How to send an amount directly from a stripe account to a debit card?
I want to send an amount directly to a debit card from a stripe account. Using /v1/transfers with destination: card_xxxxxxxx, gives No such destination. What am I doing wrong? Is there a different api method for doing this?

答:
You cannot, unfortunately.

To send a money FROM Stripe account to someone, you'll need to create a Connect account. And then you can send the money to that account via Stripe.

You cannot simply send money to a card from a Stripe account.

You have to create a Connected account from Stripe, and then you have to send money to that account. And then the user can Payout to his/her bank from his/her connected account.


问:
Java - How to do floor division?
I know that in Python you can do floor division like this:

```<code>5 // 2 #2
</code>```

The // is used for something totally different in Java. Is there any way to do floor division in Java?

答:
You can easily use Math.floorDiv() method.
For example:</p>

```<code>int a = 15, b = 2;
System.out.println(Math.floorDiv(a, b));
// Expected output: 7
</code>```

Title: Java - How to do floor division?

Body:
I know that in Python you can do floor division like this:

5 // 2 #2

The // is used for something totally different in Java. Is there any way to do floor division in Java?

Body:
You can easily use Math.floorDiv() method.
For example:

int a = 15, b = 2;
System.out.println(Math.floorDiv(a, b));
// Expected output: 7


问:
Cyclic dependency check using EF Core
I have the following requirement whilst using EF Core 3. I have Exercises with (Id = 1 Pushup), (Id = 2 Squat), (Id = 3 Weight Lift) and users. Once one exercise is completed, one ore more new exercise(s) are created. A multilevel hierarcy can be created with n level.
I have an issue though that can cause cyclic dependencies to the exercices.
e.g Pushup (1) is completed. Squat (2) is created. Squat (2) is completed then Weight Lift (3) is created. There is also a dependency on Weight Lift (3) that once it is completed it creates Pushup(1) with leads to cyclic dependency and I need to avoid that.
I gave a very simple example. In my project, dependencies can go up to level 50 and I dont know how to check for cyclic reference and avoid them.
Below is the code:</p>

```<code>public class Exercise
{
    public Exercise()
    {
        ExerciseDependencyExercises = new HashSet<ExercisesDependency>();
        ExerciseDependencyTargetExercises = new HashSet<ExercisesDependency>();
        UserExercises = new HashSet<UserExercise>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<ExercisesDependency> ExerciseDependencyExercises { get; set; }
    public virtual ICollection<ExercisesDependency> ExerciseDependencyTargetExercises { get; set; }

    public virtual ICollection<UserExercise> UserExercises { get; set; }
}

public class UserExercise
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public long UserId { get; set; }

    public long ExerciseId { get; set; }
}

public class ExercisesDependency
{
    public long ExerciseId { get; set; }
    public virtual Exercise Exercise { get; set; }

    public long TargetExerciseId { get; set; }
    public virtual Exercise TargetExercise { get; set; }
}
</code>```

答:
Easiest solution I can think of is to not have your requirements dictate primary keys values (which should only be used to uniquely identify a record).

I don't know/understand why you have this requirement. But I would suggest just continue numbering, and while creating the new records to calculate whether it should be an exercise of type 1, 2 or 3. e.g. 1=>1, 2=>2, 3=>3, 4=>1, 5=>2, 6=>3, 7=>1.

Then a simple: var type = ((id - 1) %3) + 1; returns that list of numbers.

Title: Cyclic dependency check using EF Core

Body:
I have the following requirement whilst using EF Core 3. I have Exercises with (Id = 1 Pushup), (Id = 2 Squat), (Id = 3 Weight Lift) and users. Once one exercise is completed, one ore more new exercise(s) are created. A multilevel hierarcy can be created with n level.
I have an issue though that can cause cyclic dependencies to the exercices.
e.g Pushup (1) is completed. Squat (2) is created. Squat (2) is completed then Weight Lift (3) is created. There is also a dependency on Weight Lift (3) that once it is completed it creates Pushup(1) with leads to cyclic dependency and I need to avoid that.
I gave a very simple example. In my project, dependencies can go up to level 50 and I dont know how to check for cyclic reference and avoid them.
Below is the code:

public class Exercise
{
    public Exercise()
    {
        ExerciseDependencyExercises = new HashSet<ExercisesDependency>();
        ExerciseDependencyTargetExercises = new HashSet<ExercisesDependency>();
        UserExercises = new HashSet<UserExercise>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    [Required]
    public string Name { get; set; }

    public virtual ICollection<ExercisesDependency> ExerciseDependencyExercises { get; set; }
    public virtual ICollection<ExercisesDependency> ExerciseDependencyTargetExercises { get; set; }

    public virtual ICollection<UserExercise> UserExercises { get; set; }
}

public class UserExercise
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public long UserId { get; set; }

    public long ExerciseId { get; set; }
}

public class ExercisesDependency
{
    public long ExerciseId { get; set; }
    public virtual Exercise Exercise { get; set; }

    public long TargetExerciseId { get; set; }
    public virtual Exercise TargetExercise { get; set; }
}


问:
Input clicked, add class Angular 8
I have an array which produces a set of questions. It displays them as radio buttons.

Here is the HTML

```<code>          <div *ngSwitchCase="'radio'">
            <ul>
              <li
                *ngFor="let option of question.options"
                class="col-12 col-sm-6 p-0 purchase-type"
              >
                <input
                  class="form-control"
                  id="{{ option.id }}"
                  formControlName="{{ question.name }}"
                  value="{{ option.value }}"
                  type="radio"
                  (click)="clickEvent()"
                  [ngClass]="status ? 'success' : 'danger'"
                />
                <label for="{{ option.id }}" class="btn btn-choice {{ option.class }}">
                  <span class="hidden-xs">{{ option.id }} </span
                  ><span class="hidden-xs"> (</span> {{ option.label
                  }}<span class="hidden-xs">)</span></label
                >
              </li>
            </ul>
          </div>
</code>```

Boolean inside the .ts

```<code>  status: boolean = false;
  clickEvent() {
    this.status = !this.status;
  }
</code>```

As this is in an array, i'm struggling to toggle a class between each. At the moment, when I select any radio button, all radio button elements get the same class applied.

How would I only apply this to the radio button clicked?

Pretty new to Angular. Appreciate any help or suggestions.

Thanks in advance

答:
Maybe this should help you

```<code><input
    class="form-control"
    id="{{ option.id }}"
    formControlName="{{ question.name }}"
    value="{{ option.value }}"
    type="radio"
    (click)="clickEvent($event)"  // add $event here
    [ngClass]="status ? 'success' : 'danger'"
/>
</code>```

And in your component inject render. Make sure to check for your condition base on status variable

```<code>  constructor(private renderer: Renderer2) { }

  clickEvent(event: any) {
    this.status ?
    this.render.addClass(event.target,"active") :
    this.render.removeClass(event.target,"active"); // set your class here
  }
</code>```

Title: Input clicked, add class Angular 8

Body:
I have an array which produces a set of questions. It displays them as radio buttons.

Here is the HTML

                <input
                  class="form-control"
                  id="{{ option.id }}"
                  formControlName="{{ question.name }}"
                  value="{{ option.value }}"
                  type="radio"
                  (click)="clickEvent()"
                  [ngClass]="status ? 'success' : 'danger'"
                />

                  {{ option.id }}  ( {{ option.label
                  }})

Boolean inside the .ts

  status: boolean = false;
  clickEvent() {
    this.status = !this.status;
  }

As this is in an array, i'm struggling to toggle a class between each. At the moment, when I select any radio button, all radio button elements get the same class applied.

How would I only apply this to the radio button clicked?

Pretty new to Angular. Appreciate any help or suggestions.

Thanks in advance

Body:
Maybe this should help you

<input
    class="form-control"
    id="{{ option.id }}"
    formControlName="{{ question.name }}"
    value="{{ option.value }}"
    type="radio"
    (click)="clickEvent($event)"  // add $event here
    [ngClass]="status ? 'success' : 'danger'"
/>

And in your component inject render. Make sure to check for your condition base on status variable

  constructor(private renderer: Renderer2) { }

  clickEvent(event: any) {
    this.status ?
    this.render.addClass(event.target,"active") :
    this.render.removeClass(event.target,"active"); // set your class here
  }


问:
How to access to a Websocket from an @EventPattern
I have an events.gateway.ts which is controlling all the client and server events, but when I do
this.server.emit('client.events', data) from @EventPattern('gw-event:playback.state')I have the emit null. Please see below the code:

import { Logger, Inject, Controller } from '@nestjs/common';
import { SubscribeMessage,
  WebSocketGateway,
  MessageBody,
  WebSocketServer,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect} from '@nestjs/websockets';
import { Socket, Server  } from 'socket.io';
import { ClientProxy, EventPattern} from '@nestjs/microservices';

@Controller('gateway')
@WebSocketGateway()
export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect{

  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('EventsGateway');

  constructor(@Inject('EVENTS_SERVICE') private readonly client: ClientProxy) {
  }

  afterInit(server: Server) {
    this.server = server;
    this.logger.log('Init', EventsGateway.name);
  }// OnGatewayInit

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`, EventsGateway.name);
  }// OnGatewayDisconnect

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`, EventsGateway.name);
    this.server.emit('client.events', 'Welcome client:' + client.id);
  }// OnGatewayConnection

  @SubscribeMessage('client.events')
  handleEvent(@MessageBody() data: string): any {
    return { event: 'client.events', 'data': data + '__from Server'};
  }

  @EventPattern('gw-event:playback.state')
  async handlePlaybackState(data: Record<string, unknown>) {
    this.server.emit('client.events', data); //<= Error emit is null
  }

}

```

Any suggestion? Thanks.

答: Solved applying the suggested approach at How to access websocket from controller or another component/services? by Raold

Body:
I have an events.gateway.ts which is controlling all the client and server events, but when I do
this.server.emit('client.events', data) from @EventPattern('gw-event:playback.state')I have the emit null. Please see below the code:

import { Logger, Inject, Controller } from '@nestjs/common';
import { SubscribeMessage,
  WebSocketGateway,
  MessageBody,
  WebSocketServer,
  OnGatewayInit,
  OnGatewayConnection,
  OnGatewayDisconnect} from '@nestjs/websockets';
import { Socket, Server  } from 'socket.io';
import { ClientProxy, EventPattern} from '@nestjs/microservices';

@Controller('gateway')
@WebSocketGateway()
export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect{

  @WebSocketServer() server: Server;
  private logger: Logger = new Logger('EventsGateway');

  constructor(@Inject('EVENTS_SERVICE') private readonly client: ClientProxy) {
  }

  afterInit(server: Server) {
    this.server = server;
    this.logger.log('Init', EventsGateway.name);
  }// OnGatewayInit

  handleDisconnect(client: Socket) {
    this.logger.log(`Client disconnected: ${client.id}`, EventsGateway.name);
  }// OnGatewayDisconnect

  handleConnection(client: Socket, ...args: any[]) {
    this.logger.log(`Client connected: ${client.id}`, EventsGateway.name);
    this.server.emit('client.events', 'Welcome client:' + client.id);
  }// OnGatewayConnection

  @SubscribeMessage('client.events')
  handleEvent(@MessageBody() data: string): any {
    return { event: 'client.events', 'data': data + '__from Server'};
  }

  @EventPattern('gw-event:playback.state')
  async handlePlaybackState(data: Record<string, unknown>) {
    this.server.emit('client.events', data); //<= Error emit is null
  }

}

Any suggestion? Thanks.


问:
what's the largest number float type can hold?
I'm new to programming and have recently come up with this simple question .
float type has 32 bits in which 8 bits are for the whole number part (the mantissa).
so my question is can float type hold numbers bigger than 255.9999 ?

and I would also appreciate if someone told me why this code is behaving unexpectedly. Is it a related issue?

```<code>int main(){
float a=123456789.1;
printf("%lf",a);
return 0;
}
</code>```

for which the output is :

```<code>123456792.000000
</code>```

答:
<float.h> -- Numeric limits of floating point types has your answers, specifically...

FLT_MAX

DBL_MAX

LDBL_MAX

maximum finite value of float, double and long double respectively

...and...

FLT_DIG

DBL_DIG

LDBL_DIG

number of decimal digits that are guaranteed to be preserved in text -> float/double/long double -> text roundtrip without change due to rounding or overflow

That last part is meant to say that a float value longer (i.e. more significant digits) than FLT_DIG is no longer guaranteed to be precisely representable.

Body:
I'm new to programming and have recently come up with this simple question .
float type has 32 bits in which 8 bits are for the whole number part (the mantissa).
so my question is can float type hold numbers bigger than 255.9999 ?

and I would also appreciate if someone told me why this code is behaving unexpectedly. Is it a related issue?

int main(){
float a=123456789.1;
printf("%lf",a);
return 0;
}

for which the output is :

123456792.000000


问:
Nodejs - Calling a method from other file properly
I'm new to this domain and want to fix this error, I have two classes, 'Ticket.js' where I put my routes and 'support.js' where my websockets methods are declared,
I just want to use the method delared in 2nd file in 1st file,
here's the strucutre of code of both files :

```<code>class SupportTicketRouter  {
.
.
.
    sendMessagesSocket = (req, res, next) => {
        const SUPPORT_SOCKET = require('app/routes/socket/support');
        const MESSAGES       = req.api.support.messages;

        SUPPORT_SOCKET.sendModifiedTicket(MESSAGES);

        next();
    }
}

</code>```

in the other file :

```<code>const SUPPORT_SOCKET = (MQTT_CLIENT, REDIS_CLIENT, IO_SERVER, IO_CLIENT) => {

   // EntryPoints

   // Exit points
   SUPPORT_SOCKET.sendModifiedTicket = (data) => {
       IO_SERVER.in(data[0]._id).emit('OneTicketReload', data);
       Logger.info('%s%s', 'Ticket sent to room ', data[0]._id);
   };

</code>```

so basically I just want to call sendModifiedTicket from other file.

Thanks in advance

答:
You should export your function from a file where it is defined:

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

then include it wherever you want to use it:

```<code>const supportSocket = require('./path-to-js-file').
class SupportTicketRouter  {...
</code>```

this also may help:
https://evdokimovm.github.io/javascript/nodejs/2016/06/13/NodeJS-How-to-Use-Functions-from-Another-File-using-module-exports.html

Body:
I'm new to this domain and want to fix this error, I have two classes, 'Ticket.js' where I put my routes and 'support.js' where my websockets methods are declared,
I just want to use the method delared in 2nd file in 1st file,
here's the strucutre of code of both files :

class SupportTicketRouter  {
.
.
.
    sendMessagesSocket = (req, res, next) => {
        const SUPPORT_SOCKET = require('app/routes/socket/support');
        const MESSAGES       = req.api.support.messages;

        SUPPORT_SOCKET.sendModifiedTicket(MESSAGES);

        next();
    }
}

in the other file :

const SUPPORT_SOCKET = (MQTT_CLIENT, REDIS_CLIENT, IO_SERVER, IO_CLIENT) => {

   // EntryPoints

   // Exit points
   SUPPORT_SOCKET.sendModifiedTicket = (data) => {
       IO_SERVER.in(data[0]._id).emit('OneTicketReload', data);
       Logger.info('%s%s', 'Ticket sent to room ', data[0]._id);
   };

so basically I just want to call sendModifiedTicket from other file.

Thanks in advance

Body:
You should export your function from a file where it is defined:

module.exports = SUPPORT_SOCKET

then include it wherever you want to use it:

const supportSocket = require('./path-to-js-file').
class SupportTicketRouter  {...

this also may help:
https://evdokimovm.github.io/javascript/nodejs/2016/06/13/NodeJS-How-to-Use-Functions-from-Another-File-using-module-exports.html


问:
Facebook Graph API - get a photos album ID
I'm writing an application that uploads a photo to facebook. I'm not supplying an album ID so an album is created on behalf of my app.

My question is: how do I get the album ID the photo was uploaded to?

When I GET the the photo information the album isn't present in the JSON which was my hope.

答:
If I'm understanding you correctly, you have the photo ID but need the album ID. You could try using the photo FQL table with the following query:

SELECT aid, pid FROM photo WHERE pid = '<your photo id>'
```


问:
How to use sys.argv?
Hello I am trying to write a function which will take different argument and
would be used in another function in another script. My idea is to be able to precise a parameter directly from the terminal and the script will somewhat go the function with the precise parameter and Apply the correct line.

So I run my script like this and put f which is my parameter but I do not have any answer , below the full script.

```<code>C:\Users\Etu\ocuments>python test2.py f
</code>```

first script

```<code>
import sys

first_arg = sys.argv[1]

texte = "je MaNgE"

def get_command(texte, first_arg):
    if first_arg =="f":
        texte = texte.lower()
        return texte
    elif first_arg=="t":
        return texte.split()
    elif first_arg =="r":

    return texte

    else:
        raise Exception("Wrongfile feature type entered. Possible values: 't','f', 'r")

</code>```

second script

```<code>from test import *

texte = "je MaNgE"

def choose (texte):
    texte=get_command(texte, first_arg)

    print(texte)

</code>```

The idea is to modify directly the parameter from the shell without going Inside the script all the time.

答:
What you are trying to do can be easily achieved with the help of python command line arguments :>

Consider the code that will help clear your understanding of command line arguments:

```<code>"""
Filename: test.py
"""

import sys

def main():
    # always check to avoid IndexError
    if len(sys.argv) > 1:
        # sys.argv[0] always returns the current python file name

        print("Number of arguments: ", len(sys.argv))
        print("Filename: ", sys.argv[0])
        print("Hello", sys.argv[1])

main()
</code>```

Note:
sys.argv returns

the list of command line arguments passed to a Python script. argv[0]
  is the script name (it is operating system dependent whether this is a
  full pathname or not). If the command was executed using the -c
  command line option to the interpreter, argv[0] is set to the string
  '-c'. If no script name was passed to the Python interpreter, argv[0]
  is the empty string.

Now when you run the above script using:
python test.py Lana

The output will be

Number of arguments: 2
 Filename: test.py
 Hello, Lana

Hope this will help you:)

Title: How to use sys.argv?

Body:
Hello I am trying to write a function which will take different argument and
would be used in another function in another script. My idea is to be able to precise a parameter directly from the terminal and the script will somewhat go the function with the precise parameter and Apply the correct line.

So I run my script like this and put f which is my parameter but I do not have any answer , below the full script.

C:\Users\Etu\ocuments>python test2.py f

first script

import sys

first_arg = sys.argv[1]

texte = "je MaNgE"

def get_command(texte, first_arg):
    if first_arg =="f":
        texte = texte.lower()
        return texte
    elif first_arg=="t":
        return texte.split()
    elif first_arg =="r":

    return texte

    else:
        raise Exception("Wrongfile feature type entered. Possible values: 't','f', 'r")

second script

from test import *

texte = "je MaNgE"

def choose (texte):
    texte=get_command(texte, first_arg)

    print(texte)

The idea is to modify directly the parameter from the shell without going Inside the script all the time.

Body:
What you are trying to do can be easily achieved with the help of python command line arguments :>

Consider the code that will help clear your understanding of command line arguments:

"""
Filename: test.py
"""

import sys

def main():
    # always check to avoid IndexError
    if len(sys.argv) > 1:
        # sys.argv[0] always returns the current python file name

        print("Number of arguments: ", len(sys.argv))
        print("Filename: ", sys.argv[0])
        print("Hello", sys.argv[1])

main()

Note:
sys.argv returns

the list of command line arguments passed to a Python script. argv[0]
  is the script name (it is operating system dependent whether this is a
  full pathname or not). If the command was executed using the -c
  command line option to the interpreter, argv[0] is set to the string
  '-c'. If no script name was passed to the Python interpreter, argv[0]
  is the empty string.

Now when you run the above script using:
python test.py Lana

The output will be

Number of arguments: 2
 Filename: test.py
 Hello, Lana

Hope this will help you:)


问:
Can't install r-base on Ubuntu 19.10; unmet dependencies r-recommended
In general, I am new in working with Ubuntu (19.10;eoan) and currently trying to install r-base. r-base-dev is installed.
When I do so, I get the following message:

```<code>Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 r-base : Depends: r-recommended (= 3.6.2-1xenial) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.
</code>```

I have used the following Threads to try to fix my problem - without any succes.

Installing r-base; Depenency: r-recommended missing?

Issues in installing r-base-dev

For this one I stopped at the section: "Disable/Remove/Purge PPA:". Because I was not able to understand the process.

https://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies-after-adding-a-ppa

I will appreciate any solution or advice to solve my problem.

答:
Without more information about what you actually tried (and the order) it is difficult to try and pinpoint why it doesn't work, but I recently installed this on 19.10 myself. I used the following.

```<code># Get the key from the keyserver.
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

# Add the repository to your sources.list. Make sure that it does not already exist
# and that it is not a typo in there. Making a backup of the file before running the
# next line is useful.
echo "deb https://cloud.r-project.org/bin/linux/ubuntu eoan-cran35/" | sudo tee -a /etc/apt/sources.list

# Install base, dev and other dependencies.
sudo apt install r-base r-base-dev r-cran-curl r-cran-openssl r-cran-xml2 libssl-dev libxml2-dev libcurl4-openssl-dev
</code>```

It worked without any problem for me. It is very important that you add the correct repository to your sources.list. Judging by the error message you are using a repository referring to Ubuntu Xenial and not Ubuntu Eoan.

Body:
In general, I am new in working with Ubuntu (19.10;eoan) and currently trying to install r-base. r-base-dev is installed.
When I do so, I get the following message:

Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 r-base : Depends: r-recommended (= 3.6.2-1xenial) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I have used the following Threads to try to fix my problem - without any succes.

Installing r-base; Depenency: r-recommended missing?

Issues in installing r-base-dev

For this one I stopped at the section: "Disable/Remove/Purge PPA:". Because I was not able to understand the process.

https://askubuntu.com/questions/140246/how-do-i-resolve-unmet-dependencies-after-adding-a-ppa

I will appreciate any solution or advice to solve my problem.

Body:
Without more information about what you actually tried (and the order) it is difficult to try and pinpoint why it doesn't work, but I recently installed this on 19.10 myself. I used the following.

# Get the key from the keyserver.
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

# Add the repository to your sources.list. Make sure that it does not already exist
# and that it is not a typo in there. Making a backup of the file before running the
# next line is useful.
echo "deb https://cloud.r-project.org/bin/linux/ubuntu eoan-cran35/" | sudo tee -a /etc/apt/sources.list

# Install base, dev and other dependencies.
sudo apt install r-base r-base-dev r-cran-curl r-cran-openssl r-cran-xml2 libssl-dev libxml2-dev libcurl4-openssl-dev

It worked without any problem for me. It is very important that you add the correct repository to your sources.list. Judging by the error message you are using a repository referring to Ubuntu Xenial and not Ubuntu Eoan.


问:
How to copy rage of rows in google sheets according to the range mentioned in sheet1
In sheet1 there are 2 columns.

in first column there is number 6 and in second column there is a number 20.

This means, all the data in Sheet2 from row 6 to 20 has to get copied in Sheet3.

So in the future, if we change number in sheet1, the data should flow according to those numbers

Could somebody help me to achieve this.

答:
Apps Script features the method copyTo, the documentation contains a sample:

```<code>// The code below copies the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));
</code>```

You can adapt this sample to your question but performing two modifications:

Instead of copying the range to the range in the same sheet - defined two different sheets and copy it from the one to the other

When defining the range with the method getRange(row, column, numRows, numColumns) instead of assigning to the parameters static numbers, retrieve the values dynamically from your spreadsheet.

Sample:

```<code>function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet1 = spreadsheet.getSheetByName("Sheet1");
  var sheet2 = spreadsheet.getSheetByName("Sheet2");
  var sheet3 = spreadsheet.getSheetByName("Sheet3");
  //adapt the ranges to the real cells contianing the row information
  var startRow = sheet1.getRange("A1").getValue();
  var endRow = sheet1.getRange("B1").getValue();
  var rowNumber = endRow-startRow+1;
  var rangeToCopy = sheet2.getRange(startRow, 1, rowNumber, sheet2.getLastRow());
  rangeToCopy.copyTo(sheet3.getRange(startRow, 1));
}

</code>```

Body:
Apps Script features the method copyTo, the documentation contains a sample:

// The code below copies the first 5 columns over to the 6th column.
var sheet = SpreadsheetApp.getActiveSheet();
var rangeToCopy = sheet.getRange(1, 1, sheet.getMaxRows(), 5);
rangeToCopy.copyTo(sheet.getRange(1, 6));

You can adapt this sample to your question but performing two modifications:

Instead of copying the range to the range in the same sheet - defined two different sheets and copy it from the one to the other

When defining the range with the method getRange(row, column, numRows, numColumns) instead of assigning to the parameters static numbers, retrieve the values dynamically from your spreadsheet.

Sample:

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet1 = spreadsheet.getSheetByName("Sheet1");
  var sheet2 = spreadsheet.getSheetByName("Sheet2");
  var sheet3 = spreadsheet.getSheetByName("Sheet3");
  //adapt the ranges to the real cells contianing the row information
  var startRow = sheet1.getRange("A1").getValue();
  var endRow = sheet1.getRange("B1").getValue();
  var rowNumber = endRow-startRow+1;
  var rangeToCopy = sheet2.getRange(startRow, 1, rowNumber, sheet2.getLastRow());
  rangeToCopy.copyTo(sheet3.getRange(startRow, 1));
}


问:
XmlWriter - disposable
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();
```

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

答:
according to c# docs
The using statement ensures that Dispose is called even if an exception occurs within the using block. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

```<code>        {
            var font1 = new Font("Arial", 10.0f);
            try
            {
                byte charset = font1.GdiCharSet;
            }
            finally
            {
                if (font1 != null)
                    ((IDisposable)font1).Dispose();
            }
        }
</code>```

and close function is do the same thing
This method calls Dispose, specifying true to release all resources. You do not have to specifically call the Close method. Instead, ensure that every Stream object is properly disposed. You can declare Stream objects within a using block (or Using block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the Dispose method.

Title: XmlWriter - disposable

Body:
I am having trouble understanding the way XmlWriter works in C#. Take the following code as if it hypothetically was used somewhere.

StringBuilder builder = new StringBuilder();
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = new UTF8Encoding(false);
settings.ConformanceLevel = ConformanceLevel.Document;
settings.Indent = true;

XmlWriter writer = XmlWriter.Create(builder, settings);

// Do stuff

writer.Close();

Since XmlWriter is not used within an using statement, could this potentially result in an OutOfMemoryException due to it not being properly disposed?

Body:
according to c# docs
The using statement ensures that Dispose is called even if an exception occurs within the using block. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

        {
            var font1 = new Font("Arial", 10.0f);
            try
            {
                byte charset = font1.GdiCharSet;
            }
            finally
            {
                if (font1 != null)
                    ((IDisposable)font1).Dispose();
            }
        }

and close function is do the same thing
This method calls Dispose, specifying true to release all resources. You do not have to specifically call the Close method. Instead, ensure that every Stream object is properly disposed. You can declare Stream objects within a using block (or Using block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the Dispose method.


问:
Why is $_POST[''] not working with <form>
This is a Rock Paper Scissors game and I am just starting on it, but it will not display the $_POST['keuzen'].

So I don't get why this is not working. Tried many things but can't find a good solution.

```<code><?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>RockPaperScissor</title>
    </head>
    <body>
        <form action="RockPaperScissor.php" method="post">
            <input type="image" src="steen.jpg" alt="steen" name="keuzen" value="steen" title="Steen">
            <input type="image" src="papier.jpg" alt="papier" name="keuzen" value="papier" title="Papier">
            <input type="image" src="schaar.jpg" alt="schaar" name="keuzen" value="schaar" title="Schaar">
        </form>
        <?php
            if (isset($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '<br>';
                echo 'De computer koos ' . $computer . '<br';

                if ($keuzen == $computer) {
                    echo 'Resultaat : Draw ';
                }
            }
        ?>
    </body>
</html>
</code>```

答:
Change names of inputs like this: name="keuzen[steen]" and remove value attributes.

Read POSTed value like this: $keuzen = array_keys($_POST['keuzen'])[0];

You can also verify that the POSTed value is not empty.

Body:
This is a Rock Paper Scissors game and I am just starting on it, but it will not display the $_POST['keuzen'].

So I don't get why this is not working. Tried many things but can't find a good solution.

<?php session_start(); ?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>RockPaperScissor</title>

        <form action="RockPaperScissor.php" method="post">
            <input type="image" src="steen.jpg" alt="steen" name="keuzen" value="steen" title="Steen">
            <input type="image" src="papier.jpg" alt="papier" name="keuzen" value="papier" title="Papier">
            <input type="image" src="schaar.jpg" alt="schaar" name="keuzen" value="schaar" title="Schaar">
        </form>
        <?php
            if (isset($_POST['keuzen'])) {
                $keuzen = $_POST['keuzen'];
                $kiezenuit = array("steen", "papier", "schaar");
                $random = rand(0, 2);
                $computer = $kiezenuit[$random];

                echo 'jij koos ' . $keuzen . '
';
                echo 'De computer koos ' . $computer . '


问:
How to scroll option-box with TR?
I have few TR in table, When i click on TR then open a option-box now i want to move this box as per TR position while scrolling, how can i do this?

Its working fine on click but after window scroll this is not moving as per TR

My Code:-

$('tr').click(function(){
  var editContentmarginTop = $(this).offset().top;
  $('.option-box').show();
   $('.option-box').css({
            'top': editContentmarginTop
        });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-div{height:2000px;}
.option-box{ display:none;}
.option-box{ background:#ccc; position:fixed; top:0px; left:0px; height:50px; width:50px;}

.table{ margin-left:50px;}</code>```

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

        Firstname
        Lastname
        Email

        John
        Doe
        john@example.com

        Mary
        Moe
        mary@example.com

        July
        Dooley
        july@example.com

Add New

  ```

答:
Change position:fixed to position:absolute in .option-box class

check the updated snippet

$('tr').click(function() {
  var editContentmarginTop = $(this).offset().top;
  $('.option-box').show();
  $('.option-box').css({
    'top': editContentmarginTop
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-div {
  height: 2000px;
}

.option-box {
  display: none;
}

.option-box {
  background: #ccc;
  position: absolute;
  top: 0px;
  left: 0px;
  height: 50px;
  width: 50px;
}

.table {
  margin-left: 50px;
}</code>```

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

          Firstname
          Lastname
          Email

          John
          Doe
          john@example.com

          Mary
          Moe
          mary@example.com

          July
          Dooley
          july@example.com

Add New
```

Title: How to scroll option-box with TR?

Body:
I have few TR in table, When i click on TR then open a option-box now i want to move this box as per TR position while scrolling, how can i do this?

Its working fine on click but after window scroll this is not moving as per TR

My Code:-

$('tr').click(function(){
  var editContentmarginTop = $(this).offset().top;
  $('.option-box').show();
   $('.option-box').css({
            'top': editContentmarginTop
        });
});

.main-div{height:2000px;}
.option-box{ display:none;}
.option-box{ background:#ccc; position:fixed; top:0px; left:0px; height:50px; width:50px;}

.table{ margin-left:50px;}

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

        Firstname
        Lastname
        Email

        John
        Doe
        john@example.com

        Mary
        Moe
        mary@example.com

        July
        Dooley
        july@example.com

Add New

Body:
Change position:fixed to position:absolute in .option-box class

check the updated snippet

$('tr').click(function() {
  var editContentmarginTop = $(this).offset().top;
  $('.option-box').show();
  $('.option-box').css({
    'top': editContentmarginTop
  });
});

.main-div {
  height: 2000px;
}

.option-box {
  display: none;
}

.option-box {
  background: #ccc;
  position: absolute;
  top: 0px;
  left: 0px;
  height: 50px;
  width: 50px;
}

.table {
  margin-left: 50px;
}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <div class="main-div">

    <table class="table">
      <thead>
        <tr>
          <th>Firstname</th>
          <th>Lastname</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>John</td>
          <td>Doe</td>
          <td>john@example.com</td>
        </tr>
        <tr>
          <td>Mary</td>
          <td>Moe</td>
          <td>mary@example.com</td>
        </tr>
        <tr>
          <td>July</td>
          <td>Dooley</td>
          <td>july@example.com</td>
        </tr>
      </tbody>
    </table>

  </div>
  <div class="option-box">Add New</div>


问:
How to find pair of numbers in a list which makes a sum as given number
A few days back I encountered a problem which says that there is a list of numbers and a value called total. Now we need to write a program that gives a list of tuples (only 2 elements in the tuple) and sum of each tuple should be equal to the value of total. Example: Following is the input:

```<code>input = [1,2,3,4,6,7,8,9]
total = 10
</code>```

Following is the output:

```<code>output = [(1,9), (2,8), (3,7), (4,6)]
</code>```

答:
You can find the difference and check if the value is a part of the remaining list as follows - </p>

```<code>>>> [(index,i) for index,i in enumerate(input)] #how enumerate works
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 6), (5, 7), (6, 8), (7, 9)]
>>> [(i,total-i) for index,i in enumerate(input) if (total-i) in input[index+1:]]
[(1, 9), (2, 8), (3, 7), (4, 6)]
</code>```

Body:
A few days back I encountered a problem which says that there is a list of numbers and a value called total. Now we need to write a program that gives a list of tuples (only 2 elements in the tuple) and sum of each tuple should be equal to the value of total. Example: Following is the input:

input = [1,2,3,4,6,7,8,9]
total = 10

Following is the output:

output = [(1,9), (2,8), (3,7), (4,6)]

Body:
You can find the difference and check if the value is a part of the remaining list as follows -

>>> [(index,i) for index,i in enumerate(input)] #how enumerate works
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 6), (5, 7), (6, 8), (7, 9)]
>>> [(i,total-i) for index,i in enumerate(input) if (total-i) in input[index+1:]]
[(1, 9), (2, 8), (3, 7), (4, 6)]


问:
Suppress warning messages using mysql from within Terminal, but password written in bash script
When I tried running the following command on MySQL from within Terminal:

```<code>mysql -u $user -p$password -e "statement"
</code>```

The execution works as expected, but it always issues a warning:

Warning: Using a password on the command line interface can be insecure.

However, I have to conduct the statement above using an environment variable ($password) that stores my password, because I want to run the command iteratively in bash script from within Terminal, and I definitely don't like the idea of waiting a prompt showing up and forcing me to input my password 50 or 100 times in a single script. So here's my question:

Is it feasible to suppress the warning? The command works properly as I stated, but the window becomes pretty messy when I loop over and run the command 50 or 100 times.

Should I obey the warning message and do NOT write my password in my script? If that's the case, then do I have to type in my password every time the prompt forces me to do so?

Running man mysql doesn't help, saying only

--show-warnings

  Cause warnings to be shown after each statement if there are any. This option applies to interactive and batch mode.

and mentions nothing about how to turn off the functionality, if I'm not missing something.

I'm on OS X 10.9.1 Mavericks and use MySQL 5.6 from homebrew.

答:
Define the helper:

```<code>remove-warning () {
    grep -v 'mysql: [Warning] Using a password on the command line interface can be insecure.'
}
</code>```

Use it:

```<code>mysql -u $user -p$password -e "statement" 2>&1 | remove-warning
</code>```

Tachaan! Your code is clean and nice to read

(tested with bash)

Body:
When I tried running the following command on MySQL from within Terminal:

mysql -u $user -p$password -e "statement"

The execution works as expected, but it always issues a warning:

Warning: Using a password on the command line interface can be insecure.

However, I have to conduct the statement above using an environment variable ($password) that stores my password, because I want to run the command iteratively in bash script from within Terminal, and I definitely don't like the idea of waiting a prompt showing up and forcing me to input my password 50 or 100 times in a single script. So here's my question:

Is it feasible to suppress the warning? The command works properly as I stated, but the window becomes pretty messy when I loop over and run the command 50 or 100 times.

Should I obey the warning message and do NOT write my password in my script? If that's the case, then do I have to type in my password every time the prompt forces me to do so?

Running man mysql doesn't help, saying only

--show-warnings

  Cause warnings to be shown after each statement if there are any. This option applies to interactive and batch mode.

and mentions nothing about how to turn off the functionality, if I'm not missing something.

I'm on OS X 10.9.1 Mavericks and use MySQL 5.6 from homebrew.

Body:
Define the helper:

remove-warning () {
    grep -v 'mysql: [Warning] Using a password on the command line interface can be insecure.'
}

Use it:

mysql -u $user -p$password -e "statement" 2>&1 | remove-warning

Tachaan! Your code is clean and nice to read

(tested with bash)


问:
Why can't I find the image added to my Android Solution sample?
I'm still fairly new to Visual Studio/Xamarin. I'm trying to get an image into my Android sample.

I'm using Visual Studio for Mac community 8.4.5 (build 19) on macOS Mojava 10.14.6 and the following Packages:

BruTile 2.1.2

Mapsui 1.4.8

OsmSharp 6.2.0

Xamarin.Android.Support.Core.Utils 28.0.0.3

Xamarin.Android.Support.CustomTabs 28.0.0.3

Xamarin.Android.Support.Design 28.0.0.3

Xamarin.Essentials 1.3.1

In my Solution I added an image to the following locations:

Assets > Images > sample.png

Resources > drawables > sample.png

Then I'm trying to find it using the following code:

```<code>    String target = "sample.png"
    Assembly resourceAssembly = null;
    String resourceName = null;
    Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
    foreach (Assembly assembly in assemblies)
    {
        Console.WriteLine("Assembly: '" + assembly.GetName());
        try
        {
            String[] fileNames = assembly.GetManifestResourceNames();
            foreach (var fileName in fileNames)
            {
                Console.WriteLine("File Name: '" + fileName + "'");
                if (fileName.ToUpper().EndsWith(target.ToUpper()))
                {
                    resourceAssembly = assembly;
                    resourceName = fileName;
                }
            }
        }
        catch (NotSupportedException e)
        {
            Console.WriteLine(
                "Not Supported for Assembly: '" + assembly.GetName() + "'  (" + e.GetType() + ")"
            );
        }
    }
    if (resourceName != null) {
        Console.WriteLine("Resource file name [{0}] found as [{1}]", fileName, resourceName);
    }
</code>```

The console log shows quite the number of assemblies and filenames, but never prints out the last line and thus does not find the sample.png file.

Why doesn't this code find the file? Did I add the file to the wrong location in my Solution? Or do I need to do something additionally?

(My current preference is to keep using the Assembly approach to find the file.)

答:
I'm not 100% sure what you are trying to do mate but if you are needing the image to show you can use the xaml.

```<code><Image Source="sample.jpg" />
</code>```

As long as the file name is all lower case, no special characters/numbers & is in - Resources > drawables it should show.

Hope this helps.

Body:
I'm still fairly new to Visual Studio/Xamarin. I'm trying to get an image into my Android sample.

I'm using Visual Studio for Mac community 8.4.5 (build 19) on macOS Mojava 10.14.6 and the following Packages:

BruTile 2.1.2

Mapsui 1.4.8

OsmSharp 6.2.0

Xamarin.Android.Support.Core.Utils 28.0.0.3

Xamarin.Android.Support.CustomTabs 28.0.0.3

Xamarin.Android.Support.Design 28.0.0.3

Xamarin.Essentials 1.3.1

In my Solution I added an image to the following locations:

Assets > Images > sample.png

Resources > drawables > sample.png

Then I'm trying to find it using the following code:

    String target = "sample.png"
    Assembly resourceAssembly = null;
    String resourceName = null;
    Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
    foreach (Assembly assembly in assemblies)
    {
        Console.WriteLine("Assembly: '" + assembly.GetName());
        try
        {
            String[] fileNames = assembly.GetManifestResourceNames();
            foreach (var fileName in fileNames)
            {
                Console.WriteLine("File Name: '" + fileName + "'");
                if (fileName.ToUpper().EndsWith(target.ToUpper()))
                {
                    resourceAssembly = assembly;
                    resourceName = fileName;
                }
            }
        }
        catch (NotSupportedException e)
        {
            Console.WriteLine(
                "Not Supported for Assembly: '" + assembly.GetName() + "'  (" + e.GetType() + ")"
            );
        }
    }
    if (resourceName != null) {
        Console.WriteLine("Resource file name [{0}] found as [{1}]", fileName, resourceName);
    }

The console log shows quite the number of assemblies and filenames, but never prints out the last line and thus does not find the sample.png file.

Why doesn't this code find the file? Did I add the file to the wrong location in my Solution? Or do I need to do something additionally?

(My current preference is to keep using the Assembly approach to find the file.)

Body:
I'm not 100% sure what you are trying to do mate but if you are needing the image to show you can use the xaml.

<Image Source="sample.jpg" />

As long as the file name is all lower case, no special characters/numbers & is in - Resources > drawables it should show.

Hope this helps.


问:
Where does 'Hello world' come from?
'hello, world' is usually the first example for any programming language. I've always wondered where this sentence came from and where was it first used.

I've once been told that it was the first sentence ever to be displayed on a computer screen, but I've not been able to find any reference to this.

So my question is:

Where does the practice to use 'hello, world' as the first example for computer languages originate from?

Where was it first used?

Update

Although the answers are quite interesting, I should have noted that I had read the Wikipedia article. It does answer the question about the first use in literature, but does not answer when 'hello world' was first used.

So I think that it is safe to conclude that it was not the first sentence ever to be displayed on a computer screen and that there is no record about when it was first used?

答:
The first C program in the book "The C Programming Language" was to print "hello world!" on the screen.

Since then it is used as the first program to introduce the basic details of a programming language.

OwnerDisplayName: Jacco

Title: Where does 'Hello world' come from?

LastEditorDisplayName: Jacco

OwnerDisplayName: Xolve


问:
Real time chat implementation for SharePoint
I have a client interested in a real time chat application for a SharePoint intranet portal to enable online interview style chat sessions.

Has anyone got reccomendations for a product on the Microsoft Stack that does this? Something that is integrated into SharePoint would be prefferable, but any ASP.NET product would suffice.

The solution would need to be pretty robust as we would expect over 1000 users during a given session.

答: There is a third party product for SharePoint 2010 called GameTime that supports real-time web based chat integrated into SharePoint.</p>


问:
How to use Two Toggle buttons on same page having same function with different css?
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

```<code>onclick="themeToggle()" id="theme-switcher"
</code>```

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

```<code> var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

</code>```

This is the code for Two Toggle buttons

```<code>
    <label class="switcher">
    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">
    <div>
    <i class="fas fa-sun"></i>
    <i class="fas fa-arrow-left arrow"></i>
    <i class="fas fa-moon"></i>
    </div>
    </label>

</code>```

```<code>
 <label class="switch" style="padding: 23px 0;">
<input type="checkbox" onclick="themeToggle()" id="theme-switcher">
<div>
    <span></span>
</div>

</code>```

Kindly help me in solving the issue with the code as well.

Thanks for the help.

答:
You can't use the same ID for two or more HTML elements. Also, once you want to use this functionality in multiple elements, I strongly recommend you to not use onclick inline. Instead, you can get all switchers from your page and add a listener to them:

Get all switchers in your page

```<code>const switchers = document.querySelectorAll('.switcher');
</code>```

Apply the click event listener on them

```<code>switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});
</code>```

Finally, you must add the switcher class to all elements

```<code><input type="checkbox" id="theme-switcher-1" class="switcher">
<input type="checkbox" id="theme-switcher-2" class="switcher">
<input type="checkbox" id="theme-switcher-3" class="switcher">
</code>```

Using this approach, you can use this method all over your website or application and it's also easier to maintain.

Update: you should adjust the themeToggle() method like so:

```<code>function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is on');
  } else {
    localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is off');
  }
}
</code>```

Example snippet

Obs.: You should adjust it into your code. I had to comment localStorage because it didn't work here.

const switchers = document.querySelectorAll('.switcher');
console.log(switchers);
switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});
function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    //localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode');
    console.log('Dark mode is ON on ' + tSwitcher.id);
  } else {
    //localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode');
    console.log('Dark mode is OFF on ' + tSwitcher.id);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="theme-switcher-1" class="switcher"><br />
<input type="checkbox" id="theme-switcher-2" class="switcher"><br />
<input type="checkbox" id="theme-switcher-3" class="switcher"></code>```

Body:
I have been trying to hard to add 2 Toggle Buttons having different styles (css) on Menu Bar and footer page. They are to be used for night and dark mode.

However when I use

onclick="themeToggle()" id="theme-switcher"

for both of the buttons, only one of them works.

This is my Toggle Buttons Test Page.

This is the js which is being used :

 var tSwitcher = document.getElementById('theme-switcher');
let element = document.body;

 let onpageLoad = localStorage.getItem("theme") || "";
 if(onpageLoad != null && onpageLoad  == 'dark-mode'){
      tSwitcher.checked = true;
 }
 element.classList.add(onpageLoad);

function themeToggle(){
      if(tSwitcher.checked){
          localStorage.setItem('theme', 'dark-mode');
            element.classList.add('dark-mode');
        } else {
          localStorage.setItem('theme', '');
            element.classList.remove('dark-mode');
        }
    }

This is the code for Two Toggle buttons

    <input type="checkbox" onclick="themeToggle()" id="theme-switcher">

<input type="checkbox" onclick="themeToggle()" id="theme-switcher">

Kindly help me in solving the issue with the code as well.

Thanks for the help.

Body:
You can't use the same ID for two or more HTML elements. Also, once you want to use this functionality in multiple elements, I strongly recommend you to not use onclick inline. Instead, you can get all switchers from your page and add a listener to them:

Get all switchers in your page

const switchers = document.querySelectorAll('.switcher');

Apply the click event listener on them

switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});

Finally, you must add the switcher class to all elements

<input type="checkbox" id="theme-switcher-1" class="switcher">
<input type="checkbox" id="theme-switcher-2" class="switcher">
<input type="checkbox" id="theme-switcher-3" class="switcher">

Using this approach, you can use this method all over your website or application and it's also easier to maintain.

Update: you should adjust the themeToggle() method like so:

function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is on');
  } else {
    localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode'); // changed element to tSwitcher
    console.log('Dark mode is off');
  }
}

Example snippet

Obs.: You should adjust it into your code. I had to comment localStorage because it didn't work here.

const switchers = document.querySelectorAll('.switcher');
console.log(switchers);
switchers.forEach((element) => {
    element.addEventListener('click', (event) => {
        themeToggle(event);
    });
});
function themeToggle(event){
  var tSwitcher = event.target;
  if(tSwitcher.checked){
    //localStorage.setItem('theme', 'dark-mode');
    tSwitcher.classList.add('dark-mode');
    console.log('Dark mode is ON on ' + tSwitcher.id);
  } else {
    //localStorage.setItem('theme', '');
    tSwitcher.classList.remove('dark-mode');
    console.log('Dark mode is OFF on ' + tSwitcher.id);
  }
}

<input type="checkbox" id="theme-switcher-1" class="switcher"><br />
<input type="checkbox" id="theme-switcher-2" class="switcher"><br />
<input type="checkbox" id="theme-switcher-3" class="switcher">


问:
I can't use JQuery : Cannot find name '$'
I have a problem using jQuery in my project (with Angular and boosted which is a fork of bootstrap). The error is below:

ERROR in folder/containing/my/component.ts: error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i @types/jquery.

I have installed @types/jquery and jquery, and I have added the script in angular.json file:

```<code>"dependencies": {
   // ...
  "boosted": "^4.3.1",
  "bootstrap": "^4.4.1",
},
"devDependencies": {
  // ...
  "typescript": "~3.1.6"
}

"scripts":[
  // ...
  "node_modules/@types/jquery/dist/jquery.slim.d.ts",
  "node_modules/jquery/dist/jquery.js"
]
</code>```

答:
Try to install jquery.

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

And then import jquery as $. like below

```<code>import * as $ from 'jquery';
</code>```

Body:
I have a problem using jQuery in my project (with Angular and boosted which is a fork of bootstrap). The error is below:

ERROR in folder/containing/my/component.ts: error TS2581: Cannot find name '$'. Do you need to install type definitions for jQuery? Try npm i @types/jquery.

I have installed @types/jquery and jquery, and I have added the script in angular.json file:

"dependencies": {
   // ...
  "boosted": "^4.3.1",
  "bootstrap": "^4.4.1",
},
"devDependencies": {
  // ...
  "typescript": "~3.1.6"
}

"scripts":[
  // ...
  "node_modules/@types/jquery/dist/jquery.slim.d.ts",
  "node_modules/jquery/dist/jquery.js"
]

Body:
Try to install jquery.

npm install jquery

And then import jquery as $. like below

import * as $ from 'jquery';


问:
Call to get resource in PHP 7.3.4 intermittently returns nullptr
I am investigating a crash which is occurring when our C++ program calls ts_resource(0) in PHP 7.3.4.

The code was written by a developer who has since left the company and I have very little knowledge of PHP. The original code was written for PHP 5.3 and has worked perfectly for years, but when PHP was upgraded to 7.3.4 our program started to crash intermittently.
I discovered the crash is caused by a call to tsrm_get_ls_cache() which is returning a nullptr. I have added a check for the nullptr and so stopped the crash but I would like to know why the call to get the resource returns nullptr and what I can do to prevent it. I assume the problem is memory related as it is intermittent.

I am not sure what code to show as the calls to PHP in our code are extensive. The PHP is compiled with ZTS enabled so it multithreaded.

In the initialisation stage the thread safe manager is started with:

```<code>tsrm_startup(128, 1, 0, NULL);
ts_resource(0);
ZEND_TSRMLS_CACHE_UPDATE();
</code>```

and our Execute function which is called each time PHP code is called starts with:

```<code>ts_resource(0);
ZEND_TSRMLS_CACHE_UPDATE();

if (tsrm_get_ls_cache() == nullptr)
    return false;

ExecuteContext context;
context.pOutputStream = pOutputStream;

SG(server_context) = (void*)&context;
</code>```

Next some initialisation of the context class is carried out before calling
php_request_startup(TSRMLS_C);

When the call to get resource fails, the actual failure occurs because malloc fails:
The call to ts_resource(0) at the beginning of the Execute function calls into the following PHP function to allocate new resource:

```<code>allocate_new_resource(&thread_resources->next, thread_id);
</code>```

and this call to malloc fails the allocation

static void allocate_new_resource(tsrm_tls_entry **thread_resources_ptr, THREAD_T thread_id)
{
    (*thread_resources_ptr) = (tsrm_tls_entry *) malloc(sizeof(tsrm_tls_entry));
...

If anyone can suggest any reasons why the resource allocation might be failing I would be very grateful.

答:
Have you tried to use TSRMLS_CACHE_UPDATE instead of ZEND_TSRMLS_CACHE_UPDATE (notice ZEND_ prefix )?

So, as I have understood TSRMLS_CACHE_DEFINE should be set once per compilation unit.
TSRMLS_CACHE_EXTERN should be included in other files and TSRMLS_CACHE_UPDATE should be called when appropriate.

Body:
I am investigating a crash which is occurring when our C++ program calls ts_resource(0) in PHP 7.3.4.

The code was written by a developer who has since left the company and I have very little knowledge of PHP. The original code was written for PHP 5.3 and has worked perfectly for years, but when PHP was upgraded to 7.3.4 our program started to crash intermittently.
I discovered the crash is caused by a call to tsrm_get_ls_cache() which is returning a nullptr. I have added a check for the nullptr and so stopped the crash but I would like to know why the call to get the resource returns nullptr and what I can do to prevent it. I assume the problem is memory related as it is intermittent.

I am not sure what code to show as the calls to PHP in our code are extensive. The PHP is compiled with ZTS enabled so it multithreaded.

In the initialisation stage the thread safe manager is started with:

tsrm_startup(128, 1, 0, NULL);
ts_resource(0);
ZEND_TSRMLS_CACHE_UPDATE();

and our Execute function which is called each time PHP code is called starts with:

ts_resource(0);
ZEND_TSRMLS_CACHE_UPDATE();

if (tsrm_get_ls_cache() == nullptr)
    return false;

ExecuteContext context;
context.pOutputStream = pOutputStream;

SG(server_context) = (void*)&context;

Next some initialisation of the context class is carried out before calling
php_request_startup(TSRMLS_C);

When the call to get resource fails, the actual failure occurs because malloc fails:
The call to ts_resource(0) at the beginning of the Execute function calls into the following PHP function to allocate new resource:

allocate_new_resource(&thread_resources->next, thread_id);

and this call to malloc fails the allocation

static void allocate_new_resource(tsrm_tls_entry **thread_resources_ptr, THREAD_T thread_id)
{
    (*thread_resources_ptr) = (tsrm_tls_entry *) malloc(sizeof(tsrm_tls_entry));
...

If anyone can suggest any reasons why the resource allocation might be failing I would be very grateful.


问:
Visual Studio Git commands - Path, file name length error
Whenever I try to pull or sync from git in visual studio, I get the error

The specified path, file name, or both are too long. The fully
  qualified file name must be less than 260 characters, and the
  directory name must be less than 248 characters.

The local path where my repository is located : C:\Users\user3008\Documents\Projects\clientconsultancyservice\ClientConsultancyInterface

Both the .vs and .gitignore files are saved in the above directory. I never faced this issue in VS 2015 and have recently upgraded to VS2019.

What I have tried so far:

Updating Visual Studio

Updating GitHub Extension

Relevant Details:

Visual Studio 2019 Professional v16.4.5

GitHub Extension for Visual Studio v2.10.8.8132

答:
The local path where my repository is located:

```<code>C:\Users\user3008\Documents\Projects\clientconsultancyservice\ClientConsultancyInterface
</code>```

And then add the longest path & file name in to repo to the starting point: if any go over 260 characters you;ll get that error., Blame MS-DOS 2.0 for the 260 character limitation.

Options: either use WSL, or (easier) put you repo somewhere more sensible on you machine where the location of the repo is a rather shorter name.

(I use C:\Projects and have changed VS's default project location to match.)

Body:
The local path where my repository is located:

C:\Users\user3008\Documents\Projects\clientconsultancyservice\ClientConsultancyInterface

And then add the longest path & file name in to repo to the starting point: if any go over 260 characters you;ll get that error., Blame MS-DOS 2.0 for the 260 character limitation.

Options: either use WSL, or (easier) put you repo somewhere more sensible on you machine where the location of the repo is a rather shorter name.

(I use C:\Projects and have changed VS's default project location to match.)


问:
Add new column in a dataset based on dataset
```<code>library(quantmod)
getSymbols("LLOY.L",
           from = datefrom,
           to = dateto,
           auto.assign = TRUE)
LLOY.L$MovingAverages <- 0
e <- movavg(LLOY.L$LLOY.L.Close, 5, type = c("e"))
LLOY.L[, 7] <- e

</code>```

Is there a way to create a new column of this dataset that means if column 4 is greater than column 7 it prints "Buy Stock" in each row, else print "Sell Stock", I have tried using loops with no success

答:
You can easily do it using ifelse function in R.

```<code>df$new_var <- ifelse(df[, 4] > df[, 7], "Buy Stock", "Sell Stock")

</code>```

where df is your dataset, in which you want create new column.

I hopes, it helps you.

Body:
library(quantmod)
getSymbols("LLOY.L",
           from = datefrom,
           to = dateto,
           auto.assign = TRUE)
LLOY.L$MovingAverages <- 0
e <- movavg(LLOY.L$LLOY.L.Close, 5, type = c("e"))
LLOY.L[, 7] <- e

Is there a way to create a new column of this dataset that means if column 4 is greater than column 7 it prints "Buy Stock" in each row, else print "Sell Stock", I have tried using loops with no success

Body:
You can easily do it using ifelse function in R.

df$new_var <- ifelse(df[, 4] > df[, 7], "Buy Stock", "Sell Stock")

where df is your dataset, in which you want create new column.

I hopes, it helps you.