问:
Splitting a string using a next line regex followed by a digit (JAVA)
I have the following string which I need to split on space, commas, and next line character.
Sample string: "./homework2 3,phone3,desc3,brand4\n4,phone4,desc4,brand4\n5,phone5,desc5,brand5"

I am using split function as: .split("[,\\s+\\n+]"); but I am unable to get the required out put. The program keeps reading brand4\n4 as one substring.

Help would be appreciated.

答:
Try this code :

```<code>           String str = "./homework2 3,phone3,desc3,brand4\\n4,phone4,desc4,brand4\\n5,phone5,desc5,brand5";
           String[] arrOfStr = str.split("[\\s\\n,]+");

           for (String a : arrOfStr)
                System.out.println(a);

}
}
</code>```

Out put :

```<code>./homework2
3
phone3
desc3
brand4\n4
phone4
desc4
brand4\n5
phone5
desc5
brand5
</code>```

EDIT :

I found this function in the site : Link Here

```<code>           for (int i = 0 ; i < arrOfStr.length ; i++) { //YOUR LOOP !!!
               splitString(arrOfStr[i]);
           }
}

static void splitString(String str)
{
    StringBuffer alpha = new StringBuffer(),
    num = new StringBuffer(), special = new StringBuffer();

    for (int i=0; i<str.length(); i++)
    {
        if (Character.isDigit(str.charAt(i)))
            num.append(str.charAt(i));
        else if(Character.isAlphabetic(str.charAt(i)))
            alpha.append(str.charAt(i));
        else
            special.append(str.charAt(i));
    }
    System.out.println(alpha);
    System.out.println(num);
}
}
</code>```

Combine the two functions and you get:

```<code>homework
2

3
phone
3
desc
3
brandn
44
phone
4
desc
4
brandn
45
phone
5
desc
5
brand
5
</code>```

You can store the values in another array, or whatever you choose.

Body:
Try this code :

           String str = "./homework2 3,phone3,desc3,brand4\\n4,phone4,desc4,brand4\\n5,phone5,desc5,brand5";
           String[] arrOfStr = str.split("[\\s\\n,]+");

           for (String a : arrOfStr)
                System.out.println(a);

}
}

Out put :

./homework2
3
phone3
desc3
brand4\n4
phone4
desc4
brand4\n5
phone5
desc5
brand5

EDIT :

I found this function in the site : Link Here

           for (int i = 0 ; i < arrOfStr.length ; i++) { //YOUR LOOP !!!
               splitString(arrOfStr[i]);
           }
}

static void splitString(String str)
{
    StringBuffer alpha = new StringBuffer(),
    num = new StringBuffer(), special = new StringBuffer();

    for (int i=0; i<str.length(); i++)
    {
        if (Character.isDigit(str.charAt(i)))
            num.append(str.charAt(i));
        else if(Character.isAlphabetic(str.charAt(i)))
            alpha.append(str.charAt(i));
        else
            special.append(str.charAt(i));
    }
    System.out.println(alpha);
    System.out.println(num);
}
}

Combine the two functions and you get:

homework
2

3
phone
3
desc
3
brandn
44
phone
4
desc
4
brandn
45
phone
5
desc
5
brand
5

You can store the values in another array, or whatever you choose.


来源: stackexchange

问:
Python : Memory consumption accumulating in a while loop
A confession first - a noob programmer here doing occasional scripting. I've been trying to figure the memory consumption for this simple piece of code but unable to figure this out. I have tried searching in the answered questions, but couldn't figure it out. I'm fetching some json data using REST API, and the piece of code below ends up consuming a lot of RAM. I checked the Windows task manager and the memory consumption increases incrementally with each iteration of the loop. I'm overwriting the same variable for each API call, so I think the previous response variable should be overwritten.

```<code>while Flag == True:
        urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
        response = json.loads(obj1.get_request(urlpart))
        lstDataList = lstDataList + response['data']
        Flag = response['pageInfo']['hasMoreData']
        varScrollId = response['pageInfo']['scrollId']
        count += 1
        print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
        print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
    return lstDataList
</code>```

I tried to profile memory usage using memory_profiler...here's what it shows

```<code>    92  119.348 MiB    0.000 MiB       count = 0
    93  806.938 MiB    0.000 MiB       while Flag == True:
    94  806.938 MiB    0.000 MiB           urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
    95  807.559 MiB   30.293 MiB           response = json.loads(obj1.get_request(urlpart))
    96  806.859 MiB    0.000 MiB           print('Size of response within the loop  is {}'.format(sys.getsizeof(response)))
    97  806.938 MiB    1.070 MiB           lstDataList = lstDataList + response['data']
    98  806.938 MiB    0.000 MiB           Flag = response['pageInfo']['hasMoreData']
    99  806.938 MiB    0.000 MiB           varScrollId = response['pageInfo']['scrollId']
   100  806.938 MiB    0.000 MiB           count += 1
   101  806.938 MiB    0.000 MiB           print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
   102  806.938 MiB    0.000 MiB           print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
   103                                 return lstDataList

</code>```

obj1 is an object of Cisco's rest_api_lib class. Link to code here

In fact the program ends up consuming ~1.6 Gigs of RAM. The data I'm fetching has roughly 570K records. The API limits the records to 10K at a time, so the loop runs ~56 times. Line 95 of the code consumes ~30M of RAM as per the memory_profiler output. It's as if each iteration consumes 30M ending u with ~1.6G, so in the same ballpark. Unable to figure out why the memory consumption keeps on accumulating for the loop.
Thanks.

答:
it's as if each iteration consumes 30M

That is exactly what is happening. You need to free memory that you dont need for example once you have extracted data from response. You can delete it like so

del response
```

more on del

more on garbage collection

ContentLicense: CC BY-SA 4.0

Body:
A confession first - a noob programmer here doing occasional scripting. I've been trying to figure the memory consumption for this simple piece of code but unable to figure this out. I have tried searching in the answered questions, but couldn't figure it out. I'm fetching some json data using REST API, and the piece of code below ends up consuming a lot of RAM. I checked the Windows task manager and the memory consumption increases incrementally with each iteration of the loop. I'm overwriting the same variable for each API call, so I think the previous response variable should be overwritten.

while Flag == True:
        urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
        response = json.loads(obj1.get_request(urlpart))
        lstDataList = lstDataList + response['data']
        Flag = response['pageInfo']['hasMoreData']
        varScrollId = response['pageInfo']['scrollId']
        count += 1
        print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
        print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
    return lstDataList

I tried to profile memory usage using memory_profiler...here's what it shows

    92  119.348 MiB    0.000 MiB       count = 0
    93  806.938 MiB    0.000 MiB       while Flag == True:
    94  806.938 MiB    0.000 MiB           urlpart= 'data/device/statistics/approutestatsstatistics?scrollId='+varScrollId
    95  807.559 MiB   30.293 MiB           response = json.loads(obj1.get_request(urlpart))
    96  806.859 MiB    0.000 MiB           print('Size of response within the loop  is {}'.format(sys.getsizeof(response)))
    97  806.938 MiB    1.070 MiB           lstDataList = lstDataList + response['data']
    98  806.938 MiB    0.000 MiB           Flag = response['pageInfo']['hasMoreData']
    99  806.938 MiB    0.000 MiB           varScrollId = response['pageInfo']['scrollId']
   100  806.938 MiB    0.000 MiB           count += 1
   101  806.938 MiB    0.000 MiB           print("Fetched {} records out of {}".format(len(lstDataList), recordCount))
   102  806.938 MiB    0.000 MiB           print('Size of List is now {}'.format(str(sys.getsizeof(lstDataList))))
   103                                 return lstDataList

obj1 is an object of Cisco's rest_api_lib class. Link to code here

In fact the program ends up consuming ~1.6 Gigs of RAM. The data I'm fetching has roughly 570K records. The API limits the records to 10K at a time, so the loop runs ~56 times. Line 95 of the code consumes ~30M of RAM as per the memory_profiler output. It's as if each iteration consumes 30M ending u with ~1.6G, so in the same ballpark. Unable to figure out why the memory consumption keeps on accumulating for the loop.
Thanks.

Body:
it's as if each iteration consumes 30M

That is exactly what is happening. You need to free memory that you dont need for example once you have extracted data from response. You can delete it like so

del response

more on del

more on garbage collection


问:
Loop a short python script that parses data from a json file
I hope the title makes sense, english is not my first language and somewhat i have no idea if i wrote it right..
Basically i have a python scripts that i use for phishing sites, to spam them with random data.
I have the .py file and a .json file.

app.py:

```<code>import requests
import os
import random
import string
import json

chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (os.urandom(1024))

url = 'site/file.php'

names = json.loads(open('names.json').read())

for name in names:
    name_extra = ''.join(random.choice(string.digits))

    username = name.lower() + name_extra + '@yahoo.com'
    password = ''.join(random.choice(chars) for i in range(12))

    requests.post(url, allow_redirects=False, data={
        'login': username,
        'pass': password
    })

    print ('sending username %s and password %s' % (username, password))
</code>```

The json has a couple random names:

```<code>[
"Liam",
"Noah",
"William"
]
</code>```

In my names.json i have about 40 random names, everytime i start the program it will go through all the 40 names and then it will just close..
Is there any way for me to loop infinitely through the names? And make the program run 24/7?

答:
If you truly want it to run forever (or until you end it), you can use

```<code>while(True):
    print("This will go forever")
</code>```

It's unclear which part you want to run forever, but in your case this would look something like

```<code>while(True):
    for name in names:
        name_extra = ''.join(random.choice(string.digits))

        username = name.lower() + name_extra + '@yahoo.com'
        password = ''.join(random.choice(chars) for i in range(12))

        requests.post(url, allow_redirects=False, data={
            'login': username,
            'pass': password
        })

        print ('sending username %s and password %s' % (username, password))
</code>```

Body:
I hope the title makes sense, english is not my first language and somewhat i have no idea if i wrote it right..
Basically i have a python scripts that i use for phishing sites, to spam them with random data.
I have the .py file and a .json file.

app.py:

import requests
import os
import random
import string
import json

chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random.seed = (os.urandom(1024))

url = 'site/file.php'

names = json.loads(open('names.json').read())

for name in names:
    name_extra = ''.join(random.choice(string.digits))

    username = name.lower() + name_extra + '@yahoo.com'
    password = ''.join(random.choice(chars) for i in range(12))

    requests.post(url, allow_redirects=False, data={
        'login': username,
        'pass': password
    })

    print ('sending username %s and password %s' % (username, password))

The json has a couple random names:

[
"Liam",
"Noah",
"William"
]

In my names.json i have about 40 random names, everytime i start the program it will go through all the 40 names and then it will just close..
Is there any way for me to loop infinitely through the names? And make the program run 24/7?

Body:
If you truly want it to run forever (or until you end it), you can use

while(True):
    print("This will go forever")

It's unclear which part you want to run forever, but in your case this would look something like

while(True):
    for name in names:
        name_extra = ''.join(random.choice(string.digits))

        username = name.lower() + name_extra + '@yahoo.com'
        password = ''.join(random.choice(chars) for i in range(12))

        requests.post(url, allow_redirects=False, data={
            'login': username,
            'pass': password
        })

        print ('sending username %s and password %s' % (username, password))


问:
Changing Request Path in .Net Core 3.1
Prior to 3.0, I could change the path of a request (without any form of browser redirection) by just accessing the HttpRequest property of the HttpContext and then changed the value of the Path.

As an example, to display a page for a user who needed to change his/her password (irrespective of the page the user intended to visit), I extended the HttpContext

```<code>public static void ChangeDefaultPassword(this HttpContext context)
=> context.Request.Path = "/Account/ChangePassword";
</code>```

This piece of code takes the user to the action method ChangePassword in the AccountController without executing the action method the user intends to visit.

Then enters dotnet core 3.1.

In 3.1, the extension method changes the path. However, it never executes the action method. It ignores the updated path.

I am aware this is due to the changes in the routing.The endpoint can now be accessed with the extension method HttpContext.GetEndpoint(). There is also an extension method HttpContext.SetEndpoint which seems to be the right way to set a new endpoint. However, there is no sample of how to accomplish this.

The Question

How do I change the request path, without executing the original path?

What I Have Tried

I tried changing the path. It seems routing in dotnet core 3.1 ignores the value of the HttpRequest path value.

I tried redirecting with context.Response.Redirect("/Account/ChangePassword");. This worked but it first executed the original action method requested by the user. This behavior defeated the purpose.

I tried using the extension method HttpContext.SetEndpoint, but there was no example available to work with.

答:
In my case, I am manually selecting the matching endpoint in a DynamicRouteValueTransformer. I have a mostly working solution but have to switch to other priorities. Perhaps someone else can create a more elegant solution using built in Action executors.</p>

```<code>RequestDelegate requestDelegate = async (HttpContext x) =>
{//manually handle controller activation, method invocation, and result processing
    var actionContext = new ActionContext(x, new RouteData(values), new ControllerActionDescriptor() { ControllerTypeInfo = controllerType.GetTypeInfo() });
    var activator = x.RequestServices.GetService(typeof(IControllerActivator)) as ServiceBasedControllerActivator;
    var controller = activator.Create(new ControllerContext(actionContext));
    var arguments = methodInfo.GetParameters().Select(p =>
    {
        object r;
        if (requestData.TryGetValue(p.Name, out object value)) r = value;
        else if (p.ParameterType.IsValueType) r = Activator.CreateInstance(p.ParameterType);
        else r = null;
        return r;
    });
    var actionResultTask = methodInfo.Invoke(controller, arguments.ToArray());
    var actionTask = actionResultTask as Task<IActionResult>;
    if (actionTask != null)
    {
        var actionResult = await actionTask;
        await actionResult.ExecuteResultAsync(actionContext);//errors here. actionContext is incomplete
    }
};

var endpoint = new Endpoint(requestDelegate, EndpointMetadataCollection.Empty, methodInfo.Name);
httpContext.SetEndpoint(endpoint);
</code>```

Title: Changing Request Path in .Net Core 3.1

Body:
Prior to 3.0, I could change the path of a request (without any form of browser redirection) by just accessing the HttpRequest property of the HttpContext and then changed the value of the Path.

As an example, to display a page for a user who needed to change his/her password (irrespective of the page the user intended to visit), I extended the HttpContext

public static void ChangeDefaultPassword(this HttpContext context)
=> context.Request.Path = "/Account/ChangePassword";

This piece of code takes the user to the action method ChangePassword in the AccountController without executing the action method the user intends to visit.

Then enters dotnet core 3.1.

In 3.1, the extension method changes the path. However, it never executes the action method. It ignores the updated path.

I am aware this is due to the changes in the routing.The endpoint can now be accessed with the extension method HttpContext.GetEndpoint(). There is also an extension method HttpContext.SetEndpoint which seems to be the right way to set a new endpoint. However, there is no sample of how to accomplish this.

The Question

How do I change the request path, without executing the original path?

What I Have Tried

I tried changing the path. It seems routing in dotnet core 3.1 ignores the value of the HttpRequest path value.

I tried redirecting with context.Response.Redirect("/Account/ChangePassword");. This worked but it first executed the original action method requested by the user. This behavior defeated the purpose.

I tried using the extension method HttpContext.SetEndpoint, but there was no example available to work with.

Body:
In my case, I am manually selecting the matching endpoint in a DynamicRouteValueTransformer. I have a mostly working solution but have to switch to other priorities. Perhaps someone else can create a more elegant solution using built in Action executors.

RequestDelegate requestDelegate = async (HttpContext x) =>
{//manually handle controller activation, method invocation, and result processing
    var actionContext = new ActionContext(x, new RouteData(values), new ControllerActionDescriptor() { ControllerTypeInfo = controllerType.GetTypeInfo() });
    var activator = x.RequestServices.GetService(typeof(IControllerActivator)) as ServiceBasedControllerActivator;
    var controller = activator.Create(new ControllerContext(actionContext));
    var arguments = methodInfo.GetParameters().Select(p =>
    {
        object r;
        if (requestData.TryGetValue(p.Name, out object value)) r = value;
        else if (p.ParameterType.IsValueType) r = Activator.CreateInstance(p.ParameterType);
        else r = null;
        return r;
    });
    var actionResultTask = methodInfo.Invoke(controller, arguments.ToArray());
    var actionTask = actionResultTask as Task<IActionResult>;
    if (actionTask != null)
    {
        var actionResult = await actionTask;
        await actionResult.ExecuteResultAsync(actionContext);//errors here. actionContext is incomplete
    }
};

var endpoint = new Endpoint(requestDelegate, EndpointMetadataCollection.Empty, methodInfo.Name);
httpContext.SetEndpoint(endpoint);


问:
Can I access the shadow DOM using jQuery?
I defined a component with polymer like this:

```<code><polymer-element name="my-component">
  <template>
    <div id='test'>CONTENT</div>
  </template>
</polymer-element>
</code>```

Now I want to access the shadow dom, for example: to get the content of div id='test'

```<code>var x = $("div#test").html();
</code>```

The given code doesn't work.
Can I access the shadow dom with jquery?

答:
You can do it like this:</p>

```<code>$("#example", this.shadowRoot).DataTable();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I defined a component with polymer like this:

<polymer-element name="my-component">
  <template>

CONTENT

  </template>
</polymer-element>

Now I want to access the shadow dom, for example: to get the content of div id='test'

var x = $("div#test").html();

The given code doesn't work.
Can I access the shadow dom with jquery?

Body:
You can do it like this:

$("#example", this.shadowRoot).DataTable();


问:
Destructor called in method that pass value to variable
I am creating pseudo std::vector. I want to be able to declare variable Matrix B and after that assign value to it, passed by another Matrix variable.
Matrix have constructor, that allocate memo

```<code>Vect(int size, char name) : name(name), size(size), store(new int[size]){}
</code>```

and destructor that deletes it on end of var lifecycle

```<code>~Vect(){
  std::cout << "memo located: " << name << std::endl;
  delete[] store;
}
</code>```

Unfortunatelly, the method that used to return value returns it with destructor called

```<code>  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b; // <- here it calls destructor!!!
  }
</code>```

I try to do this:

```<code>  Vect m2;
  Vect m1 = Vect(10, 'A');
  m2 = -m1;
</code>```

And I get this error:

```<code>memo located: C
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10,
memo located: A
memo located: C
a.out(46158,0x109e71dc0) malloc: *** error for object 0x7f9162401850: pointer being freed was not allocated
a.out(46158,0x109e71dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6
</code>```

How can I walk around it with functionality saved?
My code:

```<code>#include <iostream>

class Vect {
  int *store;
  int size = 0;
  char name;

  public:
  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b;
  }

  int *getPointer(){
    return store;
  }
  int getSize(){
    return size;
  }

  bool set(int i, int v){
    if (i >= size)
      return false;
    store[i] = v;
    return true;
  }

  Vect(){}
  Vect(int size, char name) : name(name), size(size), store(new int[size]){}
  ~Vect(){
    std::cout << "memo located: " << name << std::endl;
    delete[] store;
    }
};

int main(int argc, char **argv){
  Vect m2;
  Vect m1 = Vect(10, 'A');

  int i = 0;
  while(m1.set(i++, i));

  m2 = -m1;
  int size = m2.getSize(), *ptr = m2.getPointer();
  for (int i = 0; i < size; i++){
    std::cout << ptr[i] << ", ";
  }
  std::cout << std::endl;
  return 0;
}
</code>```

答: What I'm trying to do is impossible achieve. Either operator- should invert original object or I should implement operator= and modify operator-

Body:
I am creating pseudo std::vector. I want to be able to declare variable Matrix B and after that assign value to it, passed by another Matrix variable.
Matrix have constructor, that allocate memo

Vect(int size, char name) : name(name), size(size), store(new int[size]){}

and destructor that deletes it on end of var lifecycle

~Vect(){
  std::cout << "memo located: " << name << std::endl;
  delete[] store;
}

Unfortunatelly, the method that used to return value returns it with destructor called

  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b; // <- here it calls destructor!!!
  }

I try to do this:

  Vect m2;
  Vect m1 = Vect(10, 'A');
  m2 = -m1;

And I get this error:

memo located: C
-1, -2, -3, -4, -5, -6, -7, -8, -9, -10,
memo located: A
memo located: C
a.out(46158,0x109e71dc0) malloc: *** error for object 0x7f9162401850: pointer being freed was not allocated
a.out(46158,0x109e71dc0) malloc: *** set a breakpoint in malloc_error_break to debug
Abort trap: 6

How can I walk around it with functionality saved?
My code:

#include <iostream>

class Vect {
  int *store;
  int size = 0;
  char name;

  public:
  Vect operator- (){
    Vect b(size,'C');
    for (int i = 0; i < size; i++){
      b.store[i] = -store[i];
    }
    return b;
  }

  int *getPointer(){
    return store;
  }
  int getSize(){
    return size;
  }

  bool set(int i, int v){
    if (i >= size)
      return false;
    store[i] = v;
    return true;
  }

  Vect(){}
  Vect(int size, char name) : name(name), size(size), store(new int[size]){}
  ~Vect(){
    std::cout << "memo located: " << name << std::endl;
    delete[] store;
    }
};

int main(int argc, char **argv){
  Vect m2;
  Vect m1 = Vect(10, 'A');

  int i = 0;
  while(m1.set(i++, i));

  m2 = -m1;
  int size = m2.getSize(), *ptr = m2.getPointer();
  for (int i = 0; i < size; i++){
    std::cout << ptr[i] << ", ";
  }
  std::cout << std::endl;
  return 0;
}


问:
Android Kotlin: fetching image from directory
I am building an app with Kotlin frontend/Python backend. My python script creates a .png file under getFilesDir() directory (/data/user/0/com.example.myproject/files/mygraph.png). I then want to use kotlin to fetch the .png file and display it on imageview.

Believe I have to use Bitmap but am not familiar with it so your support is much appreciated.

```<code>class Graph : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_graph)

        val dir = "/data/user/0/com.example.myproject/files/mygraph.png"
        //Bitmap function

    }
}
</code>```

答:
Use BitmapFactory to decode file path

```<code>    val imageView = ImageView(this)
        imageView.setImageBitmap(BitmapFactory.decodeFile(filePath))
</code>```

Body:
I am building an app with Kotlin frontend/Python backend. My python script creates a .png file under getFilesDir() directory (/data/user/0/com.example.myproject/files/mygraph.png). I then want to use kotlin to fetch the .png file and display it on imageview.

Believe I have to use Bitmap but am not familiar with it so your support is much appreciated.

class Graph : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_graph)

        val dir = "/data/user/0/com.example.myproject/files/mygraph.png"
        //Bitmap function

    }
}

Body:
Use BitmapFactory to decode file path

    val imageView = ImageView(this)
        imageView.setImageBitmap(BitmapFactory.decodeFile(filePath))


问:
Rearrange two columns so that the first column values are always larger in R
I have two columns that holds integers. I need to rearrange the columns so that the first column values are always larger

The example input:

```<code>     co1 co2
[1,]  15  25
[2,]  35  55
[3,]  65  45
[4,]  40  50
</code>```

The desired output:

```<code>     co1 co2
[1,]  25  15
[2,]  55  35
[3,]  65  45
[4,]  50  40
</code>```

Any help will be appreciated.

答:
My solution is as follows:

```<code>for(i in 1:dim(df)[1]){
  if(df[i,1]<df[i,2]){
    df[i,1]->store
    df[i,2]->df[i,1]
    store->df[i,2]
  }
}
</code>```

However, I am sure that there is an elegant solution in a line!

Body:
I have two columns that holds integers. I need to rearrange the columns so that the first column values are always larger

The example input:

     co1 co2
[1,]  15  25
[2,]  35  55
[3,]  65  45
[4,]  40  50

The desired output:

     co1 co2
[1,]  25  15
[2,]  55  35
[3,]  65  45
[4,]  50  40

Any help will be appreciated.

Body:
My solution is as follows:

for(i in 1:dim(df)[1]){
  if(df[i,1]<df[i,2]){
    df[i,1]->store
    df[i,2]->df[i,1]
    store->df[i,2]
  }
}

However, I am sure that there is an elegant solution in a line!


问:
Class object can only call a method if object attribute is between a range
I am looking to make my code more sophisticated and this is the issue that I am running into

```<code>class Person:

    def __init__(self, age):
        self.age = age

    def drives(self):
        if self.age >= 18:
            # Do more things which driving entitles
            print("you can drive")

    def studies(self):
        if self.age <= 25:
            # Do more student stuffs
            print("Good luck with your education")

bob = Person(14)
bob.drives()
bob.studies()

jim = Person(35)
jim.drives()
jim.studies()
</code>```

I don't like the checks as soon as I enter the method, increasing markup. I know about decorators, are they the best thing to do here? And how would I use them for this use case? What I would like it to look like is:

```<code>class Person:

    def __init__(self, age):
        self.age = age

    @check_if_person_age_is_greater_than_17
    def drives(self):
        # Do more things which driving entitles
        print("you can drive")

    @check_if_person_age_is_less_than_26
    def studies(self):
        # Do more student stuffs
        print("Good luck with your education")

bob = Person(14)
bob.drives() # either this method cannot be accessed or returns nothing, since bob is 14
bob.studies() # this should work normally

jim = Person(35)
jim.drives() # this should work normally
jim.studies() # either this method cannot be accessed or returns nothing, since jim is 35
</code>```

I am sorry if my question isn't concise or worthwhile.

答:
So this is what I was able to come up with. This cleans up the code quite a lot but may make it a little difficult to understand. You can also make the decorator into a classmethod or staticmethod, if that is your requirement.</p>

```<code>from functools import wraps

def prerequisite(age_limit=18, _func=None):
  def _wrapper_function(func):
    @wraps(func)
    def _inner_function(*args, **kwargs):
        if args[0].age >= age_limit:
          return func(*args, **kwargs)
        else:
          raise ValueError("You can't {func_name} at the age of {age}".format(func_name=func.__name__, age=args[0].age))
    return _inner_function
  if _func is None:
      return _wrapper_function
  else:
      return _wrapper_function(_func)

class Person(object):
    def __init__(self, age):
      self.age = age

    @prerequisite(age_limit=16)
    def drive(self):
      # Do more drive stuffs
      print("You are eligible to apply for a license to drive. Please drive responsibly.")

    @prerequisite(age_limit=21)
    def drink(self, drink_name):
      # Do more drink stuffs
      # Passing an argument just to show that arguments can also be passed like this.
      print("You can legally drink. Alcohol is dangerous to health, drink cautiously. Your favorite drink is {drink_name}".format(drink_name=drink_name))

    @prerequisite()
    def fly(self):
      # Do more fly stuffs
      # This is an example for how default args for decorator works
      print("You are eligible to apply for a license to fly.")

bob = Person(19)

bob.drive() # works
bob.fly() # works
bob.drink("Beer") # This will throw an exception
</code>```

Body:
I am looking to make my code more sophisticated and this is the issue that I am running into

class Person:

    def __init__(self, age):
        self.age = age

    def drives(self):
        if self.age >= 18:
            # Do more things which driving entitles
            print("you can drive")

    def studies(self):
        if self.age <= 25:
            # Do more student stuffs
            print("Good luck with your education")

bob = Person(14)
bob.drives()
bob.studies()

jim = Person(35)
jim.drives()
jim.studies()

I don't like the checks as soon as I enter the method, increasing markup. I know about decorators, are they the best thing to do here? And how would I use them for this use case? What I would like it to look like is:

class Person:

    def __init__(self, age):
        self.age = age

    @check_if_person_age_is_greater_than_17
    def drives(self):
        # Do more things which driving entitles
        print("you can drive")

    @check_if_person_age_is_less_than_26
    def studies(self):
        # Do more student stuffs
        print("Good luck with your education")

bob = Person(14)
bob.drives() # either this method cannot be accessed or returns nothing, since bob is 14
bob.studies() # this should work normally

jim = Person(35)
jim.drives() # this should work normally
jim.studies() # either this method cannot be accessed or returns nothing, since jim is 35

I am sorry if my question isn't concise or worthwhile.

Body:
So this is what I was able to come up with. This cleans up the code quite a lot but may make it a little difficult to understand. You can also make the decorator into a classmethod or staticmethod, if that is your requirement.

from functools import wraps

def prerequisite(age_limit=18, _func=None):
  def _wrapper_function(func):
    @wraps(func)
    def _inner_function(*args, **kwargs):
        if args[0].age >= age_limit:
          return func(*args, **kwargs)
        else:
          raise ValueError("You can't {func_name} at the age of {age}".format(func_name=func.__name__, age=args[0].age))
    return _inner_function
  if _func is None:
      return _wrapper_function
  else:
      return _wrapper_function(_func)

class Person(object):
    def __init__(self, age):
      self.age = age

    @prerequisite(age_limit=16)
    def drive(self):
      # Do more drive stuffs
      print("You are eligible to apply for a license to drive. Please drive responsibly.")

    @prerequisite(age_limit=21)
    def drink(self, drink_name):
      # Do more drink stuffs
      # Passing an argument just to show that arguments can also be passed like this.
      print("You can legally drink. Alcohol is dangerous to health, drink cautiously. Your favorite drink is {drink_name}".format(drink_name=drink_name))

    @prerequisite()
    def fly(self):
      # Do more fly stuffs
      # This is an example for how default args for decorator works
      print("You are eligible to apply for a license to fly.")

bob = Person(19)

bob.drive() # works
bob.fly() # works
bob.drink("Beer") # This will throw an exception


问:
How can I get print except statement printed instead of an error below in try/except syntax in Python
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)
```

<p>This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?</p>

```Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined
```

答:
```<code>hours_float = None
rate_float = None

while hours_float is None:
    hours_string = input("Enter Hours: ")
    try:
        hours_float = float(hours_string)
    except ValueError:
        print("Invalid input. Enter a number please.")

while rate_float is None:
    rate_string = input("Enter Rate: ")
    try:
        rate_float = float(rate_string)
    except ValueError:
        print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay", result)
</code>```

In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.

Valid input changes the initially set None value to something else, which finishes the corresponding loop.

Body:
I am new to Python programming. Following is the code written and it works fine when I print any numeric digit and give me the desired result as expected but the problem comes when I enter string (anything other than integer/float) instead of giving me just the except statement, it also gives me an error which I don't want. So, what I want is when a user enter anything other than numeric digits, he should be prompted with a message i.e., "Invalid input. Enter a number please" instead of an error which I am getting after the except print statement in the end. Please help.

hours_string = input("Enter Hours: ")
rate_string = input("Enter Rate: ")
try:
    hours_float = float(hours_string)
    rate_float = float(rate_string)
except:
    print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay",result)

This is the error I am getting. If I enter string, I should simply get an except statement. That's it. Not any other error. How can I accomplish to get there?

Enter Hours: 9
Enter Rate: entered string by mistake
Invalid input. Enter a number please.
Traceback (most recent call last):
  File "<string>", line 9, in <module>
NameError: name 'rate_float' is not defined

Body:
hours_float = None
rate_float = None

while hours_float is None:
    hours_string = input("Enter Hours: ")
    try:
        hours_float = float(hours_string)
    except ValueError:
        print("Invalid input. Enter a number please.")

while rate_float is None:
    rate_string = input("Enter Rate: ")
    try:
        rate_float = float(rate_string)
    except ValueError:
        print("Invalid input. Enter a number please.")

result = hours_float * rate_float
print("Pay", result)

In the while loop we repeatedly ask user for input, while they don't enter a valid number, separately for hours and rate.

Valid input changes the initially set None value to something else, which finishes the corresponding loop.


问:
In-place modification, insertion or removal in the same function for hash maps in Rust
Say I have a hash map m: HashMap<K, V>, a key k: K and a value v: V, and would like to do the following:

If m does not contain a value at index k, insert v at index k.

If m contains a value w at index k, apply a function fn combine(x: V, y: V) -> Option<V> to v and w, and:

If the result is None, remove the entry at index k from m.

If the result is Some(u), replace the value at index k by u.

Is there a way to do this "in-place", without calling functions that access, modify or remove the value at k multiple times?

I would also like to avoid copying data, so ideally one shouldn't need to clone v to feed the clones into insert and combine separately.

I could rewrite combine to use (mutable) references (or inline it), but the wish of not copying data still remains.

答:
Digging deeper into the Entry documentation, I noticed that the variants of the Entry enum offer functions to modify, remove or insert entries in-place.

After taking std::collections::hash_map::Entry into scope, one could do the following:

```<code>match m.entry(k) {
    Entry::Occupied(mut oe) => {
        let w = oe.get_mut();
        match combine(v, w) {
            Some(u) => { *w = u; },
            None    => { oe.remove_entry(); },
        }
    },
    Entry::Vacant(ve) => { ve.insert(v); },
}
</code>```

(Here is a PoC in the Rust playground.)

This, however, requires combine to take a (mutable) reference as its second argument (which is fine in my case).

Body:
Digging deeper into the Entry documentation, I noticed that the variants of the Entry enum offer functions to modify, remove or insert entries in-place.

After taking std::collections::hash_map::Entry into scope, one could do the following:

match m.entry(k) {
    Entry::Occupied(mut oe) => {
        let w = oe.get_mut();
        match combine(v, w) {
            Some(u) => { *w = u; },
            None    => { oe.remove_entry(); },
        }
    },
    Entry::Vacant(ve) => { ve.insert(v); },
}

(Here is a PoC in the Rust playground.)

This, however, requires combine to take a (mutable) reference as its second argument (which is fine in my case).


问:
Match div to window size with css or javascript
I have an element which drops down when I toggle my menu bars.
I can make the element as large or as small as I like but can't make it fit to screen so it doesn't scroll and no page shows underneath. It's a WordPress site and I started off with an an i class fa-bars. It wasn't possible to animate font awesome so I replaced it with this.

```

<p>This worked to toggle the menu amd make it drop but it didn't cover the screen. The element controlling the dropdown area was too small so I enlarged it by increasing height, like so:</p>

<pre class="lang-css prettyprint-override"><code>@media (max-width: 768px) {
    .collapse {
        position: absolute;
        height: 775px;
        background-color: white;
        z-index: 99999 !important;
        top: 75px;
        left: -50px;
        line-height: 10px;
    }
}
</code>```

This made it too high but making it any lower would show the page underneath.

Is there a way I can modify my existing javascript or css to make it fit to screen exactly, responsively with no scroll and no page showing underneath?

It's located in my header.php so it would go there I'm assuming, if there's a way to modify what i already have. If not, what's a good way to approach this?

here on mobile

Html dropdown.

                    Contact

```

I've tried applying min-height to element collapse max- height and  100%  None worked.

Here's a pen https://codepen.io/adsler/pen/bGVXNVM

答:
You can used position: fixed to size the element with respect to the frame:

```<code>.your-selector {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}
</code>```

This will make it take up the entire window. It's not clear if you're wanting it to cover the window in all dimensions, but you can choose where the top/bottom/left/right anchor selectively.

If you're also wanting to make the body (or if it's not the body some other scrollable element) non-scrollable, set the overflow style to hidden.

Body:
I have an element which drops down when I toggle my menu bars.
I can make the element as large or as small as I like but can't make it fit to screen so it doesn't scroll and no page shows underneath. It's a WordPress site and I started off with an an i class fa-bars. It wasn't possible to animate font awesome so I replaced it with this.

This worked to toggle the menu amd make it drop but it didn't cover the screen. The element controlling the dropdown area was too small so I enlarged it by increasing height, like so:

@media (max-width: 768px) {
    .collapse {
        position: absolute;
        height: 775px;
        background-color: white;
        z-index: 99999 !important;
        top: 75px;
        left: -50px;
        line-height: 10px;
    }
}

This made it too high but making it any lower would show the page underneath.

Is there a way I can modify my existing javascript or css to make it fit to screen exactly, responsively with no scroll and no page showing underneath?

It's located in my header.php so it would go there I'm assuming, if there's a way to modify what i already have. If not, what's a good way to approach this?

here on mobile

Html dropdown.

                    Contact

I've tried applying min-height to element collapse max- height and  100%  None worked.

Here's a pen https://codepen.io/adsler/pen/bGVXNVM

Body:
You can used position: fixed to size the element with respect to the frame:

.your-selector {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

This will make it take up the entire window. It's not clear if you're wanting it to cover the window in all dimensions, but you can choose where the top/bottom/left/right anchor selectively.

If you're also wanting to make the body (or if it's not the body some other scrollable element) non-scrollable, set the overflow style to hidden.


问:
How can I access functions whose names have been shadowed?
I'm creating a subclass of NSDocument. From within the methods of this class, I am unable to call the print(_:String) function that writes to stdout, because it is being shadowed by NSDocument's func print(withSettings: [NSPrintInfo.AttributeKey : Any], showPrintPanel: Bool, delegate: Any?, didPrint: Selector?, contextInfo: UnsafeMutableRawPointer?).

I thought it might be possible to access print by prefixing it with its module name (or using something like global:: in C#), but I was unable to figure out which module it belongs to. The documentation states that print is included in the Swift Standard Library.

How can I access the commonly used print function in this case, and shadowed functions in general?

答:
The standard output print function is part of the Swift framework. You can call it that way:

```<code>Swift.print("Hello, world!")
</code>```

Body:
The standard output print function is part of the Swift framework. You can call it that way:

Swift.print("Hello, world!")


问:
Check if request was sent by Ajax or not
I am overriding a magento controller, before processing, is there a way to know if the request was sent by Ajax or not?

Thanks

答:
The best mehtod is :</p>

```<code>if (!$this->getRequest()->isAjax()) {
   return false;
}
</code>```

Body:
The best mehtod is :

if (!$this->getRequest()->isAjax()) {
   return false;
}


问:
Retrieve data between certain hours of day
I am trying to write a query to retrieve data between midnight and 7am of the current day.  I know I am on the right track but cannot get the syntax correct...</p>

```<code>SELECT * FROM `monthly`
WHERE LogDateTime >= date_sub(curdate('07:00:00'),INTERVAL 1 hour)
</code>```

答:
You could try this:</p>

```<code>SELECT
    *
FROM
    monthly
WHERE
    LogDateTime <= DATE_ADD(CURDATE(), INTERVAL 7 HOUR)
AND
    LogDateTime >= CURDATE()
</code>```

Body:
I am trying to write a query to retrieve data between midnight and 7am of the current day.  I know I am on the right track but cannot get the syntax correct...

SELECT * FROM `monthly`
WHERE LogDateTime >= date_sub(curdate('07:00:00'),INTERVAL 1 hour)

Body:
You could try this:

SELECT
    *
FROM
    monthly
WHERE
    LogDateTime <= DATE_ADD(CURDATE(), INTERVAL 7 HOUR)
AND
    LogDateTime >= CURDATE()


Title: Rearrange two columns so that the first column values are always larger in R

Body:
A base R one-liner is

mat[] <- t(apply(mat, 1, sort, decreasing = TRUE))
mat
#     co1 co2
#[1,]  25  15
#[2,]  55  35
#[3,]  65  45
#[4,]  50  40

Data

mat <-
structure(c(25L, 55L, 65L, 50L, 15L, 35L, 45L, 40L),
.Dim = c(4L, 2L), .Dimnames = list(NULL, c("co1", "co2")))


问:
How to push a local git reset to github?
I am trying to roll back a git commit. On the local version of the repo, I can do

```<code>`git reset --HARD xxxxxxx`
</code>```

Where the xxxxxx is the hash, but how do I push the rollback to the master on github.com?

Just a git commit fails, since the local repo is behind the master.

答:
You should use git revert (docs)

Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them.

You should use it to revert from HEAD to your specified commit with

```<code>git revert --no-commit <xxxxxxx>..HEAD
git commit
</code>```

It is handy to use --no-commit, as stated in the docs, in case you have more commits to revert at once:

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.

Body:
I am trying to roll back a git commit. On the local version of the repo, I can do

`git reset --HARD xxxxxxx`

Where the xxxxxx is the hash, but how do I push the rollback to the master on github.com?

Just a git commit fails, since the local repo is behind the master.

Body:
You should use git revert (docs)

Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them.

You should use it to revert from HEAD to your specified commit with

git revert --no-commit <xxxxxxx>..HEAD
git commit

It is handy to use --no-commit, as stated in the docs, in case you have more commits to revert at once:

Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

This is useful when reverting more than one commits' effect to your index in a row.


问:
How to link main.c to another C file from different directory in Xcode Project
In the Xcode project with languages as C.

heap

heap_sort.c

heap_sort.c

main.c

this is the heap_sort.c file

```<code>#include "heap_sort.h"

int sum(int a, int b)
{
    return a + b;

}
</code>```

this is the heap_sort.h file

```<code>#ifndef heap_sort_h
#define heap_sort_h

#include <stdio.h>

#endif /* heap_sort_h */
</code>```

this is the screenshot for my code in Xcode. I just wanted to import a function name sum to my main.c file.

this is the main.c

```<code>#include <stdio.h>
#include "heap/heap_sort.h"

int main(int argc, const char * argv[]) {
    int s;
    s = sum(3,5);
    printf("The integer is: %d\n",s);
    return 0;
}
</code>```

答:
Your main file doesn't have a declaration for sum, so it doesn't know how to call it properly.

This declaration should go in your header file:

```<code>#ifndef heap_sort_h
#define heap_sort_h

int sum(int a, int b);

#endif /* heap_sort_h */
</code>```

Body:
In the Xcode project with languages as C.

heap

heap_sort.c

heap_sort.c

main.c

this is the heap_sort.c file

#include "heap_sort.h"

int sum(int a, int b)
{
    return a + b;

}

this is the heap_sort.h file

#ifndef heap_sort_h
#define heap_sort_h

#include <stdio.h>

#endif /* heap_sort_h */

this is the screenshot for my code in Xcode. I just wanted to import a function name sum to my main.c file.

this is the main.c

#include <stdio.h>
#include "heap/heap_sort.h"

int main(int argc, const char * argv[]) {
    int s;
    s = sum(3,5);
    printf("The integer is: %d\n",s);
    return 0;
}

Body:
Your main file doesn't have a declaration for sum, so it doesn't know how to call it properly.

This declaration should go in your header file:

#ifndef heap_sort_h
#define heap_sort_h

int sum(int a, int b);

#endif /* heap_sort_h */


答:
Use CURDATE() for start and add 7 hours for the end of the datetime of BETWEEN:

```<code>SELECT * FROM `monthly`
WHERE LogDateTime BETWEEN CURDATE() AND CURDATE() +  INTERVAL 7 hour
</code>```

See a simplified demo.

Title: Retrieve data between certain hours of day

Body:
Use CURDATE() for start and add 7 hours for the end of the datetime of BETWEEN:

SELECT * FROM `monthly`
WHERE LogDateTime BETWEEN CURDATE() AND CURDATE() +  INTERVAL 7 hour

See a simplified demo.


问:
Add-in rejected for not using Microsoft OAuth, however the video the reviewer attached clearly shows it using Microsoft OAuth. What do I do?
Because older versions of Word do not support the Dialog API we display the authentication process in the Task Pane because it cannot be iframed in for obvious reasons. This process has never been an issue before so I do not understand why it is now.

What is the recommended way to provide Microsoft OAuth when the Dialog API is not available?

答: This seems like an error in the review - apologies for that; there's no problem with having the OAuth flow in the TaskPane where DialogAPI is not supported. I believe this rejection item was removed in the subsequent submission of your offer</p>


问:
putting html inside an iframe (using javascript)
Can I create an empty iframe as a placeholder to later insert html into it?

In otherwords, suppose I have an empty iframe with an id,

How do I insert html in it?

I'm using jquery, if that makes it easier.

答:
View the source of this page: http://mg.to/test/dynaframe.html It appears to do exactly what you want to do.</p>

```<code>$(function() {
    var $frame = $('<iframe style="width:200px; height:100px;">');
    $('body').html( $frame );
    setTimeout( function() {
        var doc = $frame[0].contentWindow.document;
        var $body = $('body',doc);
        $body.html('<h1>Test</h1>');
    }, 1 );
});
</code>```

OwnerDisplayName: hasen j

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: hasen j

Body:
View the source of this page: http://mg.to/test/dynaframe.html It appears to do exactly what you want to do.

$(function() {
    var $frame = $('<iframe style="width:200px; height:100px;">');
    $('body').html( $frame );
    setTimeout( function() {
        var doc = $frame[0].contentWindow.document;
        var $body = $('body',doc);
        $body.html('<h1>Test</h1>');
    }, 1 );
});

OwnerDisplayName: Tyson


问:
Restrict date in jquery datetimepicker based on another datetimepicker
I have two text boxes with a datetimepicker hooked up to them. The text boxes are for start date and end date. The first datetimepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datetimepicker so that it cannot choose a date before the date chosen in the first date picker and whatever date is selected in first datetimepicker, the second datetimepicker date should be exactly 1 month from the first datetimepicker(User can then select the second datetimepicker to be 1 month or less than 1 month)?

Here's what I have so far:

Tried it via datetimepicker and onChangeDateTime function

```<code><script src="~/Scripts/jquery.datetimepicker.js"></script>
    <script>
    $(document).ready(function () {
        $('#ValidFrom').datetimepicker({
            datepicker: true,
            timepicker: false,
            format: 'm/d/Y',
            step: 30,
            minDate: new Date(),
            onChangeDateTime: function (dp, $input) {
                var date = new Date($input.val());
                $('#ValidTo').datetimepicker("option", "minDate", date);
                //alert(date);
                var date2 = new Date($input.val());
                date2.setMonth(date.getMonth() + 1);
                $('#ValidTo').datetimepicker("option", "maxDate", date2);
                //alert(date2);
                date2 = (date2.getMonth() + 1) + '/' + date2.getDate() + '/' + date2.getFullYear();
                $('#ValidTo').val(date2);
            }
        });

        $('#ValidTo').datetimepicker({
            datepicker: true,
            timepicker: false,
            format: 'm/d/Y',
            step: 30,
            minDate: new Date()
        });
    });

</script>
</code>```

If today is 1/16/2019 and I choose 1/28/2019 in the first datetimepicker, then the second date picker shouldn't be able to choose anything before 1/28/2019, second datetimepicker date should be 2/28/2019 or the user if wants, can select the date as less than 1 month.

答:
```<code>let DateInitial = $("#DateInitial");
let DateEnd = $("#DateEnd");
let dateNow = new Date();

/* click start clear end  */
DateInitial.on("click", function(){
    DateEnd.val(" ");

    DateInitial.datetimepicker({
        onShow:function( ct ){
            this.setOptions({
                format: 'd-m-Y H:i',
                closeOnDateSelect : true,
                validateOnBlur : true,
                minDate: -0,
                minTime: dateNow.getTime(),
                onClose: function($input){
                    dateAllowPlusOne($input);
                }
            });
       }
    });
});

function dateAllowPlusOne(dateStart){

    if(DateInitial.val()=="")
    {
        DateInitial.focus();
        return false;
    }

    DateEnd.datetimepicker({
        'format': 'd/m/Y H:i',
        'minDate': -0,
        startDate: dateStart,
        'closeOnDateSelect' : true,
        'validateOnBlur' : true,
        'minDateTime': new Date()
    });

    DateEnd.attr("disabled", false);
}
</code>```

Body:
I have two text boxes with a datetimepicker hooked up to them. The text boxes are for start date and end date. The first datetimepicker is setup so that the user cannot choose a date before today, but can choose any date in the future.

How can I setup the second datetimepicker so that it cannot choose a date before the date chosen in the first date picker and whatever date is selected in first datetimepicker, the second datetimepicker date should be exactly 1 month from the first datetimepicker(User can then select the second datetimepicker to be 1 month or less than 1 month)?

Here's what I have so far:

Tried it via datetimepicker and onChangeDateTime function

If today is 1/16/2019 and I choose 1/28/2019 in the first datetimepicker, then the second date picker shouldn't be able to choose anything before 1/28/2019, second datetimepicker date should be 2/28/2019 or the user if wants, can select the date as less than 1 month.


问:
Editing files through a shellscript?
I need to unzip a file and for each of the documents in that file, I need to make a correction to the comment (the files are written in C). I'm a bit confused as to how I can do this for each document in the file (I don't know the amount of documents, or their names), is there someway I can write a for loop across the folder to open each document individually and then edit them, within the shellscript?

I'm also a bit confused at the difference between sed and awk and which one I should be using here. I need to edit the comment (which begins with //) and believe I should be using awk but am not too sure.

My pseudocode for this (so far) would be as such

```<code>unzip $1
edit_comment(){
    cat file1 file2 ... filen > total.txt
    *some awk command that will search for all instances of // and replace the text on that line (after
    the //) with a new comment*
}
</code>```

Thanks!

答:
I believe You are looking for How to do a recursive find/replace of a string with awk or sed.

Assumptions:

- The argument $1 is some folder.tar.gz or archive.zip or blah.bz4

- All files within that unzipped archive that contain comments should be changed

dir=$(echo $1 | sed 's#\..*##')
find $dir -type f -print0 | xargs -0 sed -i 's#//old comment #//new comment#'
```

Title: Editing files through a shellscript?

Body:
I need to unzip a file and for each of the documents in that file, I need to make a correction to the comment (the files are written in C). I'm a bit confused as to how I can do this for each document in the file (I don't know the amount of documents, or their names), is there someway I can write a for loop across the folder to open each document individually and then edit them, within the shellscript?

I'm also a bit confused at the difference between sed and awk and which one I should be using here. I need to edit the comment (which begins with //) and believe I should be using awk but am not too sure.

My pseudocode for this (so far) would be as such

unzip $1
edit_comment(){
    cat file1 file2 ... filen > total.txt
    *some awk command that will search for all instances of // and replace the text on that line (after
    the //) with a new comment*
}

Thanks!


问:
Decode Base64 data in Java
I have an image that is Base64 encoded. What is the best way to decode that in Java? Hopefully using only the libraries included with Sun Java 6.</p>

答:
```<code>import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/***
 *
 * @author Vaquar khan
 *
 *
 */
public class AES {

    private static SecretKeySpec secretKey;
    private static final String VK_secretKey = "VaquarKhan-secrate-key!!!!";
    private static byte[] key;

    /**
     *
     * @param myKey
     */
    public static void setKey(String myKey) {
        MessageDigest sha = null;
        try {
            key = myKey.getBytes("UTF-8");
            sha = MessageDigest.getInstance("SHA-1");
            key = sha.digest(key);
            key = Arrays.copyOf(key, 16);
            secretKey = new SecretKeySpec(key, "AES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
/**
 * encrypt
 * @param strToEncrypt
 * @param secret
 * @return
 */
    public static String encrypt(String strToEncrypt, String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
        } catch (Exception e) {
            System.out.println("Error while encrypting: " + e.toString());
        }
        return null;
    }
/**
 * decrypt
 * @param strToDecrypt
 * @param secret
 * @return
 */
    public static String decrypt(String strToDecrypt, String secret) {
        try {
            setKey(secret);
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
        } catch (Exception e) {
            System.out.println("Error while decrypting: " + e.toString());
        }
        return null;
    }

    public static void main(String[] args) {
        final String secretKey = VK_secretKey;
        String password = "VKhan@12";
        //
        String encryptedString = AES.encrypt(password, secretKey);
        String decryptedString = AES.decrypt(encryptedString, secretKey);
        //
        System.out.println(password);
        System.out.println(encryptedString);
        System.out.println(decryptedString);
    }

}
</code>```

OwnerDisplayName: Ryan P

Title: Decode Base64 data in Java

LastEditorDisplayName: Ryan P


问:
how to type transition props in material ui popper
I am using material ui popper and want to separate the transition into a separate function as follows

```<code>import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Popper from '@material-ui/core/Popper';
import Fade from '@material-ui/core/Fade';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    paper: {
      border: '1px solid',
      padding: theme.spacing(1),
      backgroundColor: theme.palette.background.paper,
    },
  }),
);

export default function TransitionsPopper() {
  const classes = useStyles();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'transitions-popper' : undefined;

  const popperTrans = ({ TransitionProps }) => (
    <Fade {...TransitionProps} timeout={350}>
      <div className={classes.paper}>The content of the Popper.</div>
    </Fade>
  )
  return (
    <div>
      <button aria-describedby={id} type="button" onClick={handleClick}>
        Toggle Popper
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl} transition>
        {popperTrans}
      </Popper>
    </div>
  );
}
</code>```

I am using typescript and it's throwing tslint error Binding element 'TransitionProps' implicitly has an 'any' type. How can I type TransitionProps here?

答:
Alternatively, TransitionProps is exported, so you can do:

```<code>import { TransitionProps as TransitionPropsType } from "@material-ui/core";
</code>```

Then:

```<code>  const popperTrans = ({ TransitionProps }: { TransitionProps: TransitionPropsType }) => (
    <Fade {...TransitionProps} timeout={350}>
      <div className={classes.paper}>The content of the Popper.</div>
    </Fade>
  )
</code>```

Body:
I am using material ui popper and want to separate the transition into a separate function as follows

import React from 'react';
import { makeStyles, Theme, createStyles } from '@material-ui/core/styles';
import Popper from '@material-ui/core/Popper';
import Fade from '@material-ui/core/Fade';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    paper: {
      border: '1px solid',
      padding: theme.spacing(1),
      backgroundColor: theme.palette.background.paper,
    },
  }),
);

export default function TransitionsPopper() {
  const classes = useStyles();
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(anchorEl ? null : event.currentTarget);
  };

  const open = Boolean(anchorEl);
  const id = open ? 'transitions-popper' : undefined;

  const popperTrans = ({ TransitionProps }) => (
    <Fade {...TransitionProps} timeout={350}>

The content of the Popper.

    </Fade>
  )
  return (

      <button aria-describedby={id} type="button" onClick={handleClick}>
        Toggle Popper
      </button>
      <Popper id={id} open={open} anchorEl={anchorEl} transition>
        {popperTrans}
      </Popper>

  );
}

I am using typescript and it's throwing tslint error Binding element 'TransitionProps' implicitly has an 'any' type. How can I type TransitionProps here?

Body:
Alternatively, TransitionProps is exported, so you can do:

import { TransitionProps as TransitionPropsType } from "@material-ui/core";

Then:

  const popperTrans = ({ TransitionProps }: { TransitionProps: TransitionPropsType }) => (
    <Fade {...TransitionProps} timeout={350}>
      <div className={classes.paper}>The content of the Popper.</div>
    </Fade>
  )


问:
How can I get an item by a string key using web api?
I can't figure out how to hit an endpoint like "api/GetItems/AB123" (AB123 of course being a string) and have it return that item from my data set. I read the docs on the FindAsync() method and it seemed to indicate that it would accept a string by default. Is there something I need to do to 'id' before passing it into FindAsync()? My DB does not have a primary key, if that matters. (I can't change that either, this is legacy data and I have no control over schema)

My db doesn't have a PK ID field. I need to do the next best thing and target a unique string field.

My GET method:

```<code>        // GET: api/Items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(string id)
        {
            var item = await _context.Items.FindAsync(id); // Error happens here: "InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int64'."

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }
</code>```

Relevant from my model:

```<code>    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string ItemId { get; set; }

</code>```

答:
From your error it is obvious that int is expected in FindById method. Can you check the field type in database but from your model I would say that you don't have correct type.
String can't be used as Identity in this way because SQL Server doesn't know how to generate value for that.

You can check this post for more details on that: DatabaseGeneratedOption.Identity not generating an Id

So to conclude, you should check what do you really have in the database to determine is your model wrong.

If that is not the case and you do have a string in the db you should just retrieve item by using SingleAsync method (note that it will throw exception if the id is wrong).

```<code>var item = await _context.Items.SingleAsync(e => e.ItemId == id);
</code>```

If you don't want an exception if the id doesn't exist you can use:

```<code>var item = await _context.Items.SingleOrDefaultAsync(e => e.ItemId == id);
</code>```

which will return null for non existent id.

Body:
I can't figure out how to hit an endpoint like "api/GetItems/AB123" (AB123 of course being a string) and have it return that item from my data set. I read the docs on the FindAsync() method and it seemed to indicate that it would accept a string by default. Is there something I need to do to 'id' before passing it into FindAsync()? My DB does not have a primary key, if that matters. (I can't change that either, this is legacy data and I have no control over schema)

My db doesn't have a PK ID field. I need to do the next best thing and target a unique string field.

My GET method:

        // GET: api/Items/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Item>> GetItem(string id)
        {
            var item = await _context.Items.FindAsync(id); // Error happens here: "InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int64'."

            if (item == null)
            {
                return NotFound();
            }

            return item;
        }

Relevant from my model:

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public string ItemId { get; set; }

Body:
From your error it is obvious that int is expected in FindById method. Can you check the field type in database but from your model I would say that you don't have correct type.
String can't be used as Identity in this way because SQL Server doesn't know how to generate value for that.

You can check this post for more details on that: DatabaseGeneratedOption.Identity not generating an Id

So to conclude, you should check what do you really have in the database to determine is your model wrong.

If that is not the case and you do have a string in the db you should just retrieve item by using SingleAsync method (note that it will throw exception if the id is wrong).

var item = await _context.Items.SingleAsync(e => e.ItemId == id);

If you don't want an exception if the id doesn't exist you can use:

var item = await _context.Items.SingleOrDefaultAsync(e => e.ItemId == id);

which will return null for non existent id.


问:
Checking if float is equivalent to an integer value in python
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

```<code>import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num
</code>```

Or do I need to do check within a tolerance instead?

```<code>epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon
</code>```

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

答: I think the module decimal is what you need

Body:
In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.


问:
RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False, Dataloader Error, and setting pin_memory=False
I am a beginner trying to evaluate this video object segmentation network paper.

When following the instructions on https://github.com/seoungwugoh/STM

It says the requirements are as follows:-

```<code>python 3.6
pytorch 1.0.1.post2
numpy, opencv, pillow
</code>```

I couldn't get this pytorch version to install, so I installed the conda-forge pytorch version 1.5.

and I run this command in either Windows 10 or Ubuntu 16.04 using Anaconda

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python eval_DAVIS.py -g '1' -s val -y 16 -D ../DAVISSemiSupervisedTrainVal480
</code>```

after doing pip install matplotlib, and pip install tqdm ...

I get the following error message:-

Space-time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Traceback (most recent call last):

File "eval_DAVIS.py", line 111, in
  model.load_state_dict(torch.load(pth_path))

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 593, in load
  return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 773, in _legacy_load
  result = unpickler.load()

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 729, in persistent_load

deserialized_objects[root_key] = restore_location(obj, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 178, in default_restore_location
  result = fn(storage, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 154, in _cuda_deserialize
    device = validate_cuda_device(location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 138, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA '

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU

My Graphics Card Driver, and System and Packages are as follows:-

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ nvidia-smi
</code>```

```<code>+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1070    Off  | 00000000:01:00.0  On |                  N/A |
| 26%   34C    P8    10W / 151W |    392MiB /  8118MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1247      G   /usr/lib/xorg/Xorg                           229MiB |
|    0      2239      G   compiz                                       126MiB |
|    0      9385      G   /usr/lib/firefox/firefox                       2MiB |
|    0     11686      G   /proc/self/exe                                30MiB |
+-----------------------------------------------------------------------------+
</code>```

I also tried this

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python -c 'import torch; print(torch.rand(2,3).cuda())'
</code>```

tensor([[0.9178, 0.8239, 0.4761],
        [0.9429, 0.8877, 0.0097]], device='cuda:0')

Which shows that cuda is working here

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda info
    active environment : STMVOS
    active env location : /home/oneworld/anaconda3/envs/STMVOS
            shell level : 1
       user config file : /home/oneworld/.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : 3.18.11
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
                          __glibc=2.23
       base environment : /home/oneworld/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/oneworld/anaconda3/pkgs
                          /home/oneworld/.conda/pkgs
       envs directories : /home/oneworld/anaconda3/envs
                          /home/oneworld/.conda/envs
               platform : linux-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Linux/4.4.0-179-generic ubuntu/16.04.6 glibc/2.23
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False
</code>```

```<code>(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda list
</code>```

packages in environment at /home/oneworld/anaconda3/envs/STMVOS:

Name                    Version                   Build  Channel
_libgcc_mutex             0.1                        main

blas                      1.0                         mkl

bzip2                     1.0.8                h516909a_2    conda-forge
ca-certificates           2020.4.5.1           hecc5488_0    conda-forge
cairo                     1.16.0            hcf35c78_1003    conda-forge
certifi                   2020.4.5.1               py38_0

cudatoolkit               10.2.89              hfd86e86_1

cycler                    0.10.0                   pypi_0    pypi
dbus                      1.13.6               he372182_0    conda-forge
expat                     2.2.9                he1b5a44_2    conda-forge
ffmpeg                    4.2.3                h167e202_0    conda-forge
fontconfig                2.13.1            h86ecdb6_1001    conda-forge
freetype                  2.9.1                h8a8886c_1

gettext                   0.19.8.1          hc5be6a0_1002    conda-forge
giflib                    5.2.1                h516909a_2    conda-forge
glib                      2.64.3               h6f030ca_0    conda-forge
gmp                       6.2.0                he1b5a44_2    conda-forge
gnutls                    3.6.5             hd3a4fd2_1002    conda-forge
graphite2                 1.3.13            he1b5a44_1001    conda-forge
gst-plugins-base          1.14.5               h0935bb2_2    conda-forge
gstreamer                 1.14.5               h36ae1b5_2    conda-forge
harfbuzz                  2.4.0                h9f30f68_3    conda-forge
hdf5                      1.10.6          nompi_h3c11f04_100    conda-forge
icu                       64.2                 he1b5a44_1    conda-forge
intel-openmp              2020.1                      217

jasper                    1.900.1           h07fcdf6_1006    conda-forge
jpeg                      9c                h14c3975_1001    conda-forge
kiwisolver                1.2.0                    pypi_0    pypi
lame                      3.100             h14c3975_1001    conda-forge
ld_impl_linux-64          2.33.1               h53a641e_7

libblas                   3.8.0                    15_mkl    conda-forge
libcblas                  3.8.0                    15_mkl    conda-forge
libclang                  9.0.1           default_hde54327_0    conda-forge
libedit                   3.1.20181209         hc058e9b_0

libffi                    3.2.1             he1b5a44_1007    conda-forge
libgcc-ng                 9.1.0                hdf63c60_0

libgfortran-ng            7.3.0                hdf63c60_0

libiconv                  1.15              h516909a_1006    conda-forge
liblapack                 3.8.0                    15_mkl    conda-forge
liblapacke                3.8.0                    15_mkl    conda-forge
libllvm9                  9.0.1                he513fc3_1    conda-forge
libopencv                 4.2.0                    py38_6    conda-forge
libpng                    1.6.37               hbc83047_0

libstdcxx-ng              9.1.0                hdf63c60_0

libtiff                   4.1.0                h2733197_0

libuuid                   2.32.1            h14c3975_1000    conda-forge
libwebp                   1.0.2                h56121f0_5    conda-forge
libxcb                    1.13              h14c3975_1002    conda-forge
libxkbcommon              0.10.0               he1b5a44_0    conda-forge
libxml2                   2.9.10               hee79883_0    conda-forge
matplotlib                3.2.1                    pypi_0    pypi
mkl                       2020.1                      217

mkl-service               2.3.0            py38he904b0f_0

mkl_fft                   1.0.15           py38ha843d7b_0

mkl_random                1.1.1            py38h0573a6f_0

ncurses                   6.2                  he6710b0_1

nettle                    3.4.1             h1bed415_1002    conda-forge
ninja                     1.9.0            py38hfd86e86_0

nspr                      4.25                 he1b5a44_0    conda-forge
nss                       3.47                 he751ad9_0    conda-forge
numpy                     1.18.1           py38h4f9e942_0

numpy-base                1.18.1           py38hde5b4d6_1

olefile                   0.46                       py_0

opencv                    4.2.0                    py38_6    conda-forge
openh264                  2.1.1                h8b12597_0    conda-forge
openssl                   1.1.1g               h516909a_0    conda-forge
pcre                      8.44                 he1b5a44_0    conda-forge
pillow                    7.1.2            py38hb39fc2d_0

pip                       20.0.2                   py38_3

pixman                    0.38.0            h516909a_1003    conda-forge
pthread-stubs             0.4               h14c3975_1001    conda-forge
py-opencv                 4.2.0            py38h23f93f0_6    conda-forge
pyparsing                 2.4.7                    pypi_0    pypi
python                    3.8.1                h0371630_1

python-dateutil           2.8.1                    pypi_0    pypi
python_abi                3.8                      1_cp38    conda-forge
pytorch                   1.5.0           py3.8_cuda10.2.89_cudnn7.6.5_0    pytorch
qt                        5.12.5               hd8c4c69_1    conda-forge
readline                  7.0                  h7b6447c_5

setuptools                46.4.0                   py38_0

six                       1.14.0                   py38_0

sqlite                    3.31.1               h62c20be_1

tk                        8.6.8                hbc83047_0

torchvision               0.6.0                py38_cu102    pytorch
tqdm                      4.46.0                   pypi_0    pypi
wheel                     0.34.2                   py38_0

x264                      1!152.20180806       h14c3975_0    conda-forge
xorg-kbproto              1.0.7             h14c3975_1002    conda-forge
xorg-libice               1.0.10               h516909a_0    conda-forge
xorg-libsm                1.2.3             h84519dc_1000    conda-forge
xorg-libx11               1.6.9                h516909a_0    conda-forge
xorg-libxau               1.0.9                h14c3975_0    conda-forge
xorg-libxdmcp             1.1.3                h516909a_0    conda-forge
xorg-libxext              1.3.4                h516909a_0    conda-forge
xorg-libxrender           0.9.10            h516909a_1002    conda-forge
xorg-renderproto          0.11.1            h14c3975_1002    conda-forge
xorg-xextproto            7.3.0             h14c3975_1002    conda-forge
xorg-xproto               7.0.31            h14c3975_1007    conda-forge
xz                        5.2.5                h7b6447c_0

zlib                      1.2.11               h7b6447c_3

zstd                      1.3.7                h0b5b093_0

The code it gets stuck on in eval_DAVIS.py is as follows:-

```<code>print('Loading weights:', pth_path)
model.load_state_dict(torch.load(pth_path))
</code>```

I am using Ubuntu 16.04, however I tried a similar setup in windows 10 and received the same error messages.

Any help much appreciated.

Kind regards

OneWorld

答:
I just created README.md file for this project to run successfully, it's here: Install PyTorch via pip to run STM Paper. I have tested in Windows 10 with Cuda version 10.1. Just follow this README.md step by step and you should be good to go.

Your PyTorch installation command could be different based on your system configuration, get your installation command as shown in the image below:

Your requirements.txt file should look like this:

NOTE: I haven't done anything with [path/to/DAVIS] or something. You might be able to run the script eval_DAVIS.py without installation error, and that all that I tested. You should be run in Ubuntu as well, just use an appropriate command from README.md.

Happy Coding!

Body:
I am a beginner trying to evaluate this video object segmentation network paper.

When following the instructions on https://github.com/seoungwugoh/STM

It says the requirements are as follows:-

python 3.6
pytorch 1.0.1.post2
numpy, opencv, pillow

I couldn't get this pytorch version to install, so I installed the conda-forge pytorch version 1.5.

and I run this command in either Windows 10 or Ubuntu 16.04 using Anaconda

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python eval_DAVIS.py -g '1' -s val -y 16 -D ../DAVISSemiSupervisedTrainVal480

after doing pip install matplotlib, and pip install tqdm ...

I get the following error message:-

Space-time Memory Networks: initialized.
STM : Testing on DAVIS
Loading weights: STM_weights.pth
Traceback (most recent call last):

File "eval_DAVIS.py", line 111, in
  model.load_state_dict(torch.load(pth_path))

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 593, in load
  return _legacy_load(opened_file, map_location, pickle_module, **pickle_load_args)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 773, in _legacy_load
  result = unpickler.load()

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 729, in persistent_load

deserialized_objects[root_key] = restore_location(obj, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 178, in default_restore_location
  result = fn(storage, location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 154, in _cuda_deserialize
    device = validate_cuda_device(location)

File "/home/oneworld/anaconda3/envs/STMVOS/lib/python3.8/site-packages/torch/serialization.py", line 138, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA '

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU

My Graphics Card Driver, and System and Packages are as follows:-

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ nvidia-smi

+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.64.00    Driver Version: 440.64.00    CUDA Version: 10.2     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  GeForce GTX 1070    Off  | 00000000:01:00.0  On |                  N/A |
| 26%   34C    P8    10W / 151W |    392MiB /  8118MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
|    0      1247      G   /usr/lib/xorg/Xorg                           229MiB |
|    0      2239      G   compiz                                       126MiB |
|    0      9385      G   /usr/lib/firefox/firefox                       2MiB |
|    0     11686      G   /proc/self/exe                                30MiB |
+-----------------------------------------------------------------------------+

I also tried this

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ python -c 'import torch; print(torch.rand(2,3).cuda())'

tensor([[0.9178, 0.8239, 0.4761],
        [0.9429, 0.8877, 0.0097]], device='cuda:0')

Which shows that cuda is working here

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda info
    active environment : STMVOS
    active env location : /home/oneworld/anaconda3/envs/STMVOS
            shell level : 1
       user config file : /home/oneworld/.condarc
 populated config files :
          conda version : 4.8.2
    conda-build version : 3.18.11
         python version : 3.7.6.final.0
       virtual packages : __cuda=10.2
                          __glibc=2.23
       base environment : /home/oneworld/anaconda3  (writable)
           channel URLs : https://repo.anaconda.com/pkgs/main/linux-64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/linux-64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /home/oneworld/anaconda3/pkgs
                          /home/oneworld/.conda/pkgs
       envs directories : /home/oneworld/anaconda3/envs
                          /home/oneworld/.conda/envs
               platform : linux-64
             user-agent : conda/4.8.2 requests/2.22.0 CPython/3.7.6 Linux/4.4.0-179-generic ubuntu/16.04.6 glibc/2.23
                UID:GID : 1000:1000
             netrc file : None
           offline mode : False

(STMVOS) oneworld@oneworld:~/Documents/VideoObjectSegmentation/STMVOS$ conda list

packages in environment at /home/oneworld/anaconda3/envs/STMVOS:

Name                    Version                   Build  Channel
_libgcc_mutex             0.1                        main

blas                      1.0                         mkl

bzip2                     1.0.8                h516909a_2    conda-forge
ca-certificates           2020.4.5.1           hecc5488_0    conda-forge
cairo                     1.16.0            hcf35c78_1003    conda-forge
certifi                   2020.4.5.1               py38_0

cudatoolkit               10.2.89              hfd86e86_1

cycler                    0.10.0                   pypi_0    pypi
dbus                      1.13.6               he372182_0    conda-forge
expat                     2.2.9                he1b5a44_2    conda-forge
ffmpeg                    4.2.3                h167e202_0    conda-forge
fontconfig                2.13.1            h86ecdb6_1001    conda-forge
freetype                  2.9.1                h8a8886c_1

gettext                   0.19.8.1          hc5be6a0_1002    conda-forge
giflib                    5.2.1                h516909a_2    conda-forge
glib                      2.64.3               h6f030ca_0    conda-forge
gmp                       6.2.0                he1b5a44_2    conda-forge
gnutls                    3.6.5             hd3a4fd2_1002    conda-forge
graphite2                 1.3.13            he1b5a44_1001    conda-forge
gst-plugins-base          1.14.5               h0935bb2_2    conda-forge
gstreamer                 1.14.5               h36ae1b5_2    conda-forge
harfbuzz                  2.4.0                h9f30f68_3    conda-forge
hdf5                      1.10.6          nompi_h3c11f04_100    conda-forge
icu                       64.2                 he1b5a44_1    conda-forge
intel-openmp              2020.1                      217

jasper                    1.900.1           h07fcdf6_1006    conda-forge
jpeg                      9c                h14c3975_1001    conda-forge
kiwisolver                1.2.0                    pypi_0    pypi
lame                      3.100             h14c3975_1001    conda-forge
ld_impl_linux-64          2.33.1               h53a641e_7

libblas                   3.8.0                    15_mkl    conda-forge
libcblas                  3.8.0                    15_mkl    conda-forge
libclang                  9.0.1           default_hde54327_0    conda-forge
libedit                   3.1.20181209         hc058e9b_0

libffi                    3.2.1             he1b5a44_1007    conda-forge
libgcc-ng                 9.1.0                hdf63c60_0

libgfortran-ng            7.3.0                hdf63c60_0

libiconv                  1.15              h516909a_1006    conda-forge
liblapack                 3.8.0                    15_mkl    conda-forge
liblapacke                3.8.0                    15_mkl    conda-forge
libllvm9                  9.0.1                he513fc3_1    conda-forge
libopencv                 4.2.0                    py38_6    conda-forge
libpng                    1.6.37               hbc83047_0

libstdcxx-ng              9.1.0                hdf63c60_0

libtiff                   4.1.0                h2733197_0

libuuid                   2.32.1            h14c3975_1000    conda-forge
libwebp                   1.0.2                h56121f0_5    conda-forge
libxcb                    1.13              h14c3975_1002    conda-forge
libxkbcommon              0.10.0               he1b5a44_0    conda-forge
libxml2                   2.9.10               hee79883_0    conda-forge
matplotlib                3.2.1                    pypi_0    pypi
mkl                       2020.1                      217

mkl-service               2.3.0            py38he904b0f_0

mkl_fft                   1.0.15           py38ha843d7b_0

mkl_random                1.1.1            py38h0573a6f_0

ncurses                   6.2                  he6710b0_1

nettle                    3.4.1             h1bed415_1002    conda-forge
ninja                     1.9.0            py38hfd86e86_0

nspr                      4.25                 he1b5a44_0    conda-forge
nss                       3.47                 he751ad9_0    conda-forge
numpy                     1.18.1           py38h4f9e942_0

numpy-base                1.18.1           py38hde5b4d6_1

olefile                   0.46                       py_0

opencv                    4.2.0                    py38_6    conda-forge
openh264                  2.1.1                h8b12597_0    conda-forge
openssl                   1.1.1g               h516909a_0    conda-forge
pcre                      8.44                 he1b5a44_0    conda-forge
pillow                    7.1.2            py38hb39fc2d_0

pip                       20.0.2                   py38_3

pixman                    0.38.0            h516909a_1003    conda-forge
pthread-stubs             0.4               h14c3975_1001    conda-forge
py-opencv                 4.2.0            py38h23f93f0_6    conda-forge
pyparsing                 2.4.7                    pypi_0    pypi
python                    3.8.1                h0371630_1

python-dateutil           2.8.1                    pypi_0    pypi
python_abi                3.8                      1_cp38    conda-forge
pytorch                   1.5.0           py3.8_cuda10.2.89_cudnn7.6.5_0    pytorch
qt                        5.12.5               hd8c4c69_1    conda-forge
readline                  7.0                  h7b6447c_5

setuptools                46.4.0                   py38_0

six                       1.14.0                   py38_0

sqlite                    3.31.1               h62c20be_1

tk                        8.6.8                hbc83047_0

torchvision               0.6.0                py38_cu102    pytorch
tqdm                      4.46.0                   pypi_0    pypi
wheel                     0.34.2                   py38_0

x264                      1!152.20180806       h14c3975_0    conda-forge
xorg-kbproto              1.0.7             h14c3975_1002    conda-forge
xorg-libice               1.0.10               h516909a_0    conda-forge
xorg-libsm                1.2.3             h84519dc_1000    conda-forge
xorg-libx11               1.6.9                h516909a_0    conda-forge
xorg-libxau               1.0.9                h14c3975_0    conda-forge
xorg-libxdmcp             1.1.3                h516909a_0    conda-forge
xorg-libxext              1.3.4                h516909a_0    conda-forge
xorg-libxrender           0.9.10            h516909a_1002    conda-forge
xorg-renderproto          0.11.1            h14c3975_1002    conda-forge
xorg-xextproto            7.3.0             h14c3975_1002    conda-forge
xorg-xproto               7.0.31            h14c3975_1007    conda-forge
xz                        5.2.5                h7b6447c_0

zlib                      1.2.11               h7b6447c_3

zstd                      1.3.7                h0b5b093_0

The code it gets stuck on in eval_DAVIS.py is as follows:-

print('Loading weights:', pth_path)
model.load_state_dict(torch.load(pth_path))

I am using Ubuntu 16.04, however I tried a similar setup in windows 10 and received the same error messages.

Any help much appreciated.

Kind regards

OneWorld