text:
Q: Django Model with API as data source I want to create a new model which uses the https://developer.microsoft.com/en-us/graph/graph-explorer api as a data source as i want to have additional info on the user.
Using a computed property on the model does not work as it is going to query for each instance in the set.
So, i want to have the model relate to a new model which has the api as it´s data source.
I could not find anything on this topic, besides maybe abusing the from_db()  method, if this even works.

A: It appears that what you're trying to do is to cache data from an external API that relates to, and augments/enriches, your user model data. If so, you can simply use a custom user model (instead of Django's default; this is a highly-recommended practice anyway) and then simply store the external API data in serialized form in a TextField attribute of your custom user model (let's call it user_extras; you can write model methods that serializes and deserializes this field for convenience upon access in your views).
The key challenge then is how to keep user_extras fresh, without doing something terrible performance-wise or hitting some constraint like API call limits. As you said, we can't do API queries in computed properties. (At least not synchronously.) One option then is to have a batch job/background task that regularly goes through your user database to update the user_extras in some controlled, predictable fashion.


text:
Q: Directive é executada 2 vezes Tenho a seguinte "directve":
app.directive('modal', ['$window', function ($window) {
return {
    restrict: 'C',
    link: function (scope, element, attrs) {
        scope.onResizeFunction = function() {
            console.log(attrs.id);
        };

        scope.onResizeFunction();
        angular.element($window).bind('resize', function() {
            scope.onResizeFunction();
            scope.$apply();
        });
    }
}
}]);

O que o código acima faz é executar a função "onResizeFunction" toda vez que a janela é redimensionada.
Dentro da função tenho "console.log" que faz o trace do ID do elemento.
Quando faço resize da janela, o ID aparece 2 vezes seguidas, ou seja, a função é executada 2 vezes, mesmo existindo apenas 1 elemento no HTML com a classe "modal", onde a "directive" é aplicada.

A: Diferentes browsers interpretam o evento de resize de maneiras diferentes. Alguns disparam um evento antes de iniciar o resize; outros, a cada evento de janela que transforma o viewport; outros, apenas quando o evento é finalizado - e vários implementam uma mistura dos três.
Uma das maneiras de evitar estes disparos contínuos é filtrar os eventos de acordo com uma janela de tempo:
var res;
window.onresize=function() {
    if (res){clearTimeout(res)};
    res = setTimeout(function(){console.log("resize triggered");},100);
};

Neste trecho de código, console.log só será invocado se nenhum outro evento de resize acontecer depois de 100 milisegundos.
Fonte do exemplo: https://stackoverflow.com/questions/15812618/window-onresize-fires-twice

redpajama_set_name: RedPajamaStackExchange


text:
Q: Puppet realizing defined users Mostly as a learning exercise, I'm trying to use defines to create users. There are no errors, but the user doesn't get created. Adding calls to notify makes me suspect the problem is the order of execution (but it may also be my newbness elsewhere). I'm using Puppet 2.7.9.
Here's my code.
    # manifests/nodes.pp
    node /song.*/ {
      include users
      User <| group == developers |>
    }

    # modules/users/manifests/init.pp
    class users {
      include users::people
    }

    # modules/users/manifests/people.pp
    class users::people {
      require groups
      @users::account { "michael":
          username => "michael",
          name     => "Michael C. Harris",
          uid      => 1000,
          gid      => "developers",
          password => '{encrypted password}',
          groups   => [ "wheel" ],
      }
    }

    # modules/groups/manifests/init.pp
    class groups {
      Group { ensure => present }
      group { "wheel":
        gid => 10;
      }
      group { "developers":
        gid => 1001;
      }
    }

    # modules/users/manifests/account.pp
    define users::account($ensure=present, managehome='true', allowdupe='false', homeprefix='/home', $username, $name, $password, $uid, $gid, $groups=[], $key='', $keytype='ssh-rsa', shell='/bin/zsh') {

      File { owner => $username, group => $username, mode => '0600' }

      $home = "${homeprefix}/${username}"

      user { $username:
        ensure     => $ensure,
        uid        => $uid,
        gid        => $gid,
        password   => $password,
        comment    => "$name",
        groups     => $groups,
        shell      => "$shell",
        home       => $home,
        require    => Group["$gid"],
        allowdupe  => $allowdupe,
        managehome => $managehome;
      }

      file { "$home":
        ensure => directory
      }
      if $key {
        file { "$home/.ssh":
            ensure => directory;
        }
        ssh_authorized_key { "$username":
          user    => $username,
          require => File["$home/.ssh"],
          key     => $key,
          type    => $keytype,
          ensure  => present;
        }
      }
    }

If this is a dependency issue, what's the best way to specify dependencies? Or am I doing something else wrong? General feedback would also be appreciated.

A: Puppet is probably not even trying to create the user, because you are making a virtual user::account resource (where you specify the "@"), but are only trying to realize a user resource (there are no virtual user resources).
Further, the filter group == developer would not match anything as there is no group attribute on either user, or user::account.
Try substituting User <| group == developer |> with Users::Account <| gid == developer |> and see if that helps.


text:
Q: How can a linq query be converted to JavaScript array containing only values? I have a JavaScript grid library (it creates a table on the page) that accepts a JavaScript array as input, for rendering in the grid.  I'm not certain, however, how to convert a Linq-to-SQL query (against a SQL Server database) to a JavaScript array containing only values.
I tried this, but it included the table column names in the JSON key (and I don't want JSON anyway, I want a JavaScript string array, unless this can be converted to an array?):
JsonConvert.SerializeObject(query)

Example of the format I need to produce:
[1,2,3],[4,5,6]

Environment: .NET Core 3.1
edit: Here is a sample of what I've currently got, this returns the less than desirable JSON (due to the query results being so large, having a JSON key for very element is going to literally double the size of the query):
Devices Table
ID   Name
1    iPhone7
2    iPhone8
3    iPhone9

Needed Array (Note: no column names)
[1, "iPhone7"],[2, "iPhone8"],[3, "iPhone9"]

Current C# code in the controller method (returns undesirable key for every element currently)
var query = db.Devices;
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);

A: Technically, you could do this:
var query = db.Devices.AsEnumerable()
    .Select(d => new object[]{d.ID, d.Name});
var formattedResult = JsonConvert.SerializeObject(query);
return Ok(formattedResult);

But then the code on the other end of your request is going to have to translate all those arrays back into objects.
It's rarely worthwhile to complicate your model like this in order to optimize the size of your network traffic. If you're pulling enough items over the wire to make this a performance issue, you're likely to encounter a variety of other performance issues. I would first consider other options, like implementing paging.

A: Did you try
var query = db.Devices.ToList();
var array = JArray.FromObject(query);
return Ok(formattedResult)


text:
Q: Celery beat_schedule works only after removing previous celerybeat-schedule files Celery beat_scheduler only works after removing below three files that are created by previous another beat_schedule task
rm celerybeat-schedule.bak
rm celerybeat-schedule.dat
rm celerybeat-schedule.dir

How could I run beat_scheduler without manual removal of such files generated previously?
Would it be related to authority?
FYI, I am running Celery through Python

A: I don't know whether you edit the celerybeat-schedule db manually.
In my case, I insert some data to db, worked fine in macos 10.15, but failed in ubuntu. error with _pickle.UnpicklingError: pickle data was truncated
So, after I insert my data to another db, such as celerybeat-schedule-{suffix}, I don't need remove this file manually anymore.


text:
Q: PHP PDO: SQL query not returning expected result I have a function (see bottom) in PHP, which queries a MySQL database.
When I use the following values:

*

*$map => 1,

*$limit => 10,

*$from => 0,

*$to => CURRENT_TIMESTAMP

With the SQL statement:
SELECT user,
       scoreVal AS score,
       UNIX_TIMESTAMP(timestamp) AS timestamp
  FROM Score
 WHERE timestamp >= :from
   AND timestamp <= :to
   AND map = :map
 ORDER BY scoreVal DESC, timestamp ASC
 LIMIT :limit

In phpMyAdmin, I get the following result:

However the PHP PDO gets returned an empty array.
My attempts to debug so far:

*

*I have replaced he prepared SQL query with static values instead of placeholders - Returns correctly

*Trying each placeholder separately, replacing the rest with tested hard-coded values - Returns nothing

*Instead of passing variables to placeholders I pass fixed constants in the execute(Array()) part. - Returns nothing.

*I have furthermore discovered after turning on mySQL query logs, that the PHP client Connects, but then quits without sending any queries.

From this, I believe it to be a problem with the place holders within the function, however I have been unable to find a reason why they are failing. This is most probably occurring on the PHP side, as no errors are being thrown by MySQL to the error file.
This is the function I am using, with the variables being passed in:

*

*$map => 1,

*$limit => 10,

*$from => 0,

*$to => 0

Function:
/**
 * Gets the highscore list for the map in that timespan
 * @param  integer $map   Id of map for which to fetch the highscore
 * @param  integer $limit Maximum no. of records to fetch
 * @param  integer $from  Timestamp from when to find rank
 * @param  integer $to    Timestamp up to when to find rank
 * @return array   Array of highscores arranged by rank for the map in the format [{"user"=>$user,"score"=>score,"timestamp" => timestamp}]
 */
function get_highscore_list($map,$limit,$from,$to){
    $sql = "SELECT user,scoreVal AS score,UNIX_TIMESTAMP(timestamp) AS timestamp FROM Score WHERE timestamp >= :from AND timestamp <= :to AND map = :map ORDER BY scoreVal DESC, timestamp ASC LIMIT :limit";
    if ($to==intval(0)){
        $max =1;
        $sql = str_replace(":to","NOW()",$sql,$max);
    }
    try{
    $conn = request_connection();
    $stmt = $conn->prepare($sql);
    $stmt->execute(array(':map'=>$map,':from'=>$from,':limit'=>$limit));
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }catch(PDOException $e){
        $_POST["exception"]=$e;
        continue;
    }
    return $result;
}

EDITS

Format of MySQL table:

I have tried outputting the $conn->errorInfo();, however as no error is being thrown, I get returned an array of values:
[00000,null,null]

The request_connection function only returns the result of this function, and it is working for all of my other statements.
/**
 * Creates a new PDO connection to the database specified in the configuration file
 * @author Ignacy Debicki
 * @return PDO A new open PDO connection to the database
 */
function create_connection(){
    try {
        $config = parse_ini_file('caDB.ini');
        $conn = new PDO('mysql' . ':host=' . $config['dbHost'] . ';dbname=' . $config['db'],$config['dbPHPUser'], $config['dbPHPPass']);
        date_default_timezone_set($config['dbTimezone']);
        return $conn;
    } catch(PDOException $e){
        throw new Exception("Failed to initiate connection",102,$e);
    }
}

Thanks

A: After many hours of trying, I have finally found my solution.
Two important statements that I had missed out from creating my connection are:
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

which turn on error reporting (See https://stackoverflow.com/a/8776392/2891273).
Once I turned this on, it was trivial to catch my problem, which was due to the overwriting of the :to parameter if $to was 0, the number of parameters passed in the $conn->execute() statement was mismatched with the number of parameters in the sql query.
My solution was to use $conn->bindValue() for each parameter instead, using an if statement to check if to bind to the :to parameter. Below is my solution:
function get_highscore_list($map,$limit,$from,$to){
    $sql='SELECT user, scoreVal AS score, UNIX_TIMESTAMP(timestamp) AS timestamp FROM Score WHERE map = :map AND timestamp >= :from AND timestamp <= :to ORDER BY scoreVal DESC, timestamp ASC LIMIT :limit';
    if ($to==0){
        $sql = str_replace(":to",'CURRENT_TIMESTAMP()',$sql);
    }
    $conn = request_connection();
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':map',$map,PDO::PARAM_INT);
    $stmt->bindValue(':from',$from,PDO::PARAM_INT);
    if ($to!=0){
        $stmt->bindValue(':to',$to,PDO::PARAM_INT);
    }
    $stmt->bindValue(':limit',$limit,PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}


text:
Q: python sort list of dicts by same key value count I have list of dicts, key 'city' could be repetitive. I need to sort this list from most repetitive city to least.
My list of dicts:
data = [
    {'city': 'Zp', 'p': 8},
    {'city': 'Kyiv', 'p': 2},
    {'city': 'Lviv', 'p': 7},
    {'city': 'Kyiv', 'p': 3},
    {'city': 'Kyiv', 'p': 4},
    {'city': 'Brd', 'p': 1},
    {'city': 'Kyiv', 'p': 5},
    {'city': 'Zp', 'p': 9},
    {'city': 'Lviv', 'p': 6},
]

I tried to sort by key value count, but got same result:
data = sorted(data, key=lambda x: data.count(x['city']))
# >> data
#     [
#       {'city': 'Zp', 'p': 8},
#       {'city': 'Kyiv', 'p': 2},
#       {'city': 'Lviv', 'p': 7},
#       {'city': 'Kyiv', 'p': 3},
#       {'city': 'Kyiv', 'p': 4},
#       {'city': 'Brd', 'p': 1},
#       {'city': 'Kyiv', 'p': 5},
#       {'city': 'Zp', 'p': 9},
#       {'city': 'Lviv', 'p': 6},
#     ]

This would give me almost needed result, but there is 2 objects with 'Lviv' and 2 with 'Zp', and they are mixed in result (also I think this approach requires too much resources)
data = sorted(
    data,
    key=lambda x: len(
        [i for i in data if i['city'] == x['city']]
    ),
    reverse=True
)
# >> data
#  [
#    {'city': 'Kyiv', 'p': 2},
#    {'city': 'Kyiv', 'p': 3},
#    {'city': 'Kyiv', 'p': 4},
#    {'city': 'Kyiv', 'p': 5},
#    {'city': 'Zp', 'p': 8},
#    {'city': 'Lviv', 'p': 7},
#    {'city': 'Zp', 'p': 9},
#    {'city': 'Lviv', 'p': 6},
#    {'city': 'Brd', 'p': 1},
#]

What I want to get:
# >> data
#    [
#        {'city': 'Kyiv', 'p': 2},
#        {'city': 'Kyiv', 'p': 3},
#        {'city': 'Kyiv', 'p': 4},
#        {'city': 'Kyiv', 'p': 5},
#        {'city': 'Lviv', 'p': 6},
#        {'city': 'Lviv', 'p': 7},
#        {'city': 'Zp', 'p': 8},
#        {'city': 'Zp', 'p': 9},
#        {'city': 'Brd', 'p': 1},
#    ]

A: from collections import Counter
from pprint import pprint

data = [
    {'city': 'Zp', 'p': 8},
    {'city': 'Kyiv', 'p': 2},
    {'city': 'Lviv', 'p': 7},
    {'city': 'Kyiv', 'p': 3},
    {'city': 'Kyiv', 'p': 4},
    {'city': 'Brd', 'p': 1},
    {'city': 'Kyiv', 'p': 5},
    {'city': 'Zp', 'p': 9},
    {'city': 'Lviv', 'p': 6},
]

# find the number of occurrences of each city
cities = map(lambda d: d['city'], data)
c = Counter(cities)

# sort data according to 1) frequency of the city, 2) name of the city
sorted_data = sorted(data, key=lambda d: (c[d['city']], d['city']), reverse=True)

pprint(sorted_data)

A: You need to sort by two keys here:

*

*the number of a city record occurrences in data (you need to extract the list of city names only for this)

*The city name for tie breaking

>>> sorted(
    data,
    key=lambda x: (list(y['city'] for y in data).count(x['city']), x['city']),
    reverse=True
)
[
    {'city': 'Kyiv', 'p': 2},
    {'city': 'Kyiv', 'p': 3},
    {'city': 'Kyiv', 'p': 4},
    {'city': 'Kyiv', 'p': 5},
    {'city': 'Zp', 'p': 8},
    {'city': 'Zp', 'p': 9},
    {'city': 'Lviv', 'p': 6},
    {'city': 'Lviv', 'p': 7},
    {'city': 'Brd', 'p': 1}
]


text:
Q: Objects to file:how to? public class Student {
    String name;
    int id;
    float grade;}

public class UndergraduateStudent  extends Student{
        float grade2;}

public class GraduateStudent  extends Student{
        float grade2,grade3;
        String supervizor;}

So I have the basic class Student which is extended to 2 more types.All the Student objects are stored in a SLL and now I have to store them into a file.How can I store them in the file if when extracted from the list,a cast to (Student) is done? I will need to get them back from the file so how will I know what type of student is each of the lines in the file?(I'm not interested for now in serialization)

A: FileOutputStream fos = new FileOutputStream("file.ext");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(student);
oos.close();

or simply save this object like plain text file (ex CSV)
John, 102, 4.5
Mark, 103, 2.0

A: You can convert your objects in xml and get your object back in from there.
Probably you can use XStream.

A: You have to make your class serializable
public class Student implements java.io.Serializable

Read the article - Java Serialization

A: What I was looking for was something like this:
public void writeTofile() throws IOException{

    File file = new File("./StudentRepo.txt");
    if (!file.exists())
        file.createNewFile();
    FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);

        Student[] copy = this.getStudents();
        for (Student st : copy){
            bw.write(st.toString() + "\n");
        }
        bw.close();
 }


text:
Q: The Relationship Between Cyclotomic Polynomials and Ramification I am thinking about why the cyclotomic polynomial $\Phi_n = \prod_{i \in \mathbb{Z}/n\mathbb{Z}^\times} (x - \zeta^i)$ is irreducible, where $\zeta$ is the $n$th root of unity over $\mathbb{Q}$. Specifically, I am trying to figure out how it is related to ramification and lifting the Frobenius element.
Let $f(x)$ be the minimal polynomial of $\zeta$. $f(x) | \Phi_{n}(x)$, and we want to show that we have an equality. It suffices to show that, for any root $\zeta$ of $f(x)$, $\zeta^p$ is a root of $f(x)$. Take a prime $p$ relatively prime to $n$, and a primitive root of unity $\zeta$ which is a root of $f(x)$.
Write $K = \mathbb{Q}(\zeta_n)$. Write $p \mathcal{O}_K = \prod_{i = 1}^n \mathfrak{q}_i^{e_i}$, where $e_i$ are the ramification indices. Write $f_i = [\mathcal{O}_K / \mathfrak{q}_i: \mathbb{F}_p]$. The automorphism $\sigma \in \text{Aut}_{\mathbb{Q}}(K)$ sending $\zeta$ to $\zeta^p$ is a lift for the Frobenius element in $\text{Aut}_{\mathbb{F}_p}(\mathcal{O}_K / \mathfrak{q}_i)$. It is also the unique one. See here.
Can someone explain the below paragraph in terms of ramification and lifting factorizations? The proof is standard as it is though.
$\sigma(\zeta) = \zeta^p$ is a root of $x^n - 1$. Write $x^n - 1= f(x) g(x)$ in $\mathbb{Z}[x]$. If $\zeta^p$ is a root of $g(x)$, then $g(x^p)$ has $f(x)$ as a factor, i.e. $g(x^p) = f(x) h(x)$. In $\mathbb{F}_p[x]$, we get $g(x)^p = f(x) h(x)$. This shows that $g(x)$ and $f(x)$ have a common factor in $\mathbb{F}_p[x]$, so that $x^n - 1$ has a multiple root in $\mathbb{F}_p[x]$, whereas it is separable by the standard derivation test.
I think something is going on in this last paragraph in terms of lifts of frobenius maps and ramification at $p$. Can someone explain this to me?


text:
Q: Lenovo Legion 5P Screen Brightness stuck at max I just got a new Lenovo 5p (15IMH05H) and got xubuntu on it
But the screen is stuck at max brightness and it just won't turn down
The controls works, it sets the values in /sys/class/backlight/ and setting those by hand doesn't help
In grub I tried

*

*setting acpi_osi to blank and to linux

*setting acpi_backlight to video vendor and native
Set values be hand with echo and tee , tried every combination of of the NVIDIA Prime video setting (discrete, on-demand, and intel)
I'm at my wit's end, and my retinas too. Anyone have any idea?


text:
Q: Openshift - Cannot connect to mysql with Java I am Harold and Im new in Openshift, Im using below code to connect to MySQL with java through example here
https://www.openshift.com/forums/openshift/no-suitable-driver-found-error,
Unfortunately, I was'nt able to make it work.
At first, it says "No suitable driver found" so I added the mysql-connector to WEB-INF/lib folder and add Class.forName("com.mysql.jdc.Driver");
Then, its not working and not showing error either.
Any help would highly appreciated
import java.lang.String;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;

public class someClass {

    public String databaseCall() {
        Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        String myVersion = "";

        String url = "jdbc:mysql://127.x.xxx.x:3306/testdb"; //make sure that this database name exists;
        String user = "admin";
        String password = "xxxxxxxxxxxxxxx";

        try {
            con = DriverManager.getConnection(url, user, password);
            st = con.createStatement();
            rs = st.executeQuery("SELECT VERSION()");

            if (rs.next()) {
                System.out.println(rs.getString(1));
                myVersion = rs.getString(1);
            }

        } catch (SQLException ex) {
            myVersion = ex.getMessage();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (st != null) {
                    st.close();
                }
                if (con != null) {
                    con.close();
                }

            } catch (SQLException ex) {
                myVersion = ex.getMessage();
            }
        }
        return myVersion;
    }
}

A: Try reading through this KB article on how to use the default mysql & postgresql connections provided by each Servlet or Application container: https://www.openshift.com/kb/kb-e1086-how-to-use-the-pre-configured-mysqlds-and-postgresqlds-data-sources-in-the-java


text:
Q: How to monitor bandwidth usage per process? I am using Ubuntu 14.04. My internet connection is pretty slow (512 kbps). Sometimes I see that I have no software running which should download anything from the internet, but the system monitor still shows that some download is going on. So I think some hidden software are causing this. Is there a way I can monitor every software that is using internet?

A: The iptraf utility is another way to monitor the traffic, provided by the iptraf  package. sudo apt-get install iptraf installs it.
iptraf is available in Red Hat Linux also; run yum install iptraf as root to install it.

A: Terminal tool:    netstat -tnp . -n option is to show numerical address (ip) to which connection is established, -p is program which has established that connection, and -t lists all tcplimits to tcp connections. Alternativelly, you could use netstat -a > networkscan.txt to output everything into a txt file

A: I prefer sudo netstat -tunap
vinny@vinny-Bonobo-Extreme:~$ sudo netstat -tunap
[sudo] password for vinny:
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:8200            0.0.0.0:*               LISTEN      1160/minidlnad
tcp        0      0 127.0.1.1:53            0.0.0.0:*               LISTEN      927/dnsmasq
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      2543/cupsd
tcp        0      0 192.168.2.10:58491      198.252.206.149:443     ESTABLISHED 30401/firefox
tcp        0      0 192.168.2.10:39824      173.194.219.189:443     ESTABLISHED 30401/firefox
tcp        0      0 192.168.2.10:58569      198.252.206.149:443     ESTABLISHED 30401/firefox
tcp        0      0 192.168.2.10:59283      173.194.219.18:443      ESTABLISHED 30401/firefox
tcp6       0      0 ::1:631                 :::*                    LISTEN      2543/cupsd
tcp6       1      0 ::1:60390               ::1:631                 CLOSE_WAIT  863/cups-browsed
tcp6       1      0 ::1:34718               ::1:631                 CLOSE_WAIT  1469/plasmashell
tcp6       1      0 ::1:60391               ::1:631                 CLOSE_WAIT  863/cups-browsed
udp        0      0 0.0.0.0:1900            0.0.0.0:*                           1160/minidlnad
udp        0      0 0.0.0.0:10097           0.0.0.0:*                           26759/dhclient
udp        0      0 0.0.0.0:5353            0.0.0.0:*                           759/avahi-daemon: r
udp        0      0 0.0.0.0:39609           0.0.0.0:*                           759/avahi-daemon: r
udp        0      0 192.168.2.10:57168      0.0.0.0:*                           1160/minidlnad
udp        0      0 127.0.1.1:53            0.0.0.0:*                           927/dnsmasq
udp        0      0 0.0.0.0:68              0.0.0.0:*                           26759/dhclient
udp        0      0 0.0.0.0:631             0.0.0.0:*                           863/cups-browsed
udp6       0      0 :::5353                 :::*                                759/avahi-daemon: r
udp6       0      0 :::13818                :::*                                26759/dhclient
udp6       0      0 :::39404                :::*                                759/avahi-daemon: r

shows even system proses that is using the network and the name of them.
but not really a monitor as you half to keep running it to see changing output.

A: You can use nethogs  tool to monitor all your traffic on an interface.
Install it using
sudo apt-get install nethogs

Now run it using
sudo nethogs <interface name>

For example
sudo nethogs wlan0

For more detail type man nethogs after installing.

A: Just a bit more comfort with netstat sudo watch -n1 netstat -tunap
It will refresh the data each 1s

A: Socket Statistics, ss
ss is the modern alternative to netstat.
sudo apt install iproute2  # Install

Usage example:
watch -n1 sudo ss -ntp  # Do not try to resolve service names. TCP. View processes

A: There is a more modern alternative to ss by now :)
ss2(pyroute)


text:
Q: Laravel Boilerplate and Bootstrap I have a question about Bootstrap and CoreUI on Laravel Boilerplate.
I've been trying to use some core features that are a part of Bootstrap by default, however, some things just don't work. Collapse, Modals, these features don't seem to be available. Is there something I'm missing? Some element that is customizable and needs to be loaded?
Any advice on where to look would be helpful as I'm having trouble even determining where to search for researching a solution.


text:
Q: Uso de ref en react, Cannot read property 'textInput' of undefined Estoy desarrollando un formulario de registro con React y quiero usar ref, sin envargo siempre me muestra un error en que esta no se puede leer.
 - Cannot read property 'textInput' of undefined.

import React,{Component} from 'react';
import './Registro.css';

export default class Registro extends Component {

  textInput = React.createRef();
  inputPasswordRef = React.createRef();
  inputPasswordConfirmRef = React.createRef();

  .......
   imprimir(e){
    e.preventDefault();
    const email = this.textInput;
    console.log(email);
  }
  ..........

  render() {
        return (
          <div className="login-block">
             <input type="text" className="form-control username" ref={this.textInput} placeholder="Email" autoComplete="username"  />

             .........

  <button type="submit" className="btn btn-success float-right" onClick={this.imprimir} >Registrarme</button>

A: Veo dos opciones, una que uses onClick={this.imprimir.bind(this)} para pasar como referencia el contexto de this a tu función.
Lo otro es que definas tu función como
imprimir = (e) => {

más información sobre el por qué de esto, revisa esta respuesta. Saludos


text:
Q: jQuery AJAX Posting values to another page in PHP I am trying to post values to another page in jquery ajax and php
This is my form in page1.php.
<form method="post" action="page1.php">
     Name : <input type="text" id="N_Txt">
     Email : <input type="text" id="Email_Txt">
     <input type="button" id="Sub_Btn" value="button">
</form>

This is my AJAX in page1.php
$(document).ready(function() {
     $('#Sub_Btn').click(function() {
         var nm = $('#N_Txt').val();
         var email = $('#Email_Txt').val();
         $.ajax({
             type:"POST",
             url:"page2.php",
             data:{ nm : nm , email : email },
             success:function(resp){
                console.log('success ajax');
             },
             error:function(resp){
                console.log('error ajax');
             }
         });
     });
});

This is my page2.php
<?php
   echo $_POST['nm'];
   echo $_POST['email'];
?>

Control is not even going to page2.php. How do i do it? I dont want to send values through query string window.location.
Thanks

A: You get a response and did you look into that
alert the response or you can check like this
 $(document).ready(function() {
         $('#Sub_Btn').click(function() {
             var nm = $('#N_Txt').val();
             var email = $('#Email_Txt').val();
             $.ajax({
                 type:"POST",
                 url:"page2.php",
                 data:{ nm : nm , email : email },
                 success:function(resp){
                    console.log(resp);
                 },
                 error:function(resp){
                    console.log(resp);
                 }
             });
         });
    });

A: If you like to echo your values in page2.php don't make an AJAX call. Just set action="page2.php" and forget your AJAX.
And on page2.php:
print_r($_POST);

A: put action="page2.php"
And your form in page1.php
<form method="post" action="page2.php">
     Name : <input type="text" id="N_Txt">
     Email : <input type="text" id="Email_Txt">
     <input type="button" id="Sub_Btn" value="button">
 </form>

And in your page2.php
print_r($_POST);

Thats it. You dont need a AJAX.


text:
Q: Составление массива Добрый день!
Есть база main в ней записаны записи и соответствующие им даты.
нужно составить массив с количеством записей по месяцам.
Array (
 [0] => January-2014/10,
 [1] => December-2013/12,
 [2] => November-2013/1,
)

Я составил массив с датами по месяцам
function all_date() {
    $query = mysql_query("SELECT `date` FROM `main` ".$AUTH." ORDER BY `date` DESC");
    $year_old = "0";
    for(;$row = mysql_fetch_assoc($query);) {
       $year_row = $row['date'];
       $year = date('F-Y',$year_row);
       if($year != $year_old){
          $year_old = $year;
          $_darr[] = $year;
       }
    }
    return $_darr;
}

Результатом выполнения вышеописанного кода:
Array
(
    [0] => January-2014
    [1] => December-2013
    [2] => November-2013
)

Теперь нужно к соответствующему месяцу добавить количество записей. Не могу сообразить как лучше дописать их. Если есть какие-нибудь идеи, прошу помочь.
P.S. January-2014 подобное написание нужно для дальнейшего составления BETWEEN в sql запросе.
P.P.S. Не знаю как правильно написать заголовок вопроса :(
A: Вашу проблему легко решить использованием group by в запросе:
SELECT date_format(date, "%M-%Y") AS MONTH, count(1) AS qty
    FROM main
    GROUP BY date_format(date, "%M-%Y")
    ORDER BY date DESC;

В итоге вы получите готовый результат из двух колонок - месяц и количество записей в месяце: http://sqlfiddle.com/#!2/6be27/2


text:
Q: Particle collision animation Python I'm trying to animate a particle collision animation in one axes object while simultaneously plotting some data in another axis object (using matplotlib.gridspec).
I set up a test environment with test data, simplifying the collision to just appearing circles in axes 1 (matplotlib.patches.Circle objects) and plotting a sine function in axes 2 (matplotlib.lines.Line2D object).
The animation works for one axes at a time, but I can't run both axes animations simultaneously.
I think the problem is related to the return objects in the init() and animate(i) function. The "matplotlib.patches" and "matplotlib.lines" object have problems in combination with the animation, but I can't figure out why.
Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib.animation import FuncAnimation
from matplotlib.gridspec import GridSpec

#%% setup test data
xy = (0.5, 0.5)
r = 0.02
i = np.arange(10,110)

#%% setup figure

fig = plt.figure(figsize = (8,8))
gs = GridSpec(6,4, figure=fig, wspace=0, hspace=0)

ax0 = fig.add_subplot(gs[0:4,0:4])

ax1 = fig.add_subplot(gs[5:6,0:4])
ax1.set_xlim(0,100)
# assigning labels
circles = []
ln1, = ax1.plot([],[], 'r')

def init():
    ln1.set_data([],[])
    circles = []
    return circles, ln1

def animate(i):

    xy = (np.random.random(), np.random.random())

    circles.append(ax0.add_patch(Circle(xy,r)))
    x = np.linspace(0,100,100)
    y = np.sin(x)

    mask1 = x < i
    x1 = x[mask1]
    y1 = y[mask1]

    ln1.set_data(x1, y1)

    return circles, ln1

ani = FuncAnimation(fig, animate, init_func=init, frames = i, blit=True, interval = 1)

plt.show()

That is the error message I  receive:
Traceback (most recent call last):
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 953, in _start
    self._init_draw()
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 1741, in _init_draw
    a.set_animated(self._blit)
AttributeError: 'list' object has no attribute 'set_animated'
Traceback (most recent call last):
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\cbook\__init__.py", line 216, in process
    func(*args, **kwargs)
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 1269, in _handle_resize
    self._init_draw()
  File "C:\Users\flofr\anaconda3\lib\site-packages\matplotlib\animation.py", line 1741, in _init_draw
    a.set_animated(self._blit)
AttributeError: 'list' object has no attribute 'set_animated'

I tried to test if the return values are correct for init() and it seems to be the case.
Input:

def init():
    ln1.set_data([],[])
    circles = []
    circles.append(ax0.add_patch(Circle(xy,r)))

    return ln1, circles

a, b = init()
print(a)
print(b)

Output:
Line2D(_line0)
[<matplotlib.patches.Circle object at 0x000001E7DE16F548>]

Here are the three states of the simulation. Imgage one shows the layout, image two the axes 1 simulation (circles) and image three the axes 2 simulation (sine).


text:
Q: Get variable from a asynchronous function I'm using the following javascript solution to get the number of pages of a file :
const reader = new FileReader()
reader.readAsBinaryString(file)
reader.onloadend = function () {
 const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
 console.log('Number of Pages:', count)
}

The number of pages is correct in the console but I don't know how to extract that number from the scope of the reader so I can use it elsewhere.
I've read How to return the response from an asynchronous call but I don't understand how to implement it for my case

A: Wrap it in a promise and resolve the value you want:

function getPageNumber() {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onloadend = function () {
       const count = reader.result.match(/\/Type[\s]*\/Page[^s]/g).length
       console.log('Number of Pages:', count);
      resolve(count);
    }
  }
}

getPageNumber().then(count => {
  // here, now you have count
});


text:
Q: Weighted sampling from multidimensional tensor I need to perform a weighted sampling of a multidimensional tensor.
I have a tensor A of shape [X,Y] and a distribution of probabilities B of shape [X].
I need to sample N elements from A according to the distribution B.
B represents the distribution of the subtensors. The sampling inside each subtensor is uniform.
There is some padding in A, so I have to take this into account. The information of what is a padding is contained in a mask.
e.g
A      = [[1,   2,   3,   X,   X,  X],
          [10,  20,  30,  X,   X,  X],
          [100, 200, 300, 400, 500, 600]]
A_mask = [[T,   T,   T,   F,   F,  F],
          [T,   T,   T,   F,   F,  F],
          [T,   T,   T,   T,   T,  T]]
B = [0.5, 0.4, 0.1]

# a possible output, with N = 10
ouput = [1, 1, 2, 2, 3, 10, 20, 30, 30, 200]

I'm able to retrieve the number of elements to sample from each nested tensor of A with:
tf.multinomial(tf.log(probability_distribution), N)

# a possible output of that function, with N = 10, is:
[1, 1, 1, 1, 1, 2, 2, 2, 2, 3]

For each one of these numbers, I must perform an uniform sampling in that subtensor.
I'm able to compute the maxvalue for each subtensor.
subtensor_sizes = tf.reduce_sum(tf.cast(A_mask, tf.int32), axis=1)

# it would return: [3, 3, 6]

At this point, for each subtensor returned by the multinomial function I should perform an uniform sampling between 0 and its maxvalue (or similarly, count the occurrences and sample T elements from a subtensor that appears T times in the output of the multinomial).
I'm not sure how to procede, how can this be done?

A: So you have a tensor A containing sequences of different lengths. You want to extract values out of those sequences, with different probabilities B to pick a value for each sequence.
You can proceed as follows:
import tensorflow as tf

A = tf.constant(
    [[1,   2,   3,   -1,  -1,  -1],
     [10,  20,  30,  -1,  -1,  -1],
     [100, 200, 300, 400, 500, 600]])
A_mask = tf.constant(
    [[True,   True,   True,   False,   False,  False],
     [True,   True,   True,   False,   False,  False],
     [True,   True,   True,   True,   True,  True]])
B = tf.constant([0.5, 0.4, 0.1])
subtensor_sizes = tf.reduce_sum(tf.cast(A_mask, tf.int32), axis=1)

# get random sample index
output = tf.to_int32(tf.multinomial(tf.log(B[None]), 10)[0])
# get corresponding sample size
output_sizes = tf.gather(subtensor_sizes, output)
# generate a random index in each range
random_idxs = tf.map_fn(
  lambda x: tf.random_uniform((), maxval=x, dtype=tf.int32), output_sizes)
# construct nd-index for tf.gather
random_ndxs = tf.concat([output[:, None], random_idxs[:, None]], axis=-1)
# get sample values
random_samples = tf.gather_nd(A, random_ndxs)


text:
Q: Print results of Active Record query I was wondering if someone could help me or point me to a tutorial to help me understand how to send the results of a rails query into a view? At the moment, I am only able to run a query using the console, but I'm not sure how to render the results into a view. For example, I have a model called City with the attributes state, population_size, and capital. For example, if I run a query in the console:
results = City.where(:state => 'Virginia')

How can I run that same query in Rails? Specifically, where would I place that code? Sorry for the noob question, but I can't find any guides that explicitly show me how to do this. I have only found guides on how to work in the console, but now how to actually render a view of the results...
Thanks!!

A: You can create the instance var to use it in your views
@results = City.where(:state => 'Virginia')

Now in your view you have access to @results

A: You can create the instance var to access it throughout the request.
if you want an array of results.
 @results = City.where(:state => 'stateName')

if you want a single object
 @result = City.find_by(state: 'stateName', id: :id)

Both can help you in different circumstances.
Now in your view you have access to @results


text:
Q: How to sort with conditions? I would like to sort a table by "number" only if the type is A
| number | type |
|--------|------|
| 1      |   A  |
| 2      |   B  |
| 3      |   B  |
| 4      |   A  |
| 5      |   A  |

the request would give :
| number | type |
|--------|------|
| 1      |  A   |
| 4      |  A   |
| 5      |  A   |
| 2      |  B   |
| 3      |  B   |

The rows with "A" type are sorted then the "B" rows are listed (no matter the order)
Is it possible to do it without UNION?

A: ORDER BY type, number will work:
SELECT number, type
FROM Tablename
ORDER BY type, number

Demo on SQL Fiddle
Note: ORDER BY type, here by default it will ordering the type values by the ascending order. It is equal to ORDER BY type ASC. As per your need, you may use DESC or ASC.

A: DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(number SERIAL PRIMARY KEY
,type CHAR(1) NOT NULL
);

INSERT INTO my_table VALUES
(1,'A'),
(2,'B'),
(3,'B'),
(4,'A'),
(5,'A');

SELECT * FROM my_table ORDER BY type,CASE WHEN type = 'A' THEN number ELSE RAND() END;
+--------+------+
| number | type |
+--------+------+
|      1 | A    |
|      4 | A    |
|      5 | A    |
|      3 | B    |
|      2 | B    |
+--------+------+

A: A CASE statement can help.
For "B" rows 'no matter the order'. Does that mean original order has to be retained? In that case following query can help.
select * from TableName
order by type, CASE WHEN type='A' THEN number ELSE 0 END

If original order need not be retained, then ELSE RAND() as answered by Strawberry is good.


text:
Q: Querying Large Table in sql server 2008 We have a table with 250 Million records (unique 15 digit number. Clustered Unique Index column) which will be queried at least by 0.7 to 0.9 Million requests on an average/day.
We have multi applications accessing this table. Each application will try to compare 500,000 data against this 260 Million records.
We have application that will add more data to this Large Table which is actually slowing down the querying of other applications.
How can we improve the performance of the query? How can we maintain this table? Partition it?
Environment: Win 2K8R2, SQL 2K8R2, 64GB RAM, Dual Processor 8 Cores

A: If multiple applications are only trying to compare data then i believe these are not writing to the table, caching records should help as well. Also there is technique called sharding which unfortunately SQL server doesnt provide it. But there is a library on codeplex that provides such a feature for SQL Server. It basically tries to balance load on databases.
I havent tested it but should worth a try. If you want you can see it here http://enzosqlshard.codeplex.com/

A: 1. Use temporary tables
Create temporary table on subset (rows and columns) of data you are interested in. Temporary table should be much smaller that original source table and can be indexed easily (if needed).
To create temporary table you can use code (not tested) like:
-- copy records from last month to temporary table
INSERT INTO
   #my_temporary_table
SELECT
    *
FROM
    er101_acct_order_dtl WITH (NOLOCK)
WHERE
    er101_upd_date_iso > DATEADD(month, -1, GETDATE())

-- run other queries on temporary table (which can be indexed)
SELECT TOP 100
    *
FROM
    #my_temporary_table
ORDER BY
    er101_upd_date_iso DESC

Pros:
Easy to do for any subset of data.
Easy to manage -- it's temporary and it's table.
Doesn't affect overall system performance like view.
Temporary table can be indexed.
Cons:
It's snapshot of data -- but probably this is good enough for ad-hoc queries.
2. Create views
Similar to above, but create views instead of temporary tables.
You can create views or indexed views on subset of data you are interested in and run queries on view -- which should contain only interesting subset of data much smaller then the whole table.
Pros:
Easy to do.
It's up to date with source data.
Cons:
Possible only for defined subset of data.
Could be inefficient for large tables with high rate of updates.
Not so easy to manage.
Can affect overall system performance.
Selecting all columns
Running star query (SELECT * FROM) on big table is not good thing...
If you have large columns (like long strings) it takes a lot of time to read them from disk and pass by network.
I would try to replace * with column names which you really need.
Or, if you need all columns try to rewrite query to something like:
;WITH recs AS (
    SELECT TOP 100
        id as rec_id -- select primary key only
    FROM
        er101_acct_order_dtl
    ORDER BY
        er101_upd_date_iso DESC
)
SELECT
    *
FROM
    er101_acct_order_dtl
WHERE
    id = rec.rec_id
ORDER BY
    er101_upd_date_iso DESC

Dirty reads
Last thing which could speed up the query is allowing dirty reads with table hint WITH (NOLOCK).
Instead of hint you can set transaction isolation level to read uncommited:
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED


text:
Q: PROTOBUFF INT64 check aganist previously entered data c++ message HealthOccurrenceCount
{
    required int64 HealthID=1;
    required int32 OccCount=2;
    optional bytes wci=3;
}

I would like to add data based on HealthID; If HealthID is already entered then instead of adding a new entry, the program should instead just increment the existing entry's OccCount.
HealthOccurrenceCount objHelthOccCount;
if(objHelthOccCount.healthid() == healthID) // Is this right or do I need to iterate all the nodes?
{
    occCount++;
    objHelthOccCount.set_occcount(occCount);
}
else
    occCount = 1;

Is this code correct or I should convert HealthID into string?
Generated Code:
// required int64 HealthID = 1;
inline bool has_healthid() const;
inline void clear_healthid();
static const int kHealthIDFieldNumber = 1;
inline ::google::protobuf::int64 healthid() const;
inline void set_healthid(::google::protobuf::int64 value);

A: According to the doc there is a has_ methods for each singular (required or optional) field which return true if that field has been set.
Your code would then be something like:
        HealthOccurrenceCount objHelthOccCount;
        if(objHelthOccCount.has_healthid())
        {
            occCount++;
            objHelthOccCount.set_occcount(occCount);
        }
        else
            occCount = 1;


text:
Q: webpack error when importing react-swiper when I try to import react-swiper from react, the webpack throws an error and I haven't found a solution for this one. Does anyone here knows how to resolve this error? Thanks in advance.
Error in Webpack images
and here's my webpack
webpack.config.js


text:
Q: Success response even if email will be not delivered For example, I have param {{name}} in my template. So, I have to pass this param in TemplateData of sendTemplatedEmail method.
But, if I don't, after sending request without this param I receive success response with RequestId and MessageId. And it looks like everything is fine. But it's not. This emails will be never delivered. They even aren't counted in Sending Statistics dashboard (https://console.aws.amazon.com/ses/home?region=us-east-1#dashboard:).
Is it a bug? If this is the expected behavior, how can we handle such cases?


text:
Q: Tuple from multiple values in a list How can I make multiple tuples from the first element with each of the values in the corresponding list?
desired outcome: [(0,727), (0,1), (0,766), (0,950)... ]
Thank you

A: A nested comprehension will work:
data = [(0, [727, 1, ...]), (1, [...]), ...]

tpls = [(x, y) for x, lst in data for y in lst]

A: You can use itertools.product which creates pairwise non-repeating combinations between two iterables.
from itertools import product

s_value = [[727, 1, 766], [989, 1067, 895], [21, 22, 23]]
c_keys = range(0, 3)

for c_key, s_val in zip(c_keys, s_value):
    print(list(product([c_key], s_val)))

>> [(0, 727), (0, 1), (0, 766)]
>> [(1, 989), (1, 1067), (1, 895)]
>> [(2, 21), (2, 22), (2, 23)]

If you want to create one big list with all combination tuples. You could add the flatten function of more-itertools
from more_itertools import flatten
from itertools import product

combs = [list(product([c_key], s_val)) for c_key, s_val in zip(c_keys, s_value)]
print(combs)
>> [[(0, 727), (0, 1), (0, 766)], [(1, 989), (1, 1067), (1, 895)], [(2, 21), (2, 22), (2, 23)]]

all_combs = list(flatten(combs))
print(all_combs)
>> [(0, 727), (0, 1), (0, 766), (1, 989), (1, 1067), (1, 895), (2, 21), (2, 22), (2, 23)]

A: You can try something like this...
lst = [(0,[0,1,2,3,4]),
        (1,[5,6,7,8,9])]

for key, value in lst:
    lst1 = [key] * len(value) # has a list of key repeated n times
    print(list(zip(lst1,value)))

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


text:
Q: Lightning Experience: Setting default value of "Record Owner" of Convert Lead page When the Convert Lead page loads, I would like to have the Record Owner field emptied out or the current user's name filled in by default. How can I do this?
I have read these solutions:

*

*https://success.salesforce.com/answers?id=90630000000CmlXAAS

*https://success.salesforce.com/ideaView?id=0873A000000E5bRQAS

*https://success.salesforce.com/answers?id=9063A000000ZnJzQAK
, but all of them involved in calling the Classic Convert Lead page, like creating custom buttons/links or VisualForce page redirecting users to the Classic Convert Lead page.
Is there any way to do this in Lightning Experience, or am I limited to those solutions?
Thanks in advance!
ps. Custom Buttons don't show up in Lightning Experience.

A: You can use a custom button to redirect to a custom lightning app and in apex use database.convertlead
If your only intention to set the owner on the conversion then

*

*Hide the standard owner field from the UI

*Create a formula field which shows current user and show that on the
UI.

*User process builder or workflow to populate owner

hope this will cover your requirement.


text:
Q: Most common cassandra cql commands I am looking at exploring optimization of cassandra for a limited set of commands. For that I wanted to know which among SELECT,  INSERT, UPDATE, DELETE & BATCH is the CQL command with highest frequency of use in realtime systems. Any pointers and thoughts on this would be great help.

A: There is no such thing as common cql commands, it all depends for which use case cassandra is deployed.
So Instead of optimizing commands  you could go for Use Case based optimization:
Eg: UseCase: Write oriented Workload:
Optimize Insert and Update commands.


text:
Q: C# LINQ: How is string("[1, 2, 3]") parsed as an array? I am trying to parse a string into array and find a very concise approach.
string line = "[1, 2, 3]";
string[] input = line.Substring(1, line.Length - 2).Split();
int[] num = input.Skip(2)
                 .Select(y => int.Parse(y))
                 .ToArray();

I tried remove Skip(2) and I cannot get the array because of non-int string. My question is that what is the execution order of those LINQ function. How many times is Skip called here?
Thanks in advance.

A: The order is the order that you specify. So input.Skip(2) skips the first two strings in the array, so only the last remains which is 3. That can be parsed to an int. If you remove the Skip(2) you are trying to parse all of them. That doesn't work because the commas are still there. You have splitted by white-spaces but not removed the commas.
You could use line.Trim('[', ']').Split(','); and int.TryParse:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int i = 0;
int[] num = input.Where(s => int.TryParse(s, out i)) // you could use s.Trim but the spaces don't hurt
                 .Select(s => i)
                 .ToArray();

Just to clarify, i have used int.TryParse only to make sure that you don't get an exception if the input contains invalid data. It doesn't fix anything. It would also work with int.Parse.
Update: as has been proved by Eric Lippert in the comment section using int.TryParse in a LINQ query can be harmful. So it's better to use a helper method that encapsulates int.TryParse and returns a Nullable<int>.  So an extension like this:
public static int? TryGetInt32(this string item)
{
    int i;
    bool success = int.TryParse(item, out i);
    return success ? (int?)i : (int?)null;
}

Now you can use it in a LINQ query in this way:
string line = "[1, 2, 3]";
string[] input = line.Trim('[', ']').Split(',');
int[] num = input.Select(s => s.TryGetInt32())
                 .Where(n => n.HasValue)
                 .Select(n=> n.Value)
                 .ToArray();

A: The reason it does not work unless you skip the first two lines is that these lines have commas after ints. Your input looks like this:
"1," "2," "3"

Only the last entry can be parsed as an int; the initial two will produce an exception.
Passing comma and space as separators to Split will fix the problem:
string[] input = line
    .Substring(1, line.Length - 2)
    .Split(new[] {',', ' '}, StringSplitOptions.RemoveEmptyEntries);

Note the use of StringSplitOptions.RemoveEmptyEntries to remove empty strings caused by both comma and space being used between entries.

A: I think it would be better you do it this way:
JsonConvert.DeserializeObject(line, typeof(List<int>));

A: you might try
    string line = "[1,2,3]";
    IEnumerable<int> intValues = from i in line.Split(',')
                                 select Convert.ToInt32(i.Trim('[', ' ', ']'));


text:
Q: Update directive on callback? I have a google maps-directive that shows the travelling from one location to another.
During the application run, I ask the user for permission and add the current location to the scope:
if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function(position) {
        $rootScope.myLocation = {}
        $rootScope.myLocation.lat = position.coords.latitude;
        $rootScope.myLocation.long = position.coords.longitude;
        $rootScope.$apply()
    });
}

On some views, I generate a google map with a directive, based on the current location:
<g-map id="transit" origin="{{myLocation.lat}},{{myLocation.long}}" destination="{{location.lat}},{{location.long}}" type='TRANSIT' class="map"></g-map>

The problem is that if the map is generated before the user approves the location-request, google maps responses with an error (as there is no origin-location). What I want to do is have a default location as my origin, and update the google map on the callback from the browser location-api.
Is there something like a directive method that I could use? Here is my directive:
directive('gMap', function(){
return{
    restrict: 'E',
    replace: true,
    scope: {
        origin: '@origin',
        destination: '@destination',
    },
    template: "

",
    link: function(scope, element, attrs){
        var directionsService = new google.maps.DirectionsService();
        var directionsDisplay = new google.maps.DirectionsRenderer();

        var map = new google.maps.Map(document.getElementById(attrs.id), {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        });
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById('panel'));
        var request = {
            origin: attrs.origin,
            destination: attrs.destination,
            travelMode: google.maps.DirectionsTravelMode[attrs.type]
        };

        directionsService.route(request, function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }else(
                console.log(status)
            )
        });
    }
};

}

A: Well, first of all don't use things like this: origin="{{myLocation.lat}},{{myLocation.long}}". It's weird. That's because you never know how and when your attributes are calculated and updated. You can have different incorrect values for this. Also you need to correctly track such attributes.
Much better way is to use bi-directional binding on the scope attributes and pass the data as objects there:
<g-map id="transit" origin="myLocation" destination="location" type='TRANSIT' class="map"></g-map>

In this case you will have the directive declared as
...
scope: {
    origin: '=',
    destination: '=',
}
...

And you can have the default location specified.
Then you can easily watch over the origin and update the result.

A: Set up the default values before calling getCurrentPosition()...
$rootScope.myLocation = {lat: 47, long: 120};
if ("geolocation" in navigator) {
    navigator.geolocation.getCurrentPosition(function(position) {
        $rootScope.myLocation.lat = position.coords.latitude;
        $rootScope.myLocation.long = position.coords.longitude;
        $rootScope.$apply()
    });
}

Inside link in the directive, set up a watch on origin and destination...
function updateMap (newValue) {
    // move your map update code here and position the map to newValue
}
scope.$watch('origin', updateMap);
scope.$watch('destination', updateMap);

Simplified example here... http://jsbin.com/sanuhoje/1/edit?html,js,output


text:
Q: Stacked distribution graph (possibly in python) I would like to draw graphs like this (Sorry, I was not able to upload the picture)
http://www.organizationview.com/wp-content/uploads/2011/01/Stacked-distribution.jpg
Which software can do this? Is there any python utilities that can do this?

A: I made you a working matplotlib example. I only made three components per bar-chart. Adding two more for the five total in your example is left as an exercise to the reader. :) The code is quoted down below. You can also see it live or download my IPython notebook: http://nbviewer.ipython.org/5852773
import numpy as np
import matplotlib.pyplot as plt

width=0.5

strong_dis = np.array((20, 10, 5, 10, 15))
disagree = np.array((20, 25, 15, 15, 10))
# shortcut here
therest = np.subtract(100, strong_dis + disagree)

q = np.arange(5)

bsd=plt.barh(q, strong_dis, width, color='red')
bd=plt.barh(q, disagree, width, left=strong_dis, color='pink')
br=plt.barh(q, therest, width, left=strong_dis+disagree, color='lightblue')

ylabels = tuple(reversed(['A', 'B', 'C', 'D', 'E']))
plt.yticks(q+width/2., ylabels)

plt.xlabel('Responses (%)')
plt.legend((bsd, bd, br), ('strong disagree', 'disagree', 'the rest'))
plt.show()

A: The matplotlib library can be used for generating graphs in Python.
http://matplotlib.org/

A: Have a look at matplotlib. They have an examples section, which includes a stacked bar chart.


text:
Q: Where is the Vanguard Armory? In Destiny, if you pre-ordered, you get "early access to the Vanguard Armory."  Where is this, and what benefits does it impart upon the player?

A: The Vanguard Armory is by the shipwright on the Tower. Go to the right when you first spawn and it's down that hallway.
The early access thing is a series of level 10 items that vary depending on your class. They're pretty good but by no means super amazing. When I hit level 10 I had only one gear piece that I bought there.
Note: You can talk to the robots hanging out in the Tower to see a map of the area. You can also use the Destiny Companion App to have a map and do other cool things like mess with your gear and read the grimoire cards.

A: [Disclaimer: I have not played Destiny. All information in this post is gained through secondary sources.]
According to the official website, the Vanguard Armory grants access to upgraded weapons. If you pre-ordered, you should find several vendors around the game that you can use Glimmer (the game's currency) to purchase. One of these vendors is located near the shipwright.
Although the official website only lists flavour texts for the "upgraded weapons" the Vanguard Armory gives, we can find more details about these weapons by looking them up on the Destiny wiki. For instance, one of the weapons the Armory gives is the Carte Blanche S.1, which is supposedly pretty powerful. 67 damage sounds like a lot I suppose, compared to the 36 of the standard rifles.
Note that Bungie's website says at the bottom:

Access to Vanguard Armory can also be attained through gameplay.

This probably means that the Vanguard Armory weapons can also be found if you do not preorder, but they will more difficult to find.


text:
Q: Facebook like button not showing like count [firefox] I have a facebook like button in my blog using html5 but it doesn't display the count for visitors who didn't like. When someone hits the button, it displays 1 like (even though I tested with multiple facebook users liking it. (the like works, and it does appear on facebook.com)
tested in 3 different browsers.
this is the code I used:

<div style="float: left;margin-left: 40px;" class="fb-like"  data-href="http://www.xxxxxx.com/?p=<?php the_ID(); ?>"  data-send="false" data-layout="button_count" data-width="100" data-show-faces="true" data-font="segoe ui">

EDIT: I think the problem is with firefox. when i like the page from firefox - doesn't show in other browsers. when i like from chrome or safari - shows in all except firefox.

A: I had the same issue, but what I figured out is, its because of caching of FB as when I like anything from Firefox then at the same time it dosent shows the count, but next day you will see all the shares and like. Am on wordpress.


text:
Q: Can't update Windows 2008 server with WSUS installed on it I have installed WSUS on my Windows 2008 server. My issue is the following:
I get the error message: Windows could not search for new updates (80244019)

*

*I can get updates from WSUS.

*I tried almost everything on google but can't afford some since it's a production server.

I am wondering if I need to add my 2008 server in my updating list in WSUS. Download updates from WSUS and at the sime time, update the server itself.
Do you guys know if it's possible to download updates without WSUS for my 2008 server?
No Windows Firewall enabled.
No Antivirus software installed.
If you need more info, please let me know.
Regards,
D.

A: I will assume you are in a Active Directory environment. When I set up my WSUS on a Win 2003 server, I also had to put out a little piece of group policy that Allowed Automatic Updates, and set the intranet update server to my local server. This is found in Computer Configuration>Windows Components>Windows Update. I don't know if this has changed at all. Have you pointed your systems to the local WSUS server?

A: If the 2008 server is running the WSUS server software, then WSUS handles the download of updates to its repository internally. You can check the status of this from the WSUS server console under Administrative Tools.
For the underlying server itself, it behaves just like any other client server and will talk to the WSUS installation to obtain its updates. It should show up just like any other client on the WSUS console.
If the problem is with WSUS itself not being able to obtain updates from the internet, run through the WSUS server configuration wizard (via the WSUS console) and there's a step that should test the connection out to the Internet. Problems here are usually due to firewall restrictions between the server and the Internet.
If the problem is with the server OS getting updates from the WSUS install, check the WSUS event log in c:\Windows\SoftwareDistribution\ and see if there's any more info about the error there.
If you want to reconfigure the server to go directly to Microsofts update service, and ignore the local WSUS service, edit the update settings in the registry under:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Win dows\WindowsUpdate\AU
To reset this you can delete the AU key, and it will be re-initialised on a reboot.
If none of this solves the issue, next questions would be:

*

*How is the server 'tied' to the WSUS server? Via a group policy, or manually via a registry entry or the command line?

*What's the last 10 lines of reportingevents.log in c:\windows\softwaredistribution

A: Well, as I thought, the only way to update my 2008 server is by adding it to the WSUS updating list. A WSUS server cannot updates itself thru WindowsUpdate.com but only thru WSUS.

A: You are missing a Windows update - kb2720211.  Either install it manually or remove the WSUS group policy from the server, gpupdate /force, and then run Windows Updates.


text:
Q: Configure Sendmail to forward NSU to different server? Is it possible to configure Sendmail to forward the message to another server instead of returning it as NSU (no such user)?
We are in the process of migrating from a sendmail server to Exchange 2010. Due to various reasons it is impossible to cut over the entire domain at once. (600 mailboxes, 21 locations full of people who often have trouble even turning a PC on, and only 3 support staff to hold hands)
We are also changing our email address format at the same time, so this is the plan in my head:
-We create the mailboxes on Exchange using the new format of first.last addresses (roy.urick@) but DON'T create the current aliases yet, currently rurick@. (Creating the aliases of the current production email addresses would cause delivery issues between new exchange mailboxes and not yet migrated users as ALL of the mail from exchange users would stay local and not be delivered to the old mailboxes)
-We would configure our current sendmail server to somehow NOT return no such user (NSU) errors but instead forward the message to the Exchange server for further processing.
-On the old server we would .forward the old mailbox (rurick) to the new (roy.urick) address as we migrate each user by hand.
-When a message is received at the old server for roy.urick (or any other nonexistent mailbox) it would be forwarded to Exchange (and that server would determine whether it should be delivered or returned as NSU).
-If the message was for rurick@, the .forward would take over and the previous step would happen.
-Then eventually once all of the mailboxes were migrated, we would update the aliases on the new server to make the old addresses work, shut down the old server and change the MX record to the new server.
Any other suggestions?

A: In your sendmail.mc add:
define(`LUSER_RELAY', `[some.other.server]')dnl

Then rebuild your sendmail.cf and restart sendmail. In Debian I do this by running sendmailconfig. Other Operating Systems and Distributions have different ways of doing this.


text:
Q: Extracting a variable length sub-string using pyparsing I'm trying to get pyparsing to extract a sub-string consisting of a variable number of words from a string.
The following almost works but loses the last word of the sub-string:
text = "Joe F Bloggs is the author of this book."
author = OneOrMore(Word(alphas) + ~Literal("is the"))

print author.parseString(text)

Output:
['Joe', 'F']

What am I missing?
PS: I know I can do this with a regular expression but specifically want to do it with pyparsing because it needs to fit into a large effort already written using pyparsing.

A: Your negative lookahead has to come before the actual author word:
>>> author = OneOrMore(~Literal("is the") + Word(alphas))
>>> print author.parseString(text)
['Joe', 'F', 'Bloggs']


text:
Q: ng-message inside md-autocomplete shows with wrong style and overlaps the input field I have an md-autocomplete with ng-messages inside of it:
<md-autocomplete flex required="required"
     md-input-name="player"
     md-input-minlength="0"
     md-autoselect="true"
     md-select-on-match="true"
     md-selected-item="item.player"
     md-item-text="player.name"
     md-search-text="playerSearchText"
     md-items="player in filterPlayerItems(playerSearchText)"
     md-no-cache="true"
     md-floating-label="Select Player">

     <md-item-template>
          {{player.name}}
     </md-item-template>

This is required.

</md-autocomplete>

The md-autocomplete is inside a form, and everything works well, besides the fact that the error message is overlapping the input field and the label:

When checking the DOM I found that inside the <md-autocomple-wrap> there is a <md-input-container> with a flex class:

and if I remove that class the message goes down to its proper place:

I can see the md-autocomplete example on angular-material demo is working well and I am following their example.
What am I missing here?


text:
Q: Delete files and subfolders in the folders "tmp" and "cache" I want to use this script below to clean out "tmp" and "cache" folders in websites like "C:\Storage\Websites\Site1".
It tries to delete files and subfolders in "C:\Storage\Websites\Site1\tmp" and "C:\Storage\Websites\Site1\cache".
Which is right, but it also tries to delete files and subfolders in, for example, "C:\Storage\Websites\Site1\MySpecialLittleProgram\tmp" and, for example, "C:\Storage\Websites\Site1\MySpecialLittleProgram\cache".
Which is wrong. It should only clean up the "tmp" and "cache" folder in the root of the website and not in other subfolders.
If I delete the /s parameter in 'dir /a:d /b /s tmp cache' it will not find anything.
How can I do this part?
(I have deleted the /q parameter in the file deleting part and the folder removing part if anyone copies my script.)
@echo off

call:CleanUp "C:\Storage\Websites"

echo.&pause&goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:CleanUp
    IF EXIST %~1 (
        cd /d %~1
        FOR /f "tokens=*" %%i in ('dir /a:d /b /s tmp cache') DO (

            echo %%i

            ::DELETING FILES I FOLDERS AND SUBFOLDERS
            del %%i /s

            ::DELETING NOW EMPTY FOLDERS AND SUBFOLDERS
            FOR /D %%p IN ("%%i\*.*") DO rmdir "%%p" /s
        )
    )
goto:eof

UPDATE:
I updated my code to be (it is working now):
@echo off

call:CleanUp "C:\Storage\Web"
call:CleanUp "C:\Storage\Web-IIS"

goto:eof

::--------------------------------------------------------
::-- Function section starts below here
::--------------------------------------------------------

:CleanUp
IF EXIST %~1 (
   cd /d %~1

   FOR /f "tokens=*" %%i in ('dir /a:d /b') DO (
      IF EXIST %%i\tmp (
         del %%i\tmp /s /q
         FOR /D %%p IN ("%%i\tmp\*.*") DO rmdir "%%p" /s /q
      )

      IF EXIST %%i\cache (
         del %%i\cache /s /q
         FOR /D %%p IN ("%%i\cache\*.*") DO rmdir "%%p" /s /q
      )
   )
)
goto:eof

A: This should remove the files in those two locations:
@echo off
del "C:\Storage\Websites\Site1\tmp\*.*" /a /s
del "C:\Storage\Websites\Site1\cache\*.*" /a /s

From your comment, this may be what you need to do: remove the echo keyword after testing it to see the commands on the console that would be executed.
@echo off
cd /d "C:\Storage\Websites"
for /d %%a in (*) do (
   for %%b in (tmp cache) do (
      pushd "%%~fa\%%b" 2>nul && (echo rd /s /q "%%~fa\%%b" 2>nul & popd)
   )
)
pause

A: I suggest to use rmdir or rd for this task:
rd "C:\Storage\Websites\Site1\tmp" /S /Q
md "C:\Storage\Websites\Site1\tmp"

rd "C:\Storage\Websites\Site1\cache" /S /Q
md "C:\Storage\Websites\Site1"

Command rd with options /S for all subdirectories and /Q for quiet deletes also tmp and cache, but those 2 directories can be easily recreated using command md although I'm quite sure that this would not be really necessary here as the application creating tmp and cache would do it also automatically.
If that is not what you want, please show as directory listings with files and folders in one of the two directories before cleanup and after cleanup.


text:
Q: how can I calculate $\lim\limits_{z \to 0} {\exp(-1/z^4)}$?
$\lim\limits_{z \to 0} {\exp(-1/z^4)}$

It may be easy but i'm not sure it's correct.
the answer that i got was 0.

A: The answer is not 0. This limit is not well defined. To prove it one must show that it takes different values for different sequences converging to zero. Take, say
$$\{z_n\} = e^{i\pi/4}n^{-1},$$ as $n \rightarrow \infty$. The other sequence you can find easily.
Actually, this limit will take all complex values except at most one, but this is another story.


text:
Q: how open file system's GUI-window through terminal is there any shell command that open file system's GUI-window of the terminal's current working directory?

A: Just type:
/usr/bin/gnome-open .

Note the spce-dot at the end, where the dot represents the current directory. I actually created a symlink called run, so I can easily open anything from the command line (folders, random files, etc.).
Update:
On newer versions of Gnome, this seems to have been replaced by xdg-open. In fact, libgnome2-bin, the package needed to install gnome-open, is not available for Ubuntu 19.10. Here is the new version:
/usr/bin/xdg-open .


text:
Q: How to read password protected PDF file in Nodejs and get it in buffer? I tried using pdfjs-dist.
getting large json response.
var PDFJS=require('pdfjs-dist');
PDFJS.getDocument({ url: 'p1.pdf', password: '' }).then(function(pdf_doc)
{
console.log(pdf_doc);
}).catch(function(error) {
// incorrect password

// error is an object having 3 properties : name, message & code
});

Response
This is the whole response I am getting.
but I need response in buffer.
Can it be converted to buffer.
    PDFDocumentProxy {
    loadingTask:
    { _capability:
     { resolve: [Function], reject: [Function], promise: [Promise] },
 _transport:
  WorkerTransport {
    messageHandler: [Object],
    loadingTask: [Circular],
    commonObjs: [Object],
    fontLoader: [GenericFontLoader],
    _params: [Object],
    CMapReaderFactory: [DOMCMapReaderFactory],
    destroyed: false,
    destroyCapability: null,
    _passwordCapability: null,
    _networkStream: [PDFNodeStream],
    _fullReader: [PDFNodeStreamFsFullReader],
    _lastProgress: [Object],
    pageCache: [],
    pagePromises: [],
    downloadInfoCapability: [Object],
    numPages: 4,
    pdfDocument: [Circular] },
 _worker:
  { name: null,
    destroyed: false,
    postMessageTransfers: true,
    verbosity: 1,
    _readyCapability: [Object],
    _port: [LoopbackPort],
    _webWorker: null,
    _messageHandler: [Object] },
 docId: 'd0',
 destroyed: false,
 onPassword: null,
 onProgress: null,
 onUnsupportedFeature: null },
 _pdfInfo:
 { numPages: 4,
 fingerprint: '3432353738363537336c6e665361446f6f744f4a70' },
_transport:
  WorkerTransport {
 messageHandler:
  { sourceName: 'd0',
    targetName: 'd0_worker',
    comObj: [LoopbackPort],
    callbackId: 1,
    streamId: 1,
    postMessageTransfers: true,
    streamSinks: [Object],
    streamControllers: [Object: null prototype] {},
    callbacksCapabilities: [Object: null prototype] {},
    actionHandler: [Object],
    _onComObjOnMessage: [Function] },
 loadingTask:
  { _capability: [Object],
    _transport: [Circular],
    _worker: [Object],
    docId: 'd0',
    destroyed: false,
    onPassword: null,
    onProgress: null,
    onUnsupportedFeature: null },
 commonObjs: { objs: [Object: null prototype] {} },
 fontLoader:
  GenericFontLoader {
    docId: 'd0',
    nativeFontFaces: [],
    styleElement: null,
    loadingContext: [Object],
    loadTestFontId: 0 },
 _params:
  [Object: null prototype] {
    url: 'p1.pdf',
    password: '',
    rangeChunkSize: 65536,
    CMapReaderFactory: [Function: DOMCMapReaderFactory],
    ignoreErrors: true,
    pdfBug: false,
    nativeImageDecoderSupport: 'none',
    maxImageSize: -1,
    isEvalSupported: true,
    disableFontFace: true,
    disableRange: false,
    disableStream: false,
    disableAutoFetch: false,
    disableCreateObjectURL: false },
 CMapReaderFactory: DOMCMapReaderFactory { baseUrl: null, isCompressed: false },
 destroyed: false,
 destroyCapability: null,
 _passwordCapability: null,
 _networkStream:
  PDFNodeStream {
    source: [Object],
    url: [Url],
    isHttp: false,
    isFsUrl: true,
    httpHeaders: {},
    _fullRequest: [PDFNodeStreamFsFullReader],
    _rangeRequestReaders: [Array] },
 _fullReader:
  PDFNodeStreamFsFullReader {
    _url: [Url],
    _done: false,
    _storedError: null,
    onProgress: [Function],
    _contentLength: 112979,
    _loaded: 112979,
    _filename: null,
    _disableRange: false,
    _rangeChunkSize: 65536,
    _isStreamingSupported: true,
    _isRangeSupported: true,
    _readableStream: [ReadStream],
    _readCapability: [Object],
    _headersCapability: [Object] },
 _lastProgress: { loaded: 112979, total: 112979 },
 pageCache: [],
 pagePromises: [],
 downloadInfoCapability:
  { resolve: [Function], reject: [Function], promise: [Promise] },
 numPages: 4,
 pdfDocument: [Circular] } }
                                                                                *ignore below text*

efwrg rgsretg resgerstgh;ergh ;resjgysregh regjes powrjgu oiuueryoeq uieqroeqreqrilih ehr oiyeroeq ioiyeqroeq oieyqrioeq oieqyr oiyeqr oiyeqrp ioqyet oiehr oiyerh oieyreq oiyheqri iohereqk ioheqr qerioyqereq ioehqriheq rioqehriqeb ioeqrhpeq ioeqrhiqe ioqehriq ioqerhioq oirhqeipor oiqehrieq ioehqrq ioeqhrieq iohqerpq ieqhrpeq ioeqhrpeq iheqrpqe oiehrpqe ieqhrqierh ioeqhr ieqhr ioeqrh piqerh ieqhr iheqr piheqr ioheqr iheqr ioeqhrp ioqhre oieqhr oeqiyr qoeiryf pouqer poqure pouqr pouqre[q poquerq poqeur[q poqeur poqwuer poquer[ poqwur[wq poqr[ poqwhr powrq pow

A: You may open and read a password protected PDF like below. Working with your existing code:
var PDFJS = require('pdfjs-dist');
PDFJS.getDocument({ url: 'p1.pdf', password: '' }).then(function(pdf)
{
  let text = [];
  for(let i = 1; i <= pdf.numPages; i++) {
    pdf.getPage(i).then(function(page) {
      page.getTextContent().then(function(data) {
        for(let j = 0; j < data.items.length; j++) {
          text.push(data.items[j].str);
        }
      });
    });
  }

}).catch(function(error) {
// incorrect password

// error is an object having 3 properties : name, message & code
});


text:
Q: How to make a regular expression for given kind of String? How to write the regular expression for below kind of String such that I  get response in below format ?
"abc, -xyz, lmn, qwe,-yui"

Basically I need to parse above string in List<String> as
abc, -xyz
lmn
qwe, -yui

Below code is working fine when there is exactly one space before hyphen(-) ex:
"abc, -xyz"

but not working when there is no or more than one space, ex:
"abc,  -xyz"

Regular expression I tried:
List<String> items = Arrays.stream(order.split("(?!, -),")).map(String::trim).map(String::toLowerCase).collect(Collectors.toList());

Please provide the code which parse with any number of spaces and also explain the logic for the same.

A: Instead of splitting your string you can actually find all results using "(.+?)". This finds all string between ". Here is the full example:
String input = "\"abc, -xyz\", \"lmn\", \"qwe,-yui\"";
Pattern pattern = Pattern.compile("\"(?<item>.+?)\"");
Matcher matcher = pattern.matcher(input);
List<String> items = new ArrayList<>();
while (matcher.find()) {
    items.add(matcher.group("item"));
}
items.forEach(System.out::println);

The result will be this:
abc, -xyz
lmn
qwe,-yui

You also can use .trim(),toLowercase() before adding an item to the list if you need that.


text:
Q: Web Scraping Api with Python I've already built a python script that scrapes some data from a website that require a login-in. My question is: How can i transform this script into an api? For example i send to the api username, password and data required, then it returns the data needed.

A: A web API is nothing but an HTTP layer over your custom logic so that requests can be served the HTTP way (GET PUT POST DELETE).
Now, the question is, how?
The easiest way is to use already available packages called "web frameworks" which python has in abundance.
The easiest one to probably implement would mostly be Flask.
For a more robust application, you can use django as well.


text:
Q: In Evans PDE, trace-zero functions In Evans 275~277 trace-zero function theorem proof,
u $\in$ ${{W^1}^,}^p(R_+^n)$, $u$ has compact support in $\bar R_+^n$,
$Tu = 0$ on $\partial R_+^n$ = $R^{n-1}$
Then since $Tu = 0$ on ${{{R^n}^-}^1}$, there exist functions $u_m \in C^1(\bar R_+^n)$ such that
$u_m$   $\to$  u in  ${{W^1}^,}^p(R_+^n)$ and $Tu_m=u_m|_{R^{n-1}} \to 0$ in $L^P(R^{n-1})$.
In here, my question is Why these $C^1(\bar R_+^n)$ functions exist


text:
Q: How can I make a DEBUG function in C++ such as ConditionalAttribute in C# In C#, one can make a method such as this:
[Conditional("DEBUG")]
private void MyFunction()
{
}

In release, this method will no longer "exist".
Using C++, I have a class where I want to perform the same assertions at the beginning of every method, so I would like to put the group of assertions in their own method. If I chose to do it that way, would I have to rely on the compiler optimizing out an empty function (since asserts will be optimized out as well)? For example:
class MyClass
{
private:
   void DebugFunction()
   {
       assert(...);
       assert(...);
       assert(...);
       // ...
   }
};

Or would I have to introduce a macro:
#ifdef NDEBUG
#define DebugFunction
#endif

What's the best way to do this?

A: The compiler will definitely optimize out the empty functions.  I would prefer the function of asserts over different versions of the code for debug and release.  Of course, you should name the function appropriately, and document your reasons as well :-)
If, for some reason, you absolutely did have the urge to use #ifndef, make sure you do it inside the CheckState() function.  This allows you to perform checks in release mode as well, should you later decide to do so.  For example:
class MyClass
{
private:
    void CheckState()
    {
        assert(...);
        assert(...);

#ifndef NDEBUG
        // some expensive check to only run on Debug builds
#endif

        // Some check you want to always make
   }
}


text:
Q: Parsing a Large Text in Sections in Matlab I have a large text file as below imported in MATLAB:
Run Lat Long Time
1 32 32 34
1 23 22 21
2 23 12 11
2 11 11 11
2 33 11 12

up to 10 runs etc.
So I'm trying to break up each section in the file: section 1, section 2, etc and write it to 10 different text files. File 1 will have data from Run 1. File 2 will have data from Run 2.

A: What you're looking for is Matlab's textread function.  I'll give you the pieces you need and frame out the logic, but you'll need to connect the pieces yourself :)
Your read would look something like this
[head1, head2, head3, head4] = textread(file_name,'%s %s %s %s',1);
[run, lat, long, time] = textread(file_name,'%u %u %u %u');

and your write method would use a loop to iterate over the values in
unique(run)
creating a file with
fout = fopen([base_file_name_out num2str(run_number)]);
and writing to it the values contained in
lat_this_run=Lat(run==run_number);
using the method
fprintf(fout,'%u %u %u\n', lat_this_run, long_this_run, time_this_run)

A: If your data is already loaded into matlab and named A, you could do:
>> a = max(A(:,1));
>> AA={};
>> for i = 1:a
     AA{i}=A(find(A(:,1)==i),:)
     name=sprintf('%d.txt',i);
     dlmwrite(name,AA{i},'\t');
   end

The output will be .txt files containing tab-delimited data.


text:
Q: How to call the Image upload web service (ASP.NET ) .asmx file in android using Retrofit I am trying to upload an image file in the folder from android to asp.net(Web Service- .asmx file) using retrofit.
I have created the web method for that and that web method is working appropriately and I tested on postman also.
But when I tried to upload from android then it displays the "500 Internal Server Error"
Web Method (ASP.NET .asmx file)
[WebMethod]
public void UploadImage_http()
{
    var request = HttpContext.Current.Request;
    var photo = request.Files["photo"];
    photo.SaveAs(HttpContext.Current.Server.MapPath("images/thumbnail/"+photo.FileName));
    JavaScriptSerializer js = new JavaScriptSerializer();
    Feed feed = new Feed();
    feed.err = false;
    feed.err_message = "inserted success";
    Context.Response.Write(js.Serialize(feed));
}

Android Side Code
API Interface
 @Multipart
    @POST("/FeedAPI.asmx/UploadImage_http")
    public void upload(@Part("photo") MultipartBody.Part photo, Callback<Feed> callback);

API Call
    public void btnSelectSave(View view)
        {
            File file = new File(selectedImagePath);
// selectedImagePath contains the path of the image.
            Toast.makeText(this, file.getName(), Toast.LENGTH_SHORT).show();
            RequestBody photoContent = RequestBody.create(MediaType.parse("multipart/form-data"),file);
            MultipartBody.Part photo = MultipartBody.Part.createFormData("photo",file.getName(),photoContent);
            Log.e("DATA_ photos", ""+photo);

            retrofitService.getService().upload(photo, new Callback<Feed>() {
                @Override
                public void success(Feed feed, Response response) {
                    Toast.makeText(SharePostActivity.this, feed.getErr_message(), Toast.LENGTH_SHORT).show();
                }
                @Override
                public void failure(RetrofitError error) {
                    Toast.makeText(SharePostActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
                }
            });
        }

Below Method use to get the path and value were store in selectedImagePath
public String getRealPathFromURI(Uri contentUri)
{
    String[] proj = {MediaStore.Images.Media.DATA};
    CursorLoader loader = new CursorLoader(getApplicationContext(),contentUri,proj,null,null,null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    String result = cursor.getString(column_index);
    cursor.close();
    return result;
}

Error Occurs:
I/System.out: [OkHttp] sendRequest<<
D/Retrofit: <--- HTTP 500 http://192.168.43.25:81/FeedAPI.asmx/UploadImage_http (84ms)
    : HTTP/1.1 500 Internal Server Error
D/Retrofit: Cache-Control: private
    Content-Length: 55
    Content-Type: text/plain; charset=utf-8
    Date: Thu, 12 Sep 2019 14:21:21 GMT
    Server: Microsoft-IIS/10.0
    X-Android-Received-Millis: 1568298080946
    X-Android-Response-Source: NETWORK 500
    X-Android-Selected-Protocol: http/1.1
D/Retrofit: X-Android-Sent-Millis: 1568298080929
    X-AspNet-Version: 4.0.30319
    X-Powered-By: ASP.NET
D/Retrofit: Object reference not set to an instance of an object.
D/Retrofit: <--- END HTTP (55-byte body)

A: please try this
    [HttpPost, DisableRequestSizeLimit]
    public ActionResult UploadFile(IFormFile file)
    {
       using (var stream = file.OpenReadStream())
       {
       }
    }


text:
Q: Changing img src on click with javascript I need to change image when I click on it every time.
I added full path even it's not working.

Javascript:
var pullImage=document.getElementById("change");
function changeImage(){
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif") {
    pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png";

};
if (pullImage.src=="C:\Users\Srinivas\Downloads\Compressed\attachments_2\stop1.png"){
    pullImage.src="C:\Users\Srinivas\Downloads\Compressed\attachments_2\play1.gif";

}
};

A: Please use below javascript and place it anywhere below  tag you are using

A: The problem is your path. I recreated the problem and i alerted the actual source which look like this:

You will either have to give the actual full path. Or you dont use the path as refrence, but a html reference. For example a hidden div with value 1 or 2 - for the used image

1

A: Using attr function you can change src of image :
$("#my_image").attr("src","second.jpg");

You can also create event eg. put thumbnail and on clicking load original image:
$('#my_image').on({
    'click': function(){
        $('#my_image').attr('src','second.jpg');
    }
});


text:
Q: Как решить задачу без использования itertools.product? Наткнулся на задачку с перебором, которую решил через itertools.product, но хотелось бы увидеть варианты решения, желательно, без использования библиотек.
Задача:

Имеется набор данных, состоящий из троек положительных целых чисел.
Необходимо выбрать из каждой тройки ровно одно число так, чтобы
сумма всех выбранных чисел была чётной и минимально возможной. Если
получить требуемую сумму невозможно, в качестве ответа нужно выдать 0.
На вход программе в первой строке подаётся количество троек чисел N (1
< N < 100 000). Каждая из следующих N строк содержит три натуральных
числа, не превышающих 10 000.

Входные данные:

Sample Input 1:
5
2 3 2
2 3 3
2 2 1
3 3 5
1 1 1

Sample Output 1:
10

Sample Input 2:
10
2 3 2
2 3 3
2 2 1
3 3 5
1 1 1
1 2 3
4 5 6
11 23 56
23 13 10
45 76 89

Sample Output 2:
80

Sample Input 3:
10
2 3 2
2 3 3
2 2 1
3 3 5
1 1 1
1 2 3
4 5 6
11 23 56
23 13 9
44 76 89

Sample Output 3:
78

Моё решение:
import itertools

n = int(input())
matrix = [list(map(int, input().split())) for _ in range(n)]

min_number = 1_000_000
for items in itertools.product(*matrix):
    sum_number = sum(items)
    if sum_number % 2 == 0:
        min_number = min(min_number, sum_number)
print(min_number)

Понимая что удовольствия переписывать входные данные нет, привожу их в коде (Sample Input 2):
matrix = [list(map(int, line.split())) for line in """
2 3 2
2 3 3
2 2 1
3 3 5
1 1 1
1 2 3
4 5 6
11 23 56
23 13 10
45 76 89
""".strip().splitlines()]
n = len(matrix)

A: В принципе, у меня получилось почти то же самое, что предложил Эникейщик. Правда я хранил не разницу, а само второе минимальное число.
Алгоритм таков:
Считается сумма минимальных чисел из каждой тройки.
Параллельно сохраняется второе минимальное число при условии что оно: имеет нечётную разницу с первым минимальным (чётным сумму не поправишь) и, в принципе, минимальное из всех найденных. Также сохраняется первое минимальное число (чтобы его потом выкинуть из суммы).
Если в конце концов сумма нечётная, то из неё вычитается сохранённое число и прибавляется второе минимальное. (Ну да, здесь, в принципе, можно сразу хранить просто разницу между этими числами.)
summ = 0
min2 = (float('inf'), None)

for _ in range(int(input())):
    numb1, numb2, numb3 = sorted(map(int, input().split()))
    summ += numb1
    if   numb2-numb1 & 1 and numb2 < min2[0]: min2 = (numb2, numb1)
    elif numb3-numb1 & 1 and numb3 < min2[0]: min2 = (numb3, numb1)

if summ & 1:
    summ += min2[0] - min2[1] if min2[1] != None else -summ

print(summ)

A: Как такой алгоритм:

*

*Сложить минимальные числа из каждой тройки. Если сумма четная - профит.

Если нет:

*В каждой тройке найти разницу между минимальным и средним (по величине, а не расположению) числом.

*К нечетной сумме прибавить минимальную нечетную разницу.


text:
Q: How to get a list of connected devices? I'm experiencing a strange phenomenon. Every now and then (perhaps once per hour on average) my Win7 box emits the "Device connected" system sound (the one you get when you plug in a USB device) for no apparent reason. This can happen several times in a session, and there never is a "Device removed" sound in-between. I have no idea what's causing this. I'm not sure, but I think this only started after I had installed Dropbox.
Is there any way to find out which device Windows thinks has just been connected when it plays that sound?
I've seen this question, but the WDK requires me to install Visual Studio first, and I don't want to do that if possible. Isn't there something I could do with Sysinternals or some other tool?

A: You can try he method specified here, it tells how to enable usbstor device auditing so you can view the events in a log file.