text:
Q: Sql table relationship from a form I have a form that gathers information about a person to be used in a contact book. I need to create two tables. One for the majority of the data and another for phone numbers alone because each person can have multiple phone numbers. Obviously I want these table to be relatable but I do not understand how to input the data from the form into both tables so they share a relationship. I also need to be able to join the data into a single phonenumbers column in the main table.
The idea is illustrated by this:

(source: gyazo.com)
Use the tableA_id to populate the phonenumbers fields. How to i input the data from the form to be able to do this?
Updated code
11 //Form Validation
12 $name = $email = $gender = $comment = $website = "";
13
14 if ($_SERVER["REQUEST_METHOD"] == "POST")
15 {
16   $firstname = test_input($_POST["firstname"]);
17   $email = test_input($_POST["email"]);
18   $lastname = test_input($_POST["lastname"]);
19   $street = test_input($_POST["street"]);
20   $city = test_input($_POST["city"]);
21   $state = test_input($_POST["state"]);
22   $country = test_input($_POST["country"]);
23   $workphone = test_input($_POST["workphone"]);
24   $mobilephone = test_input($_POST["mobilephone"]);
25   $homephone = test_input($_POST["homephone"]);
26   $phonearray = array("$workphone","$mobilephone","$homephone");
27
28
29 }
30
31 function test_input($data)
32 {
33   $data = trim($data);
34   $data = stripslashes($data);
35   $data = htmlspecialchars($data);
36   return $data;
37 }
//After validation we input the data into the tables.
84
85 $sql="INSERT INTO nameaddress
86 (FirstName, LastName, Street, City, State, Country,email,photo)
87 VALUES
88     ('$firstname','$lastname','$street','$city','$state','$country','$email','$uploadfile')";
89
90
91
92
93
94 if (!mysqli_query($con,$sql))
95   {
96   die('Error: ' . mysqli_error($con));
97   }
98
99 $lastInsertId=mysqli_insert_id($con);
100 foreach ($phonearray as $a) {
101 $select="INSERT INTO userphones(phonenumbers,nameaddress_id)102
102         VALUES ($a,".$lastInsertId.")";
103 mysqli_query($con,$select);
104 }

A: To insert data you need to do it in loop in php, will look like (pseudo-code):
single insert into tableA (firstname, lastname, address, email)
get last inserted id (mysql_insert_id or mysqli_insert_id)
in loop insert all phone numbers: foreach $phonenumber
insert into phones(phonenumber, lastidfrom insert into tableA)
For output you need to use group_concat, so your query will look like this:
select a.*, group_concat(b.phonenumbers)
from tableA as a
inner join
phones as b
on (a.id=b.tableA_id)
group by a.id

NOTE: mysql with strict mode will not allow you to use a.* with only a.id in group by, you will need to do like this:
select *
from tableA as a
inner join
(
    select tableA_id, group_concat(phonenumbers)
    from tableB
    group by tableA_id
) as q
on (a.id=q.tableA_id)
group by a.id

A: Add to your first table for the majority of data a primary key (e.g., "id"). The second table for the phonenumber data should have an indexed field for the primary key from the first table.

Then you will want to first INSERT the non-phonenumber data into this table. Then use SELECT LAST_INSERT_ID() to get the primary key of this insert and add that to your insert into the second table. This way all then entries in the phonenumber table will have an indexed field that points back to the user in the first table.

This stackoverflow thread has a good discussion on using LAST_INSERT_ID():

Get the new record primary key ID from mysql insert query?


text:
Q: Python: How to filter a DataFrame of dates in Pandas by a particular date within a window of some days? I have a DataFrame of dates and would like to filter for a particular date +- some days.
import pandas as pd
import numpy as np
import datetime

dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])

If I select lets say date 2009-08-03 and a window of 5 days, output would be similar to:
>>>
                  Power
2010-07-29   713.108020
2010-07-30  1055.109543
2010-07-31   951.159099
2010-08-01  1350.638983
2010-08-02   453.166697
2010-08-03  1066.859386
2010-08-04  1381.900717
2010-08-05   107.489179
2010-08-06  1195.945723
2010-08-07  1209.762910
2010-08-08   349.554492

N.B.: The original problem I am trying to accomplish is under Python: Filter DataFrame in Pandas by hour, day and month grouped by year

A: The function I created to accomplish this is filterDaysWindow and can be used as follows:
import pandas as pd
import numpy as np
import datetime

dates = pd.date_range(start="08/01/2009",end="08/01/2012",freq="D")
df = pd.DataFrame(np.random.rand(len(dates), 1)*1500, index=dates, columns=['Power'])

def filterDaysWindow(df, date, daysWindow):
    """
    Filter a Dataframe by a date within a window of days

    @type df: DataFrame
    @param df: DataFrame of dates

    @type date: datetime.date
    @param date: date to focus on

    @type daysWindow: int
    @param daysWindow: Number of days to perform the days window selection

    @rtype: DataFrame
    @return: Returns a DataFrame with dates within date+-daysWindow
    """
    dateStart = date - datetime.timedelta(days=daysWindow)
    dateEnd = date + datetime.timedelta(days=daysWindow)
    return df [dateStart:dateEnd]

df_filtered = filterDaysWindow(df, datetime.date(2010,8,3), 5)
print df_filtered

redpajama_set_name: RedPajamaStackExchange


text:
Q: Search file on SSH server for a pattern (with less command) using JSch I am currently trying to access a Linux server and run some commands.
The general idea is to search for a log file containing certain text and then access that log, search for the requisite text and store all the data currently displayed on the screen in a String.
This approach works fine through PuTTY but now the requirement is different.
I have accomplished this task on other commands like ls and other commands that provide a direct output. However, I am having no luck with commands like less or more.
I have of course tried on sending the entire contents of the log to an array list and then searching for my text (seeing as I will have a relative idea of the position of the data once the 1st line is found). However, this takes a huge amount of time as the log size varies from 10 Mb to 750 Mb.
I would appreciate if anyone can think of another approach or provide any ideas towards a feasible way to this approach.
For reference:
Code I have tried
public class check {

private Session session;

private String username = "user";
private String password = "pass";
private String hostname = "host";

public SSHConnectionManager()
{ }

public SSHConnectionManager(String hostname, String username, String password)
{
    this.hostname = hostname;
    this.username = username;
    this.password = password;
}

public void open() throws JSchException
{
    open(this.hostname, this.username, this.password);
}

public void open(String hostname, String username, String password) throws JSchException
{

    JSch jSch = new JSch();

    session = jSch.getSession(username, hostname, 22);
    Properties config = new Properties();
    config.put("StrictHostKeyChecking", "no");  // not recommended
    session.setConfig(config);
    session.setPassword(password);

    System.out.println("Connecting SSH to " + hostname + " - Please wait for few seconds... ");
    session.connect();
    System.out.println("Connected!");
}

public String runCommand(String command) throws JSchException, IOException
{

    String ret = "";

    if (!session.isConnected())
        throw new RuntimeException("Not connected to an open session.  Call open() first!");

    ChannelExec channel = null;
    channel = (ChannelExec) session.openChannel("exec");

    channel.setCommand(command);
    channel.setInputStream(null);

    PrintStream out = new PrintStream(channel.getOutputStream());
    InputStream in = channel.getInputStream(); // channel.getInputStream();

    channel.connect();

    ret = getChannelOutput(channel, in);

    channel.disconnect();

    System.out.println("Finished sending commands!");

    return ret;
}

private String getChannelOutput(Channel channel, InputStream in) throws IOException
{

    byte[] buffer = new byte[1024];
    StringBuilder strBuilder = new StringBuilder();

    String line = "";
    while (true){
        while (in.available() > 0) {
            int i = in.read(buffer, 0, 1024);
            if (i < 0) {
                break;
            }
            strBuilder.append(new String(buffer, 0, i));
            System.out.println(line);
        }

        if(line.contains("logout")){
            break;
        }

        if (channel.isClosed()){
            break;
        }
        try {
            Thread.sleep(1000);
        } catch (Exception ee){}
    }

    return strBuilder.toString();
}

public void close()
{
    session.disconnect();
    System.out.println("Disconnected channel and session");
}

public static void main(String[] args)
{

    SSHConnectionManager ssh = new SSHConnectionManager();
    try {
        ssh.open();
        String ret = ssh.runCommand("ls -l");
        System.out.println(ret);
        ret=ssh.runCommand("cd *move to path of log*");
        System.out.println(ret);
        ret=ssh.runCommand("less *log name*");
        System.out.println(ret);
        ret=ssh.runCommand("/*searchtext*");
        System.out.println(ret);

        ssh.close();

        } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        }
    }
}

I get the necesaary output for my ls command but not for any of the others.

A: First, your code executes every command in its own separate shell. So the cd command has no effect on the less command. Send, /*searchtext* is not a command at all. Note that setCommand is not an equivalent of typing something in SSH console window. It's completely different interface.
First step would be to execute all commands in the same shell. For that use a shell technique of your server. On Linux server, you would use semicolon or double ampersand. As for example shown here: Multiple commands using JSch.
Though it won't help you with the /*searchtext*. You should not try to use "human" techniques for automation.
In the end, the better solution is to actually do everything with a single command, like using grep:
grep *searchtext* *move to path of log*/*log name*


text:
Q: Complex Thread Control Suppose I have 3 threads of execution, below describes what each thread will do.
Thread 1 - main thread
Thread 2 - detector thread
Thread 3 - action thread
When thread 1 starts, it spawns thread 2. Thread 2 will simply run alongside thread 1 and search for an event. When the event happens, I want thread 2 to spawn a new thread, thread 3. I want thread 3 to join with thread 1. Is this possible?
Sample Code:
 public class ThreadA {

// variable to flag if ThreadB should still loop
private static boolean runThreadB = true;

public void mainMethod() {

    new ThreadB().start();

    // do some stuff

    // make sure thread B can end
    runThreadB = false;

}

// inner class / Thread B
class ThreadB extends Thread {

    @Override
    public void run() {

        // loop until Thread A is done
        while (runThreadB) {

            // wait for event, if event is found, spawn thread C
            ThreadC threadC = new ThreadC();
            threadC.start();

            /**
             * Need thread C to somehow join ThreadA
             */
            try {
                threadC.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

    }

}

}
 public class ThreadC extends Thread {

@Override
public void run() {

    // perform some tasks

}

}

A: You must synchronize the threads. You can use ReentrantLock to do this.
Here is a simple example for your problem (Event producer-consumer):
public class Foo{
    //...

    public void consumeEvent() throws InterruptedException{
        aLock.lock();
        try {
            while(noEvent){
                eventAvailable.await();
            }
            // use the event
        } finally {
            sLock.unlock();
        }
    }

    public void createEvent() throws InterruptedException{
        aLock.lock();
        try {
            // add an event
            eventAvailable.signalAll();
        } finally {
            sLock.unlock();
        }
    }

    private Lock aLock = new ReentrantLock();
    private Condition eventAvailable = aLock.newCondition();
}

Your threads will use an object from this class.
Thread eventProducer = ...
Thread eventConsumer = ...
eventProducer.start();
eventConsumer.start();

Your threads synchronized now.


text:
Q: nginx with expires on javascript files (dynamically generated by PHP) I have a problem with expires headers on javascript files which are generated by PHP..
The website has two types of javascript files. One part is static javascript files and one part is dynamically generated by PHP.
conf without expires headers
Here no expires headers are added to the .js files (All files return HTTP 200)
location / {
    try_files  $uri $uri/ /index.php;
}

location ~ \.php$ {
    include  /var/ini/nginx/fastcgi.conf;
    fastcgi_pass  php;
    fastcgi_param  SCRIPT_FILENAME /var/www/index.php;
}

conf with expires headers
When adding a location for .js files then all dynamically generated files return HTTP 404
location / {
    try_files  $uri $uri/ /index.php;
}

location ~ \.php$ {
    include  /var/ini/nginx/fastcgi.conf;
    fastcgi_pass  php;
    fastcgi_param  SCRIPT_FILENAME /var/www/dyndev.dk/public/secure/index.php;
}

location ~ \.(js|css)$ {
    expires 1y;
    add_header Cache-Control "public";
}

How to handle both the static and dynamically generated .js files with expires headers?
All dynamically genereated javascript files are named *-php.js
File structure
/var/www/public/index.php # All none-static file requests are pointed to index.php
/var/www/public/js/main.js # Static files
/var/www/js-dynamically_generated.php # This file is outside the public www, but is routed by PHP since the file doesn't exists inside the public /js

PHP routing
www.example.com/ -> index.php
www.example.com/js -> static content
www.example.com/js/dynamically_generated-php.js -> js-dynamically_generated.php

A: For nginx, PHP is never Javascript. Nginx can't distinct between PHP which renders html and PHP which renders javascript (please correct me if I'm wrong).
So the way to go would be either to setup a seperate folder with PHP files which generate all JS (code is not tested!):
location ~ \normal_php/.php$ {
    include  /var/ini/nginx/fastcgi.conf;
    fastcgi_pass  php;
    fastcgi_param  SCRIPT_FILENAME /var/www/dyndev.dk/public/secure/index.php;
}

location ~ \js_php/.php$ {
    expires 1y;
    add_header Cache-Control "public";

    include  /var/ini/nginx/fastcgi.conf;
    fastcgi_pass  php;
    fastcgi_param  SCRIPT_FILENAME /var/www/dyndev.dk/public/secure/index.php;
}

...or send the header with PHP itself:
<?php
header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // 1 hour


text:
Q: Пост с картинками, используя markdown Создаю пост и внутри поста хочу использовать картинки.
Для загрузки изображений использую Paperclip.
Есть форма new.haml
.container
  %header
    %h1 Новая статья

  = simple_form_for @post do |f|

    %h5 Тема
    = f.input :theme,
      label: false

    %h5 Аннотация
    = f.input :annotate,
      label: false

    %h5 Основная картинка
    = f.file_field :main_image

    %h5 Текст статьи
    = f.input :text,
      label: false

    %h5 Изображения
    .illustrations
      = f.simple_fields_for :illustrations do |ill|
        .entry
          = ill.file_field :image
          %button.btn.btn-add{:type => "button", :id => "add_image"} 'Добавить еще картинку'

    = f.submit 'Создать'

Из нее могу добавить к посту много картинок.
Вопрос в следующем: как прописать ссылку на картинку в тексте поста. Чтоб markdown ее разобрал.
P.S. Видел статью на эту тему, но там ссылаются на id картинки в таблице, но у меня же его еще нет. Как быть не знаю.
За раннее, спасибо.


text:
Q: DNS Round-robin does not load balance SSH I tested DNS round-robin with SSH, and I noticed amazing results of the SSH client on my testing environment. I am using 3 nodes with RHEL 6.2 (openssh-5.3p1, bind-9.7.3-8.P3). Things like the host keys have been managed.
My "issue":
I would like a rudimentary kind of load balancing between several SSH servers, using multiple DNS entries. I was (almost) sure that was possible. But I got a rudimentary kind of HA... It seems that the openssh client does not care of the round-robin, it always connects to the same node, except if it is down, in this last case the client uses another record from the list of DNS entries, and then connect to it with success. Is it the normal/common behavior?? Or what is wrong in my tests?
I put my straces and tcpdumps of what happens in several cases. Thanks in advance if you have any idea or explanation which can help :)
login => 10.255.254.1 (node0), 10.255.254.3 (node2)
ssh client => 10.255.254.2 (node1)
DNS server on node0, RR has not been disabled.
login IN A 10.255.254.1
login IN A 10.255.254.3

I confirm that:

*

*the lookup with host(1) confirms the Round-Robin ;

*the ping(1) command looks good :

[root@node1 ~]# ping login
PING login.node (10.255.254.3) 56(84) bytes of data.
64 bytes from node2.node (10.255.254.3): icmp_seq=1 ttl=64 time=1.73 ms
^C
[root@node1 ~]# ping login
PING login.node (10.255.254.1) 56(84) bytes of data.
64 bytes from node0.node (10.255.254.1): icmp_seq=1 ttl=64 time=0.467 ms
^C
[root@node1 ~]# ping login
PING login.node (10.255.254.3) 56(84) bytes of data.
64 bytes from node2.node (10.255.254.3): icmp_seq=1 ttl=64 time=0.433 ms
^C

TEST 1 (both SSH servers are up and reachable)
[root@node1 ~]# strace -e connect ssh login
connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
(...)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
connect(3, {sa_family=AF_UNSPEC, sa_data="\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
(...)

[root@node0 ~]# tcpdump -i eth0 src node1 or dst node1
listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
17:03:04.875099 IP node1.node.53511 > node0.node.domain: 55904+ A? login.node. (29)
17:03:04.875417 IP node0.node.domain > node1.node.53511: 55904* 2/1/1 A 10.255.254.3, A 10.255.254.1 (102)
17:03:04.875432 IP node1.node.53511 > node0.node.domain: 22271+ AAAA? login.node. (29)
17:03:04.875523 IP node0.node.domain > node1.node.53511: 22271* 0/1/0 (79)

=> connection on node2 (10.255.254.3)
TEST 2 (both SSH servers are still up and reachable)
[root@node1 ~]# strace -e connect ssh login
connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
(...)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_UNSPEC, sa_data="\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
(...)

[root@node0 ~]# tcpdump -i eth0 src node1 or dst node1
17:04:29.663664 IP node1.node.51950 > node0.node.domain: 4685+ A? login.node. (29)
17:04:29.663685 IP node1.node.51950 > node0.node.domain: 36559+ AAAA? login.node. (29)
17:04:29.664046 IP node0.node.domain > node1.node.51950: 4685* 2/1/1 A 10.255.254.1, A 10.255.254.3 (102)
17:04:29.664110 IP node0.node.domain > node1.node.51950: 36559* 0/1/0 (79)

=> connection on node2
(another test confirms the connection to node2 again. It seems that the round-robin is only used for preliminary tests by the ssh client)
TEST 3 (SSH server on node2 is stopped)
[root@node2 ~]# /etc/init.d/sshd stop
Stopping sshd:                                             [  OK  ]

[root@node1 ~]# strace -e connect ssh login
connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
(...)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_UNSPEC, sa_data="\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = -1 ECONNREFUSED (Connection refused)
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0

[root@node0 ~]# tcpdump -i eth0 src node1 or dst node1
17:09:05.854022 IP node1.node.41233 > node0.node.domain: 63435+ A? login.node. (29)
17:09:05.854055 IP node1.node.41233 > node0.node.domain: 3015+ AAAA? login.node. (29)
17:09:05.854436 IP node0.node.domain > node1.node.41233: 63435* 2/1/1 A 10.255.254.1, A 10.255.254.3 (102)
17:09:05.854531 IP node0.node.domain > node1.node.41233: 3015* 0/1/0 (79)
17:09:05.856764 IP node1.node.59579 > node0.node.ssh: Flags [S], seq 3025023931, win 14600, options [mss 1460,sackOK,TS val 9854496 ecr 0,nop,wscale 7], length 0
17:09:05.856806 IP node0.node.ssh > node1.node.59579: Flags [S.], seq 1105519762, ack 3025023932, win 14480, options [mss 1460,sackOK,TS val 350907197 ecr 9854496,nop,wscale 7], length 0
17:09:05.857106 IP node1.node.59579 > node0.node.ssh: Flags [.], ack 1, win 115, options [nop,nop,TS val 9854496 ecr 350907197], length 0
17:09:05.865291 IP node0.node.ssh > node1.node.59579: Flags [P.], seq 1:22, ack 1, win 114, options [nop,nop,TS val 350907205 ecr 9854496], length 21
(...)

=> connection on node0 (failover?? surprise!)
TEST 4 (same conditions)
[root@node1 ~]# strace -e connect ssh login
connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
(...)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
connect(3, {sa_family=AF_UNSPEC, sa_data="\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = -1 ECONNREFUSED (Connection refused)
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0

[root@node0 ~]# tcpdump -i eth0 src node1 or dst node1
(...)
17:11:44.154595 IP node1.node.56947 > node0.node.domain: 4602+ A? login.node. (29)
17:11:44.154862 IP node0.node.domain > node1.node.56947: 4602* 2/1/1 A 10.255.254.3, A 10.255.254.1 (102)
(...)

=> same result (connection on node0)
TEST 5 (SSH server on node2 is restarted)
[root@node2 ~]# /etc/init.d/sshd restart
Stopping sshd:                                             [FAILED]
Starting sshd:                                             [  OK  ]

[root@node1 ~]# strace -e connect ssh login
connect(3, {sa_family=AF_FILE, path="/var/run/nscd/socket"}, 110) = -1 ENOENT (No such file or directory)
(...)
connect(3, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.1")}, 16) = 0
connect(3, {sa_family=AF_UNSPEC, sa_data="\0\0\0\0\0\0\0\0\0\0\0\0\0\0"}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0
connect(3, {sa_family=AF_INET, sin_port=htons(22), sin_addr=inet_addr("10.255.254.3")}, 16) = 0

[root@node0 ~]# tcpdump -i eth0 src node1 or dst node1
(...)
17:17:12.893633 IP node1.node.42432 > node0.node.domain: 7264+ A? login.node. (29)
17:17:12.893988 IP node0.node.domain > node1.node.42432: 7264* 2/1/1 A 10.255.254.1, A 10.255.254.3 (102)
(...)

=> connection on node2 again (failback)

A: DNS does not provide load balancing, so yes unless the host is down it will always utilize a record from the returned list of DNS records.  If you want to dynamically handle downed hosts you will have to load balance the incoming connections across your SSH boxes.
Round-Robin DNS requests are very rudimentary in terms of load balancing.  Check out the drawbacks section: http://en.wikipedia.org/wiki/Round_robin_DNS

A: Well, finally this behavior works as it is described above only inside the same subnet. When I use openssh clients on another LAN (with an intermediate gateway), that WORKS! I mean: I got a rudimentary load distribution, with a "failover" when one of the nodes is down.
So I conclude that RRDNS is simply enough to handle a basic load distribution of SSH users.


text:
Q: Loop through list items and check for width in-line I am trying to loop through a list using jquery and find if any of the spans have a set width of 95%.  If it does, then change the color to BG color to red or if it's 50% change the BG color to yellow.  Any ideas how I can accomplish this?
I have started the loop.
JQUERY
// .skills = UL

$('.skills').each(function(i) {
var list = $(this).find('li span');

    if (list.attr('style').indexOf('width') == 95) {
        alert('hello');
    }

});

HTML

HTML

CSS

JS

Jquery

Java

PHP

PS

AI

A: Well you can more easily cycle through the UL for spans like this:
$('.skills li span').each(function(i) {

});

Throw an if statement in there checking for width. "this" will be the span itself.

A: *

*indexOf returns the position of a substring within a string, or -1 if not found.  So it will never equal 95, unless the letters width begin at position 96 of the style.
You could do this instead:  $(this).attr('style').indexOf('width: 95%') > -1

*You cannot assign a width to an inline element with static positioning (span).

*Try to avoid using inline CSS.  Move your styles to an external CSS file instead.

*Instead of searching the style attribute, consider checking the width style itself:

$('.skills li span').each(function() {
  if(this.style.width === '95%') {
    alert('hello');
  }
});

HTML

CSS

JS

Jquery

Java

PHP

PS

AI


text:
Q: partial image content in the first access I have two nginx servers in different machines serving the same cifs share, mounted with the same options. The files serverd are images.
In one of the servers, the first access to a image file not send the complete image. The content-length are correct in both nginx servers.
For example, the partial image that sends the first nginx:
http://www.alderia.com/32445166.jpg
The correct image sends the second nginx:
http://www.alderia.com/32445166_2.jpg
If I reload (with shift+control+r) the first image, it's load ok.


text:
Q: Open cv error in pycharm I am getting the following error in pycharm (windows version). I have installed opencv using Anaconda. In addition, Pycharm auto-completion is detecting cv2. Can somebody tell what could be the possible issue? Thanks in advance
File "C:/Users/DELL/Pranavan/PyCharm Projects/QE/SIFT_implementation.py", line 1, in <module>
    import cv2
  File "C:\Users\DELL\AppData\Roaming\Python\Python36\site-packages\cv2\__init__.py", line 9, in <module>
    from .cv2 import *
ModuleNotFoundError: No module named 'cv2.cv2'

A: You said you are using Anaconda, but the Interpreter Pycharm is using seems to be searching for packages in C:\Users\DELL\AppData\Roaming\Python\Python36\site-packages which does not look like an Anaconda installation directory.
Make sure that Pycharm is using the correct interpreter (your Anaconda Python Version) by going to File->Settings->Project->Project Interpreter

A: When using Anaconda, the Interpreter Pycharm seems to be searching for packages in Anaconda(Python)
Note on setting the interpreter:
File - Default Settings - Project Interpreter - Wheel - Add local -
System Interpreter - … - /home/milab/anaconda3/bin/python - OK to all

and then
File - Settings - Project : ### - Project Interpreter - Python 3.6 ~/anaconda3/bin/python - Ok

I hope you to solve problem.


text:
Q: Why Camera.setParameters(Camera.Parameters) does not work on Sony-Ericsson X10 and Droid? Has anyone come across a strange behaviour with the Camera API when used on Sony-Ericsson X10 or Droid?
For example the following code doesn't work on those devices. As a result I'm getting a lot of negative feedback on the Market translating into many cancelled orders...
mParameters.set("rotation", orientation);
mParameters.set("jpeg-quality", img_quality);
mParameters.set("picture-size", "1024x768");
mCamera.setParameters(mParameters);

Could you suggest an alternative way of achieving the same? Thanks.

A: You can't just set random values in the camera parameters because you don't know if the hardware is going to support that, so you need to ask first!
mCamera = Camera.open();
Camera.Parameters params = mCamera.getParameters();
List<Size> sizes = params.getSupportedPictureSizes();
// See which sizes the camera supports and choose one of those
mSize = sizes.get(0);
params.setPictureSize(mSize.width, mSize.height);
mCamera.setParameters(params);

A: You must first fix the orientation of the activity and then must put orietación grades:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mCamera.setDisplayOrientation(90);


text:
Q: Sequential k-means clustering using scikit-learn Is there a way to perform sequential k-means clustering using scikit-learn? I can't seem to find a proper way to add new data, without re-fitting all the data.
Thank you

A: scikit-learn's KMeans class has a predict method that, given some (new) points, determines which of the clusters these points would belong to. Calling this method does not change the cluster centroids.
If you do want the centroids to be changed by the addition of new data, i.e. you want to do clustering in an online setting, use the MiniBatchKMeans estimator and its partial_fit method.

A: You can pass in initial values for the centroids with the init parameter to sklearn.cluster.kmeans. So then you can just do:
centroids, labels, inertia = k_means(data, k)
new_data = np.append(data, extra_pts)
new_centroids, new_labels, new_inertia = k_means(new_data, k, init=centroids)

assuming you're just adding data points and not changing k.
I think this will sometimes mean you get a suboptimal result, but it should usually be faster. You might want to occasionally redo the fit with, say, 10 random seeds and take the best one.

A: It's also relatively easy to write your own function that finds out which centroid is closest to a point that you are considering. Assuming you have some matrix X that is ready for kmeans:
centroids, labels, inertia = cluster.k_means(X, 5)

def pred(arr):
    return np.argmin([np.linalg.norm(arr-b) for b in centroids])

You can confirm that this works via:
[pred(X[i]) == labels[i] for i in range(len(X))]


text:
Q: R / Time Series: What's the lag unit for autocorrelation function (acf)? I have an XTS time series object which shows a value on the first of each month (representing an aggregated sum for the whole month) during four years.
When I run the stats::acf() function on it, I get a plot with lag (x axis) units in the hundreds of thousands. How can that be if I only have 48 values in my time series? If it is a time unit, then which one, and how can I change it?
Example code:
library(dplyr)
library(lubridate)
library(xts)

set.seed(100)

test <- data.frame(y = c(rep(2012, 12), rep(2013, 12), rep(2014, 12), rep(2015, 12)),
                   m = rep(seq(1, 12, 1), 4), d = rep(1, 48), value = runif(48, 0, 100))

test <- test %>%
  mutate(date = ymd(paste(y, m, d, sep = "-"))) %>%
  select(date, value)

test <- xts(test$value, test$date)

acf(test)

A: From the source code we see that we can calculate the lags like this:
sampleT <- as.integer(nrow(test))
nser <- as.integer(ncol(test))
lag.max <- floor(10 * (log10(sampleT) - log10(nser)))
x.freq <- frequency(test)
lag <- outer(0:lag.max, 1/x.freq)
#         [,1]
# [1,]       0
# [2,]   86400
# [3,]  172800
# [4,]  259200
# [5,]  345600
# [6,]  432000
# [7,]  518400
# [8,]  604800
# [9,]  691200
#[10,]  777600
#[11,]  864000
#[12,]  950400
#[13,] 1036800
#[14,] 1123200
#[15,] 1209600
#[16,] 1296000
#[17,] 1382400

The time unit is the reciprocal of the frequency unit. To understand how that value is calculated you need to dive into the source code of frequency.zoo, which does something I find difficult to understand at a first glance.


text:
Q: arules package - Error: subscript out of bounds for producing recommendations I'm trying make recommendation with arules package
I have this data
Data
      Client product  N       Date
    1      A  Banana  1 01/01/2016
    2      A  Tomato  1 01/01/2016
    3      A    Tuna  1 01/01/2016
    4      B  Orange  2 01/01/2016
    5      B  Tomato  3 02/01/2016
    6      C    Kiwi 11 08/01/2016

Next I used this code
trans = as(split(Data$product, Data$Client), "transactions")

Sales<- as(trans, "data.frame")

rules = apriori(trans, parameter = list(support = 0.001, confidence = 0.005))
rules.sorted <- sort(rules, by="lift")

# find redundant rules
subset.matrix <- is.subset(rules.sorted, rules.sorted)
subset.matrix[lower.tri(subset.matrix, diag=T)] <- NA
redundant <- colSums(subset.matrix, na.rm=T) >= 1
which(redundant)
rules.pruned <- rules.sorted[!redundant]
inspect(rules.pruned)
rules = rules.pruned

I get these rules:
lhs         rhs        support confidence lift
1 {Tuna}   => {Banana} 0.3333333  1.0000000  3.0
2 {Orange} => {Tomato} 0.3333333  1.0000000  1.5
3 {Tuna}   => {Tomato} 0.3333333  1.0000000  1.5
4 {Banana} => {Tomato} 0.3333333  1.0000000  1.5
5 {}       => {Kiwi}   0.3333333  0.3333333  1.0
6 {}       => {Orange} 0.3333333  0.3333333  1.0
7 {}       => {Tuna}   0.3333333  0.3333333  1.0
8 {}       => {Banana} 0.3333333  0.3333333  1.0
9 {}       => {Tomato} 0.6666667  0.6666667  1.0

but now, for all Clients, I want to recommend 3 products:
for (i in 1:3) {

        reco=function(x){
                rulesMatchLHS = is.subset(rules@lhs,x)
                suitableRules =  rulesMatchLHS & !(is.subset(rules@rhs,x))
                order.rules = sort(rules[suitableRules], by = "lift")
                LIST(order.rules@rhs)[[i]]

        }

        NewS <- sapply(1:length(trans), function(x) reco(trans[x]))
        NewS <- as.data.frame(NewS)
        Sales <-cbind(Sales,NewS)

}

This code produces the error

Error in LIST(order.rules@rhs)[[i]] : subscript out of bounds

I think that this happening because I didn't have recommendation for all users, but I want the code to continue and put "no suggestion" in this case.
What is the best way to do that?

A: I think you want code like this.
Read data and mine rules:
library(arules)

Data <- structure(list(Client = structure(c(1L, 1L, 1L, 2L, 2L, 3L), .Label = c("A", "B",  "C"), class = "factor"), product = structure(c(1L, 4L, 5L, 3L, 4L, 2L), .Label = c("Banana", "Kiwi", "Orange", "Tomato", "Tuna"), class = "factor"), N = c(1L, 1L, 1L, 2L, 3L, 11L), Date = structure(c(1L, 1L, 1L, 1L, 2L, 3L), .Label = c("01/01/2016", "02/01/2016", "08/01/2016"), class = "factor")), .Names = c("Client", "product", "N", "Date"), class = "data.frame", row.names = c(NA, -6L))

trans <- as(split(Data$product, Data$Client), "transactions")

rules <-  apriori(trans, parameter = list(support = 0.001, confidence = 0.5, maxlen = 2))
inspect(rules)

Output:
lhs         rhs      support   confidence lift
1 {}       => {Tomato} 0.6666667 0.6666667  1.0
2 {Orange} => {Tomato} 0.3333333 1.0000000  1.5
3 {Tomato} => {Orange} 0.3333333 0.5000000  1.5
4 {Tuna}   => {Banana} 0.3333333 1.0000000  3.0
5 {Banana} => {Tuna}   0.3333333 1.0000000  3.0
6 {Tuna}   => {Tomato} 0.3333333 1.0000000  1.5
7 {Tomato} => {Tuna}   0.3333333 0.5000000  1.5
8 {Banana} => {Tomato} 0.3333333 1.0000000  1.5
9 {Tomato} => {Banana} 0.3333333 0.5000000  1.5

Create recommendations:
reco <- function(rules, newTrans){
     rules.sorted <- sort(rules, by="lift")
     rhs_labels <- unlist(as(rhs(rules.sorted), "list"))

     matches <- is.subset(lhs(rules.sorted), newTrans) &
        !(is.subset(rhs(rules.sorted), newTrans))
     apply(matches, MARGIN = 2, FUN = function(x) unique(rhs_labels[x]))
}

reco(rules, trans)

Output for the three transactions (i.e., clients):
$`{Banana,Tomato,Tuna}`
[1] "Orange"

$`{Orange,Tomato}`
[1] "Tuna"   "Banana"

$`{Kiwi}`
[1] "Tomato"

A few notes:

*

*I only mine rules of length 1 and 2. This is more efficient and there is no need to look for redundant rules.

*I increased confidence.

*Package recommenderlab will do this type of recommendations using method "AR". This is currently not working correctly, but it will work soon.


text:
Q: Sublime Text: SublimeGDB doesn't stop at the breakpoint This is a similar question to sublimegdb can not stop in the breakpoint but nobody answers that one so I decided to open a new question.
I just installed sublimeGDB plugin in my sublime text 3 and set a breakpoint successfully by pressing F9. When I pressed F5 to run, the program didn't stop at the breakpoint --  it just finished running while the GDB view showed up for about 0.5 sec then disappeared.
Here's some output in my console view:
Will write debug info to file: stdout
Running: gdb --interpreter=mi ./ex8
In directory: //Users//jimmy/workspace
Process: <subprocess.Popen object at 0x1037a1110>
pty: 41, tty: None, name: /var/folders/m2/7h27qgr17v1bqyphh7wq6tpw0000gn/T/tmpnvs3afgdb_stdout: broken pipe
GDB session ended
gdb_stderr: /bin/sh: gdb: command not found
gdb_stderr: broken pipe

A:
gdb_stderr: /bin/sh: gdb: command not found

This says: sublime ran /bin/sh, and asked it to run gdb, but no program called gdb was found on the PATH.
It must be that either:

*

*you don't have GDB installed on your system at all, or

*it is installed somewhere, but it's not on whatever PATH the sublime invokes /bin/sh with.


text:
Q: how to make java trust my application I have an application overriding the default toolkit, by setting the system.property awt.toolkit. For the standalone application I set this up in the code, by using System.setProperty(String, String). This works just fine. But when I try to run via webstart, the property is set to late, because java already set up the toolkit (for splash or webstart console maybe).
So I added the property to the jnlp, but without any effect. The property is not even passed, to the vm. I figured out, that it is considered "unsecure" by java itself and my applications is considered "untrusted".
see here

For an untrusted application, system properties set in the JNLP file
  will only be set by Java Web Start if they are considered secure.

I have a signed application with a valid certificate from a certificate authority, but still my application is considered untrusted. i did all the steps suggested here, but without any effect. I don't get any of those dialogs about untrusted application or publisher information anymore, but I still do not get the property passed to my virtual machine.
any ideas, what I could try next?
BTW: still using java 7 as runtime


text:
Q: If $f$ is continuous $\displaystyle\lim_{x \to \infty}f(x)=\infty$ iff $f^{-1}(K)$ is compact for every compact $K \subset \mathbb{R}^{n}$.
Let $f: \mathbb{R}^{m}\to \mathbb{R}^{n}$ be a continuous function. Prove that the following statements are equivalents:
(i) $\displaystyle\lim_{x \to \infty}f(x)=\infty$;
(ii) $f^{-1}(K)$ is compact for every compact $K \subset \mathbb{R}^{n}$.

My attempt.
(i) $\Longrightarrow$ (ii): If $K \subset \mathbb{R}^{n}$ is compact, $f^{-1}(K)$ is closed, since $f$ is continuous. If $f^{-1}(K)$ is unbounded, there is a sequence $(x_{n}) \subset f^{-1}(K)$ such that $x_{n} \to \infty$.
I want to conclude that $f(x_{n}) \to \infty$. How can I ensure it?
(ii) $\Longrightarrow$ (i): I dont have a good idea. Can someone help me? I want just a hint, not a solution.

A: To complete  your argument for $(i)$ $\|x_n\|\rightarrow \infty$ implies that $f(x_n)\rightarrow \infty$ by hypothesis.
ii)   implies i)Suppose that there exists a sequence $x_n$ such that $lim_n\|x_n\|=\infty$ and $f(x_n)$ is bounded, $f(x_n)$ is contained in a closed ball $B$ which is compact, so $f^{-1}(B)=C$ is compact, and bounded by hypothesis, but $x_n\in C$ contradiction since $x_n$ is not bounded.

A: Regarding (ii) $\Longrightarrow$ (i)
Take $p \in \mathbb N$. You want to find $M>0$ such that for $\Vert x \Vert >M$ you have $\Vert f(x) \Vert >p$.
The closed ball $K_p$centered on zero with radius $p$ is a compact subset of $\mathbb R^n$. $f^{-1}(\mathbb R^n \setminus K_p) = f^{-1}(\mathbb R^n)\setminus f^{-1}(K_p)$. And $f^{-1}(K_p)$ is by hypothesis a compact subset of $\mathbb R^n$, therefore bounded and included in a closed ball centered on zero with a radius $M>0$.
Where are done: the image of a point $x$ with a norm $>M$ is such that $\Vert f(x)\Vert >p$.

A: The definition of $x_n\to\infty$ I am used to is that for every compact set $K$ there exists $N$ such that for all $n>N$ we have $x_n\not\in K$. So then the statement $$\lim_{x\to\infty}f(x)=\infty$$ would literally mean that for every compact set $K$ there exists compact set $L$ such that for all $x\not\in L$ we have $f(x)\not\in K$, so $f^{-1}(K)\subseteq L$.
I would like to mention how this elegant definition can be made precise with topology. In topology we say that $x_n\to x$ if for every open set $U$ containing $x$ there exists $N$ such that for all $n>N$ we have $x_n\in U$. There is also a thing in topology called the one-point compactification of a topological space $X$. The idea is to add a "point at infinity", so you get $X\cup\{\infty\}$, and the open sets containing $\infty$ are exactly the complements of the compact sets in $X$.


text:
Q: Parse Json multidimentional Array in jQuery I'm trying to parse text from facebook json file which has nested arrays, but i get only the elements of first level of array.
I want to get and the data from nested array, if exists.
For example using the code above, i can't get the fields in arrays "category_list".
Example of  data is
{
"userdata": [
        {
          "category": "Community",
          "name": "whitespace",
          "created_time": "2014-01-30T13:58:22+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "City",
          "category_list": [
            {
              "id": "xxxxxxxxxxxxxxxxxx",
              "name": "City"
            }
          ],
          "name": "Marburg, Queensland",
          "created_time": "2014-01-09T13:09:14+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Hotel",
          "name": "Hotel Line",
          "created_time": "2014-01-06T20:41:44+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Food/beverages",
          "name": "Olive",
          "created_time": "2014-01-06T20:41:16+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Education",
          "name": "Genius Solutions Group",
          "created_time": "2014-01-06T20:40:48+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Hotel",
          "category_list": [
            {
              "id": "128232937246338",
              "name": "Travel & Transportation"
            }
          ],
          "name": "Seabreeze",
          "created_time": "2014-01-06T20:40:07+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Local business",
          "category_list": [
            {
              "id": "xxxxxxxxxxxxxxxxxx",
              "name": "Computer Store"
            }
          ],
          "name": "Project",
          "created_time": "2014-01-06T20:38:26+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        },
        {
          "category": "Tv show",
          "name": "helloooo",
          "created_time": "2014-01-06T20:38:08+0000",
          "id": "xxxxxxxxxxxxxxxxxx"
        }
      ]
}

The code i use is

<title>Parsing</title>

User Data

and results are
User Data
+----------------+------------------------+
| Community      | whitespace             |
| City           | Marburg, Queensland    |
| Hotel          | Hotel Line             |
| Food/beverages | Olive                  |
| Education      | Genius Solutions Group |
| Hotel          | Seabreeze              |
| Local business | Project                |
| Tv show        | helloooo               |
+----------------+------------------------+

Some help please...

A: A simple solution would be simply add a comma-separated list of categories to the table.  Use map and then join:
+ "" + user.category_list.map(function(item) { return item.name; }).join(", ") + "	"

Of course, you also have to check whether "category_list" exists, but that's not hard:
+ "" + (typeof user.category_list == "undefined" ? "" :
        user.category_list.map(function(item) { return item.name; }).join(", "))
+ "	"

Fiddle

A: The property category_list is an array, you need a nested loop.
see fiddle for updated display: http://jsfiddle.net/4gK5L/3/
 $(document).ready(function() {
            (function(){
                $.each(data.userdata, function (i, user) {
                    var hasData = (typeof (user.category_list) != 'undefined' && user.category_list.length > 0);
                    var i = 0;
                    var tblRow = '
' + user.category + '

';
                    tblRow = tblRow + '
' + user.name + '
'
                    // + ' '  + user.Name + '
                    if (hasData)
                    {
                        tblRow = tblRow + '
Subcategory Info:
'
                        while(i < user.category_list.length){
                             tblRow = tblRow + '
Sub Category Id: ' + user.category_list[i].id + '

Sub Category Name: ' + user.category_list[i].name + '
'
                            i++
                        }
                        tblRow = tblRow + '

';
                    }
                    var dateTime = new Date(user.created_time);
                    var createdDate = (dateTime.getMonth() + 1) + '-' + dateTime.getDate() + '-' + dateTime.getFullYear();
                    tblRow = tblRow + '
Created: ' + createdDate + '
'
                    tblRow = tblRow + '
Category Id: ' + user.id + '
'
                    tblRow = tblRow + '
';
                    $(tblRow).appendTo("#userdata");
                });
            })();
        });

As an aside, McGarnagle's answer is more elegant then mine, and if you used it, you should accept his answer.


text:
Q: Recursive sequence - Convergency and Limit i just started university so im pretty new to all this new math. My problem is to solve this recursive sequence: $a_{n+1} = a_{n}^3$ with: $a_{0} = \frac{1}{2}$ and: $n \in N$
I've to analyse convergence and if its convergent i've to get the limit of this sequence.
I dont know how to start and this to the power of three confuses me.
thanks in advance!

A: Due to $a_{n+1}=a_n^{3}=(a_{n-1}^3)^3=a_{n-1}^{3^2}=……=a_{0}^{3^{n+1}}=(\frac{1}{2})^{3^{n+1}}$. if you know this ,you can do this question.

A: When the limit exists we have $\lim_{n \rightarrow \infty} a_n = \lim_{n \rightarrow \infty} a_{n+1}=a$, so to find the limit you need to solve the equation: $a^3=a$.
But that's not enougth, we can see from the definition of $a_n$ that it's non-negative (why?), and its decreasing to zero, so we can infer from above that limit is zero (a decreasing sequence converges to the infimum of the sequence).
To show that the sequence is decreasing we need to show that $a_n \geq a_{n+1}=a^3_n \ \forall n\in \mathbb{N}$, this happens when $a_n (1-a^2_n)\geq 0$, this is always valid cause $0\leq a_n \leq 1$ (why?).

A: Another idea is to define a new sequence $b_n=\log a_n$. Then your recursive equation
$$a_{n+1}=a_n^3$$
becomes
$$b_{n+1}=3b_n$$
which is pretty straight forward.


text:
Q: How do I stop receiving hashtags as links from Twitter? I wanted a Twitter forwarder to Telegram.
I found this one: https://github.com/franciscod/telegram-twitter-forwarder-bot
The problem is now, that if a tweet contains a hashtag before a link, Telegram show me the link to the hashtag.

I tried different things and searched about that, but I don't know how to only receive plain text from twitter.
Also I don't get the short link t.co if the tweet is to long. It's just a long link.
for tweet in tweets:
    self.logger.debug("- Got tweet: {}".format(tweet.text))

    # Check if tweet contains media, else check if it contains a link to an image
    extensions = ('.jpg', '.jpeg', '.png', '.gif')
    pattern = '[(%s)]$' % ')('.join(extensions)
    photo_url = ''
    tweet_text = html.unescape(tweet.text)
    if 'media' in tweet.entities:
        photo_url = tweet.entities['media'][0]['media_url_https']
    else:
        for url_entity in tweet.entities['urls']:
            expanded_url = url_entity['expanded_url']
            if re.search(pattern, expanded_url):
                photo_url = expanded_url
                break
    if photo_url:
        self.logger.debug("- - Found media URL in tweet: " + photo_url)

    for url_entity in tweet.entities['urls']:
        expanded_url = url_entity['expanded_url']
        indices = url_entity['indices']
        display_url = tweet.text[indices[0]:indices[1]]
        tweet_text = tweet_text.replace(display_url, expanded_url)

    tw_data = {
        'tw_id': tweet.id,
        'text': tweet_text,
        'created_at': tweet.created_at,
        'twitter_user': tw_user,
        'photo_url': photo_url,
    }
    try:
        t = Tweet.get(Tweet.tw_id == tweet.id)
        self.logger.warning("Got duplicated tw_id on this tweet:")
        self.logger.warning(str(tw_data))
    except Tweet.DoesNotExist:
        tweet_rows.append(tw_data)

    if len(tweet_rows) >= self.TWEET_BATCH_INSERT_COUNT:
        Tweet.insert_many(tweet_rows).execute()
        tweet_rows = []

A: Just disable markdown_twitter_hashtags() function, make it return text without replace that.


text:
Q: How to compare if two dates are closer to each other I want to check if two dates are within a range of each other, and reorder my array. I need to compare the dates from an array with the current date.
I have this:
var currentDate = new Date(); /* current date = 2021/08/18 */
listOfObjects = [ { "user": "John", "date": "2021-08-20" }, { "user": "Bob", "date": "2021-08-17" }, { "user": "Joe", "date": "2021-08-09" } ]

The return shoud be like this:
[ { "user": "Bob", "date": "2021-08-17" }, { "user": "John", "date": "2021-08-20" }, { "user": "Joe", "date": "2021-08-09" } ]

A: You can subtract the dates and compare the results. Like new Date("2021-08-18") - new Date("2021-08-17") = 86400000 cause dates are saved as milliseconds from a random but standardize reference date.
Then you can use this difference by using Math.abs(number) as a condition for finding the nearest dates to the given one and put it in a simple sorting function like below:

function orderByDateDistance(nDate, nList){
    // easy sorting by finding the current min (also working with max)
    for(let tA=0;tA<nList.length-1;tA++){ // iterating over all except the last will be sorted
        let tIndex = tA; // current index
        let tDifference = Math.abs(nDate-new Date(nList[tA]["date"])); // current difference
        for(let tB=tA+1;tB<nList.length;tB++){ // iterating over unsorted list part
            if(Math.abs(nDate-new Date(nList[tB]["date"])) < tDifference){ // compare current difference with stored
                tIndex = tB; // save index
                tDifference = Math.abs(nDate-new Date(nList[tB]["date"])); // save value optional
            }
        }
        // change items
        let tBuffer = nList[tA]; // save current object
        nList[tA] = nList[tIndex]; // copy next lowest object
        nList[tIndex] = tBuffer; // copy buffered object
    }
    return nList; // optional returning
}

// Your example
console.log(
    orderByDateDistance(
        new Date("2021/08/18"),
        [
            {"user": "John", "date": "2021-08-20"},
            {"user": "Bob", "date": "2021-08-17"},
            {"user": "Joe", "date": "2021-08-09"}
        ]
    )
);

A: In JavaScript, an array is sorted by sorting the textual representation of its items.

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.  (Source: Array.prototype.sort() - JavaScript | MDN)

See following example:
const numbers = [1, 30, 4, 21, 100000];
numbers.sort();
console.log(numbers);

We see that the output is the array with alphabetically sorted numbers:
1, 100000, 21, 30, 4

In most cases, this is not what we want (or what most people expect). To sort numbers numerically, we pass a custom compare function to sort:
function i_cmp(a, b) {
    let d = a-b;
    if (d < 0)
        return -1;
    if (d > 0)
        return 1;
    return 0;
}

numbers.sort(i_cmp);
console.log(numbers);

output:
1,4,21,30,100000

To sort an array by a criterion that depends on further conditions, it's handy to pass a function bound to runtime values that is created by another function. Here we sort items by their absolute distance of a fixed value x.
function d_cmp(x) {
    return function(a, b) {
        let d = Math.abs(a-x)-Math.abs(b-x);
        if (d < 0)
            return -1;
        if (d > 0)
            return 1;
        return 0;
    }
}

numbers.sort(d_cmp(50));
console.log(numbers);

output:
30,21,4,1,100000

Hemera already answered how to get date distances. The rest, accessing date attributes, should be easy to implement.

For a live demo of above code (combined) see: https://ideone.com/e7DaOx


text:
Q: A connected simple graph G has 14 vertices and 88 edges. Prove G is not Eulerian. A connected simple graph G has 14 vertices and 88 edges. Prove G is not Eulerian.
-This was a two part question, and for the first part I had to prove why the graph is Hamiltonian, but now i am struggling with proving why it is not Eularian. The hint my teacher gave me was to prove that G has at least 8 vertices of degree 13, which I unfortunately still can't solve, any help is appreciated.

A: Suppose $G$ has fewer than $8$ vertices of degree $13$. Then it has at most $7$ vertices of degree $13,$ and the other $7$ vertices have degree at most $12$. Thus the sum of the degrees is at most $7\times13+7\times12=175.$ This contradicts the handshake lemma, which says that the sum of the degrees is twice the number of edges, in this case $176.$

A: Step 1: prove the hint.  Suppose it's not true, then bound the total number of edges by bounding the edges at each vertex, and get a contradiction.
Step 2: Since $8>2$, there are more than two vertices of odd degree.
Step 3: Profit.


text:
Q: How do I UPDATE user values from $_SESSION? I'm trying to make a form that allows the user to change AND add some values to their session user.
I have not made the login, it was one of my old friends. He didn't comment the code very well, and commenting is useful for me that is relative new to php and SQL.
How do I UPDATE user values from $_SESSION?
index.php code:
<?php

include('template.php');
$role = array("1"=> "admin.php", "2"=> "useradmin.php", "3"=> "user.php"); //Visar vilken sida varje roll skall skickas vid inlogg.

if(isset($_POST['email']))
{
  $query = <<<END
  SELECT email, password, userID, fname, company, tel, role FROM user
  WHERE email = '{$_POST['email']}'
  AND password = '{$_POST['password']}'
END;
$res = $mysqli->query($query);
if ($res->num_rows > 0)
{
    $row = $res->fetch_object();
    $_SESSION["email"] = $row->email;
    $_SESSION["fname"] = $row->fname;
    $_SESSION["tel"] = $row->tel;
    $_SESSION["company"] = $row->company;

$query2 = <<<END
  SELECT role FROM user
  WHERE role = '{$row->role}'

END;
  $res2 = $mysqli->query($query2) or die ($mysqli->error);
  $row2 = $res2->fetch_object();

  header("Location: ".$role[$row2->role]);
  }
  else
  {
    echo "Fel email eller lösenord.";
  }
}

settings.php code with HTML File:
<?php
include('template.php');
 $content = <<<END

 Användarinställningar för {$_SESSION['fname']}

<form action="" metod="POST">

 Förnamn:

        <input type="text" name="fname" value="{$_SESSION['fname']}">

 Email:

        <input type="text" name="email" value="{$_SESSION['email']}">

 Telefonnummer:

        <input type="text" name="tel" value="{$_SESSION['tel']}">

 Företag:

        <input type="text" name="company" value="{$_SESSION['company']}">

          <input id="sparaknapp" type="submit" value="Spara">

</form>

END;
  echo $navigation_user;
  echo $header;
  echo $content;
  ?>

registration.php code:
if(isset($_POST['email']))

{
function genRandomString($length = 10) {
    $characters = "0123456789abcdefghijklmnopqrstuvwxyz";
    $string = '"';
    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }

    return $string;
}
  $password= genRandomString();
  $licenseID= genRandomString();

    $query = <<<END

    INSERT INTO user(email, company, courseID, antal, password, licenseID)

    VALUES('{$_POST['email']}','{$_POST['company']}','{$_POST['courseID']}', '{$_POST['antal']}', '$password','$licenseID');
END;
    $mysqli->query($query);

echo 'Nya licenser har lagts till i databasen';

}
 $content = <<<END

Generera Licenser

            <form action="admin.php" method="post">

              <input type="text" class="form-control" aria-describedby="basic-addon1" name="company" placeholder="Företag">

              <input type="text" class="form-control" aria-describedby="basic-addon1" name="email" placeholder="Email">

              <input type="text" class="form-control" aria-describedby="basic-addon1" name="antal" placeholder="Antal licenser">

                        <input type="checkbox" aria-describedby="basic-addon1" name="courseID">Webbutbildningen i Allmän brandskyddskunskap

                        <input type="checkbox" aria-describedby="basic-addon1" name="role">Skapa en ny administrativ användare

              <input type="submit" class="btn btn-default" value="Beställ">
              </form>

The admin on the page adds new users, and not the users, thus some values are NULL.

A: You can update session variable by using below pattern in your code.
$_SESSION['key'] = 'value';


text:
Q: Some special characters have rendering problem as a pdf file in LocalReport I am using Microsoft.Reporting.WinForms.dll to render my RDLC as a pdf file, but when i open pdf file with adobe reader i have a problem about some special Turkish characters.In pdf, they seem normal but when i try to use CTRL + F to search some words in the pdf file. I couldn't find these words. Even if my pdf file included these Turkish characters. Also, when i copy-paste these words into the file, i get characters like . It is interesting as i also use the same dll to render my RDLC as an excel file. I use same class same code and same method. I don't have this problem in an excel file.
I use byte[] Render(string format); method in WinForms.dll for rendering. Maybe some special character's ASCII code is out of range for byte array maybe because of this it couldn't render every characters for pdf format but i am not sure about this.
Thanks...

A: according to microsoft article there is an issue with special characters that is fixed in sql server 2014, the corresponding reportviewer dll would be the 2015 runtime.
maybe you should upgrade

A: I had a similar problem. My application generates PDFs using LocalReport.
My solution was:
1- Modify the RDLC XML schema to use the 2016 version. Change what you have for this.
<Report xmlns = "http://schemas.microsoft.com/sqlserver/reporting/2016/01/reportdefinition" xmlns: rd = "http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">.

Then, modify the schema, it is no longer the same as previous versions (DataSources go up ...)
2- Remove <EmbedFonts>None</EmbedFonts> from DeviceInfo.
With these changes, I got the special characters painted and printed well.


text:
Q: Python loading animation in a thread giving segmentation fault Here's the code I have created to load animations in background using pyglet.resource.animation() function, while the app does some other things.
import pyglet
import threading

animations = dict()

class LoadingThread(object):
    def __init__(self):
        thread = threading.Thread(target=self.run, args=())
        thread.start()                                  # Start the execution

    def run(self):
        """ Method that runs forever """
        loadAnimations()
        print("Loaded all animations.")

def loadAnimations():
    global animations
    print("In loadAnimations")
    for animation in os.listdir(os.getcwd()):
        if animation.endswith(".gif"):
            print(animation)
            #Gives segmentation fault here
            animations[animation] = pyglet.resource.animation(animation)
    print("Loaded animations")

thread = LoadingThread()

Runs well when called normally without a thread.
If there is any other way to deal with loading animations in background in pyglet, please  suggest.
Thanks.

A: As suggested by @Frank Merrow. The problem here was that I was using the function
pyglet.resource.animation("filename.gif") function in my main thread too. So it was creating a segmentation fault.
I found another function that can also load animation.
pyglet.image.load_animation("filename.gif")
Using this solved my problem.
Also this problem can be solved by starting two threads synchronously running main flow and the background work.


text:
Q: Why should I add identifiers before struct? I can't see why, how to fix this? This is the code in my .c file:

This is the error:

A: Whenever you get an error message like
[file]:[line]:[column]: expected [punctuation] before [keyword]

the problem is usually with the code right before the line that the compiler is complaining about.  For instance, you will get an error like this when the previous declaration or statement was not ended correctly:
struct THING { }   // oops! forgot a semicolon on this line
struct OTHER { };  // compiler complains here, but the problem is up there

This is because the compiler doesn't "know" there is a problem until it processes the beginning of the second statement.
In C, to find the code "right before the line", you may have to look past or into preprocessor directives.  In your code snippet
#include "list.h"
#define true 1
#define false 0
struct NODE *head;

when the compiler is parsing struct NODE ..., the #define directives aren't there anymore, and #include "list.h" has been replaced with the contents of the file list.h.  So, probably the missing semicolon or whatever is inside list.h.
Without seeing your complete program, I can't be more specific.

A: The compiler issues errors for the code it sees after preprocessing, so you have to consider what that code looks like after the included "list.h" has been expanded.
Whatever is at the end of that file is most likely the cause of the error - a missing semi-colon at the end of a struct definition for example.


text:
Q: Trusted Connection to SQL fails after connecting to a VPN I have a development server with an SQL 2008 EXPRESS instance running on it.  The domain is called DEVAD, and the instance is enabled for Shared Memory, Named Pipes and TCP/IP.
My workstation PC is on a different domain called AD.
I have domain trusts set up between AD and DEVAD, and I can connect to the DEVAD instance using my AD credentials, via SSMS or .NET programs.
Unfortunately, the moment I connect to another network via a VPN using credentials for a different domain, I get the following error "Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. (Microsoft SQL Server, Error: 18452)".
My VPN connection has the option for "Use default gateway on remote network" unchecked for IPv4 and IPv6.
Any ideas as to how to prevent the VPN connection from breaking the trust?

Update: I have an additional VPN that I occasionally connect to, and I don't have issues connecting to SQL at the same time when this one is active.
I did some nslookup tests on the SQL host with various VPNs connected and not connected.  My problem VPN ends up with a DNS timeout, which may mean that the DNS on the VPN is misconfigured and slurps up the request, rather than giving a Non-existent domain response (as my other VPN does), and letting the system get on with querying a DNS that does know about it.

A: I was also having this same issue and found the solution here:
http://social.technet.microsoft.com/forums/en-US/itprovistanetworking/thread/275599f0-6239-46a5-8245-50a5c13a2713/
You'll need to locate your VPN connections .pbk file.
You can find it here:

C:\Users\{WindowsLogin}\AppData\Roaming\Microsoft\Network\Connections\Pbk

Or if you have it set to allow all users to use the connection, you can find it here:

C:\ProgramData\Microsoft\Network\Connections\Pbk

Edit it with a text editor and find the line that says:
UseRasCredentials=1

Disable it by setting it to 0
UseRasCredentials=0

A: Did you ever figure this out? I think I know what your problem is.

*

*It's possible that the problematic VPN is a full tunnel, and if so, it could be the case that even unchecking the option for "use default gateway on remote network" won't help. With full tunnel VPN, when you're VPN'd in, ALL of your traffic will be on the VPN network, whether you like it or not. You can test this by going to a site such as ipchicken.com before you connect to the VPN, and then refresh the page again after you're connected. If the IP changes, then you're on a full tunnel.

*How are you trying to connect to SQL Server? Are you using an application, or SQL Server Management Studio? If you can run the program from a command line, you may have luck using the runas windows command with the /netonly switch. It enables you to be logged into one domain but run a program as a different domain user. Like this:
runas /user:MYDOMAIN\MYUSER /netonly "C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\Ssms.exe"
Replace the domain, username, and path of SQL Server Manamgent Studio with the appropriate values.
When it asks you for the password, type in the password for the domain user you enetered. It will not authenticate the user at this point. Then when you open SSMS, connect to the DB in question like you normally would, and if it can't connect with your normal creds it should try to use the ones you entered with the runas command.

A: Let's say your workstation is on domain A and the domain of the server in the VPN is B
As the accepted answer alludes to, the issue is that Windows is trying to send "domain A" credentials to the "domain B" server, and "B" basically responds , "I don't know who 'A' is!" and denies the authentication request.
You can override this to send your "B" credentials, by using the Windows Credential Manager.  In Credential Manager, under Windows Credentials, click "Add a Windows Credential".  The address should be the SQL server (with port 1433 or whatever your SQL port is), and the credentials should be your "B domain" credentials (which you may be more familiar with as domain\user but user@domain is also valid)


text:
Q: Authenticate CVS users against Active Directory I have a mixed Linux/Windows software development environment where the Linux clients are migrating to a system where they are able to authenticate against Active Directory.  (That part I figured out)
Our lab is currently using CVS to conduct version control on our source code.  In the migration, we will need users to be able to authenticate to our CVS server.  I have it planned such that when the migration occurs, we will set up the CVS server to also authenticate users against AD.
Unfortunately, I do not have a lot of experience with CVS.  Is this task even possible?  From what I understand, it can be set up to authenticate users based on the local users on the system.  However, since the actual users won't have their credentials stored locally on the server (as it's pulling them from AD), is it possible to point CVS to rely upon pam for authentication?
I have read about accessing CVS over SSH with user credentials.  Would that be a requirement for this to occur?  If so, how does one set this up?
I greatly appreciate the assistance!

A: This is going to be rather long, but let's do it anyway. First of all, yes this can be done. I can't supply much in the way of configuring CVS, but I can provide all you need to make a linux server authenticate users against Active Directory.
It all starts with /etc/nsswitch.conf. Here is the relevant section:
passwd:     files ldap compatshadow:     files ldap compatgroup:      files ldap compat
Now, depending on what distro you are using, you will need to install some ldap packages. Under Redhat/Fedora/CentOS this would be nss_ldap, under Debian/Ubuntu and the likes, you will need libnss-ldap and libpam-ldap. I would also recommend some ldap-utils for debugging.
With the above your name services will attempt to use LDAP, so now you need to configure the various LDAP packages to use your AD server. The search base should be base cn=Users,dc=aminocom,dc=com and the bind DN should be binddn cn=LDAPsearch,cn=Users,dc=aminocom,dc=com. You will need to define a specific User to allow browsing of the AD. We have created a user named LDAPSearch, and put its credentials into a separate file named .secret. Read the documentation of these packages for more detail. Furthermore I would recommend a soft bind policy and the following attribute mappings:

# Services for UNIX 3.5 mappings
nss_base_passwd cn=Users,dc=aminocom,dc=com?sub
nss_base_shadow cn=Users,dc=aminocom,dc=com?sub
nss_base_group cn=Users,dc=aminocom,dc=com?sub
nss_map_objectclass posixAccount user
nss_map_objectclass shadowAccount user
nss_map_attribute uid sAMAccountName
nss_map_attribute uidNumber msSFU30UidNumber
nss_map_attribute gidNumber msSFU30GidNumber
nss_map_attribute loginShell msSFU30LoginShell
nss_map_attribute gecos name
nss_map_attribute userPassword msSFU30Password
nss_map_attribute homeDirectory msSFU30HomeDirectory
nss_map_objectclass posixGroup Group
nss_map_attribute uniqueMember msSFU30PosixMember
nss_map_attribute cn cn
pam_login_attribute sAMAccountName
pam_filter objectclass=user
pam_member_attribute msSFU30PosixMember
pam_groupdn cn=nixUsers,cn=Users,dc=aminocom,dc=com
pam_password ad

All of this assumes that you have the Windows Services for Unix installed on your domain controller. In AD you will need to configure a primary Unix group (in our case called nixUsers) and add every CVS user into that group.
You should probably be able to use AD directly (i.e. without the Windows Services for Unix), but that will require different attribute mappings. You might have to experiment a bit there.
Now we get to the PAM configuration. Under Debian there are basically 4 files that need modifications:
1.) common-account:

account required   pam_unix.so broken_shadow
account sufficient pam_localuser.so
account sufficient pam_succeed_if.so uid

2.) common-auth:

auth    required   pam_env.so
auth    sufficient pam_unix.so nullok try_first_pass
auth    requisite  pam_succeed_if.so uid >=500 quiet
auth    sufficient pam_ldap.so use_first_pass
auth    required   pam_deny.so

3.) common-session:

session optional        pam_keyinit.so revoke
session required        pam_limits.so
session [success=1 default=ignore] pam_succeed_if.so service in crond quiet use_uid
session required        pam_unix.so
session optional        pam_ldap.so

4.) common-password

password sufficient pam_unix.so md5 shadow nullok try_first_pass
password sufficient pam_ldap.so
password required   pam_deny.so

Under Redhat (and derivatives) all the necessary changes should go into the relevant sections in /etc/pam.d/system-auth and /etc/pam.d/system-auth-ac.
The above will allow users to log in with AD credentials. However, this does NOT automatically create a home directory for them (unless you do some more scripting around that) and it does not allow them to change their passwords through linux. This can be done, too, but it requires modification of their workstations (if they use Linux). Any more questions re the above, just ask.
We use this on many of our servers, works like a charm.

A: As it turns out, CVS just uses PAM.  So, if your server is already configured to authenticate to AD, CVS will also receive the authentication info.
wolfgangsz's suggestion is very helpful in getting the 1st step completed (server authentication to AD via LDAP [you could also use Winbind]).


text:
Q: Separate stream of numbers into groups of closer integers I have a stream of numbers such as
[2872, 2997, 3121, 13055, 14178, 14302, 23134, 23382, 23507, 32832, 33677, 34017, 43415, 44246, 44374, 52866, 54035, 54158, 62835, 64243, 64936, 73110, 73890, 74014, 82809, 83771, 83899, 93436, 94765, 94891].

I would like to split it as follows:
[[2872, 2997, 3121], [13055, 14178, 14302], [23134, 23382, 23507], [32832, 33677, 34017], [43415, 44246, 44374], [52866, 54035, 54158], [62835, 64243, 64936], [73110, 73890, 74014], [82809, 83771, 83899], [93436, 94765, 94891]].

It is to be noted that the distance between the groups could be closer to each other, also the digits within a group could be farther away.

A: This is not an answer, but a way to look at your data, which should be insightful.
Original values:

Deltas:

A: Can't you just create a list of list of integers (or array of array) with size N/3 (N being the total of your numbers), and then just loop on this length and put the minimal number in it?
Something like this (I don't know what language you are using so I use c# as exemple):
        int len = numbersStream.count();
        List<List<int>> BigList = new List<List<int>>();
        List<int> smallList = new List<int>();
        for (int i = 0; i < len; ++i)
        {
            smallList = new List<int>();
            for (int j = 0; j < 3; ++i)
            {
                int value = Math.Min(numbersStream);
                smallList.Add(value);
                numbersStream.remove(value);
            }
            BigList.Add(smallList);
        }

BigList will be : (2872, 2997, 3121), (13055, 14178, 14302) etc...
*Assuming you always have exactly %3 numbers, otherwise you just tune the algorithm to avoid exceptions

A: The solution is in java but basically what this does is find the average delta and groups everything in a subset if the difference between the two elements is smaller then that average. You can fine tune this process by changing how the averageDelta operates
ps. this solution assumes your input is at least 1 large and called temp
int[] diffrence = new int[temp.length-1];

for (int i=1; i < temp.length; i++) {
    diffrence[i-1] = temp[i]-temp[i-1];
}
int averageDelta = (int) Math.round(Arrays.stream(diffrence).average().orElse(1.0));

List<List<Integer>> resultList = new ArrayList<>();
List<Integer> currentList = new ArrayList<>();
currentList.add(temp[0]);

for (int i=1; i < temp.length; i++) {
    if (temp[i]-temp[i-1] > averageDelta) {
        resultList.add(currentList);
        currentList = new ArrayList<>();
    }
    currentList.add(temp[i]);
}
resultList.add(currentList);
System.out.println(resultList.toString());


text:
Q: syntax error at or near ":" when running parametrized query from shell I'm trying to run a parameterized query from shell.
But when I run:
p='some stuff'
psql -d "dbname" -v v1="$p" -c "SELECT * FROM table WHERE name=:'v1'"

I'm getting the following error:
ERROR:  syntax error at or near ":"

Meanwhile:
psql -d "dbname" -v v1="$p" -c "\echo :'v1'"

works normally. (returns as expected: 'some stuff')

A: You cannot use the variable defined in -v in -c command (see below). Try passing the command into the standard input:
psql -d "dbname" -v v1="$p" <<< "SELECT * FROM table WHERE name=:'v1'"

From the document:

-c command
--command command
...
command must be either a command string that is completely parsable by
  the server (i.e., it contains no psql-specific features), or a single
  backslash command.
...

-v does set the psql's internal variable, which is psql-specific features. That's why you got the syntax error.


text:
Q: Porque me bloquea CORS en python? Tengo una Api REST en python en un servidor con XAMPP, no habia tenido problemas al usarlo, ya que importe el flask_cors y lo llame a mi instancia.
app = Flask(__name__)
CORS(app)

Pero al querer acceder desde otra lap a travez de la IP, al hacer peticiones me marca error:
Solicitud de origen cruzado bloqueada:
La misma política de origen no permite la lectura de recursos remotos en http://127.0.0.1:5000/login. (Razón: Solicitud CORS sin éxito). Código de estado: (null).
Algo curioso es que ayer si funcionaba pero hoy ya no.


text:
Q: Parser: The syntax for the ImpersonationInfo object is incorrect, If the ImpersonateAccount value is used for ImpersonationInfo I am trying to deploy a cube for the first time on my PC.  I have run SSMS as an Admin and made myself (Gary-pc\gary, using Windows authentication) an admin. Doing this got me past the error message user does not have permission to create a new object in 'GARY-PC', or the object does not exist.
When I deploy the cube now, I get the error: the syntax for the ImpersonationInfo object is incorrect. If the ImpersonateAccount value is used for ImpersonationInfo, then the Account property cannot be empty.
I have not (knowingly! LOL) set up anything related to impersonation.

A: I tried changing the impersonation to "Credentials of User" and although I was successful in deploying the cube, I could not process it.  I ended up getting an error that said:

"The datasource contains an ImpersonationMode that is not supported
  for processing operations"

So I changed the impersonation from "Credentials of User" to "Inherit" and was able to process.  I don't know if the first deployment would have worked with "Inherit", but thought I would share my experience.

A: I've resolved the problem with this:

*

*Double click on data source

*Select impersonation

*Choose use credentials of user
As @user1335419 says.

A: I've solved it with @napstercake's solution too. I choosed Use the service account in Impersonation info tab


text:
Q: How to use Power Management Functions (PowerEnuimerate) to get power settings I need my application to read things like the amount of time the system will wait before shutting off the display, or going to sleep, or going into hibernate. As far as I can tell, I need to use the Power Management Functions (http://msdn.microsoft.com/en-us/library/aa373163%28v=vs.85%29.aspx) In particular, it looks like I need to use the PowerEnumerate method (http://msdn.microsoft.com/en-us/library/aa372730%28v=vs.85%29.aspx).
I'm really confused about how to do this. First, I'm doing this in C#, and the code looks to be C++. Second, the C++ code seems to not really tell you how to specifically read the different time outs I want.
Note, I'm new to windows programming and C#. Most of my experience has been in Java and Android.
Thanks

A: I found an example on MSDN for using the PowerEnumerate function in VB.
I have converted the example to C#, and added the Friendly Name to the output of each Video setting in the loop. You can change the GUID_VIDEO_SUBGROUP to one of the other subgroups to see the other settings.
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

namespace TestProject
{
    class PowerEnumerator
    {
        private static Guid NO_SUBGROUP_GUID = new Guid("fea3413e-7e05-4911-9a71-700331f1c294");
        private static Guid GUID_DISK_SUBGROUP = new Guid("0012ee47-9041-4b5d-9b77-535fba8b1442");
        private static Guid GUID_SYSTEM_BUTTON_SUBGROUP = new Guid("4f971e89-eebd-4455-a8de-9e59040e7347");
        private static Guid GUID_PROCESSOR_SETTINGS_SUBGROUP = new Guid("54533251-82be-4824-96c1-47b60b740d00");
        private static Guid GUID_VIDEO_SUBGROUP = new Guid("7516b95f-f776-4464-8c53-06167f40cc99");
        private static Guid GUID_BATTERY_SUBGROUP = new Guid("e73a048d-bf27-4f12-9731-8b2076e8891f");
        private static Guid GUID_SLEEP_SUBGROUP = new Guid("238C9FA8-0AAD-41ED-83F4-97BE242C8F20");
        private static Guid GUID_PCIEXPRESS_SETTINGS_SUBGROUP = new Guid("501a4d13-42af-4429-9fd1-a8218c268e20");

        [DllImport("powrprof.dll")]
        static extern uint PowerEnumerate(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            ref Guid SubGroupOfPowerSetting,
            uint AccessFlags,
            uint Index,
            ref Guid Buffer,
            ref uint BufferSize);

        [DllImport("powrprof.dll")]
        static extern uint PowerGetActiveScheme(
            IntPtr UserRootPowerKey,
            ref IntPtr ActivePolicyGuid);

        [DllImport("powrprof.dll")]
        static extern uint PowerReadACValue(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            IntPtr SubGroupOfPowerSettingGuid,
            ref Guid PowerSettingGuid,
            ref int Type,
            ref IntPtr Buffer,
            ref uint BufferSize
            );

        [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]
        static extern uint PowerReadFriendlyName(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            IntPtr SubGroupOfPowerSettingGuid,
            IntPtr PowerSettingGuid,
            StringBuilder Buffer,
            ref uint BufferSize
            );

        [DllImport("kernel32.dll")]
        static extern IntPtr LocalFree(
            IntPtr hMem
            );

        private const uint ERROR_MORE_DATA = 234;

        public static void GetCurrentPowerEnumerateVistaAPI()
        {
            IntPtr activeGuidPtr = IntPtr.Zero;
            try
            {
                uint res = PowerGetActiveScheme(IntPtr.Zero, ref activeGuidPtr);
                if (res != 0)
                    throw new Win32Exception();

                //Get Friendly Name
                uint buffSize = 0;
                StringBuilder buffer = new StringBuilder();
                Guid subGroupGuid = Guid.Empty;
                Guid powerSettingGuid = Guid.Empty;
                res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr,
                    IntPtr.Zero, IntPtr.Zero, buffer, ref buffSize);

                if (res == ERROR_MORE_DATA)
                {
                    buffer.Capacity = (int)buffSize;
                    res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr,
                        IntPtr.Zero, IntPtr.Zero, buffer, ref buffSize);
                }

                if (res != 0)
                    throw new Win32Exception();

                Console.WriteLine("ReadFriendlyName = " +
                    buffer.ToString());

                //Get the Power Settings
                Guid VideoSettingGuid = Guid.Empty;
                uint index = 0;
                uint BufferSize = Convert.ToUInt32(Marshal.SizeOf(typeof(Guid)));

                while (
                    PowerEnumerate(IntPtr.Zero, activeGuidPtr, ref GUID_VIDEO_SUBGROUP,
                    18, index, ref VideoSettingGuid, ref BufferSize) == 0)
                {
                    uint size = 4;
                    IntPtr temp = IntPtr.Zero;
                    int type = 0;
                    res = PowerReadACValue(IntPtr.Zero, activeGuidPtr, IntPtr.Zero,
                        ref VideoSettingGuid, ref type, ref temp, ref size);

                    IntPtr pSubGroup = Marshal.AllocHGlobal(Marshal.SizeOf(GUID_VIDEO_SUBGROUP));
                    Marshal.StructureToPtr(GUID_VIDEO_SUBGROUP, pSubGroup, false);
                    IntPtr pSetting = Marshal.AllocHGlobal(Marshal.SizeOf(VideoSettingGuid));
                    Marshal.StructureToPtr(VideoSettingGuid, pSetting, false);

                    uint builderSize = 200;
                    StringBuilder builder = new StringBuilder((int)builderSize);
                    res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr,
                        pSubGroup, pSetting, builder, ref builderSize);
                    Console.WriteLine(builder.ToString() + " = " + temp.ToString());

                    index++;
                }
            }
            finally
            {
                if (activeGuidPtr != IntPtr.Zero)
                {
                    IntPtr res = LocalFree(activeGuidPtr);
                    if (res != IntPtr.Zero)
                        throw new Win32Exception();
                }
            }
        }
    }
}

The resulting output from this code:

A: However the accepted answer is still valid, I want to point out there is a bug in it, causing it to enumerate all the default values instead of the actual values.
When reading AC Values it also requires for the sub group guid to be passed:
res = PowerReadACValue(IntPtr.Zero, activeGuidPtr, pSubGroup, ref settingGuid, ref type, ref temp, ref size);

A: I ran across this post looking for a similar solution and found and corrected a few bugs.
My IDE (visual studio 2019) required a main function so I had to figure out where thats supposed to be in this rather complex code. Finally I tried renaming GetCurrentPowerEnumerateVistaAPI() to Main(). I have also incorporated @Martijn Spaan fix with a slight change. instead of ref settingGuid add ref videoSettingGuid.
So now it looks like this and functions as expected:
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;

namespace TestProject
{
    class PowerEnumerator
    {
        private static Guid NO_SUBGROUP_GUID = new Guid("fea3413e-7e05-4911-9a71-700331f1c294");
        private static Guid GUID_DISK_SUBGROUP = new Guid("0012ee47-9041-4b5d-9b77-535fba8b1442");
        private static Guid GUID_SYSTEM_BUTTON_SUBGROUP = new Guid("4f971e89-eebd-4455-a8de-9e59040e7347");
        private static Guid GUID_PROCESSOR_SETTINGS_SUBGROUP = new Guid("54533251-82be-4824-96c1-47b60b740d00");
        private static Guid GUID_VIDEO_SUBGROUP = new Guid("7516b95f-f776-4464-8c53-06167f40cc99");
        private static Guid GUID_BATTERY_SUBGROUP = new Guid("e73a048d-bf27-4f12-9731-8b2076e8891f");
        private static Guid GUID_SLEEP_SUBGROUP = new Guid("238C9FA8-0AAD-41ED-83F4-97BE242C8F20");
        private static Guid GUID_PCIEXPRESS_SETTINGS_SUBGROUP = new Guid("501a4d13-42af-4429-9fd1-a8218c268e20");

        [DllImport("powrprof.dll")]
        static extern uint PowerEnumerate(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            ref Guid SubGroupOfPowerSetting,
            uint AccessFlags,
            uint Index,
            ref Guid Buffer,
            ref uint BufferSize);

        [DllImport("powrprof.dll")]
        static extern uint PowerGetActiveScheme(
            IntPtr UserRootPowerKey,
            ref IntPtr ActivePolicyGuid);

        [DllImport("powrprof.dll")]
        static extern uint PowerReadACValue(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            IntPtr SubGroupOfPowerSettingGuid,
            ref Guid PowerSettingGuid,
            ref int Type,
            ref IntPtr Buffer,
            ref uint BufferSize
            );

        [DllImport("powrprof.dll", CharSet = CharSet.Unicode)]
        static extern uint PowerReadFriendlyName(
            IntPtr RootPowerKey,
            IntPtr SchemeGuid,
            IntPtr SubGroupOfPowerSettingGuid,
            IntPtr PowerSettingGuid,
            StringBuilder Buffer,
            ref uint BufferSize
            );

        [DllImport("kernel32.dll")]
        static extern IntPtr LocalFree(
            IntPtr hMem
            );

        private const uint ERROR_MORE_DATA = 234;

        public static void Main()
        //public static void GetCurrentPowerEnumerateVistaAPI()
        {
            IntPtr activeGuidPtr = IntPtr.Zero;
            try
            {
                uint res = PowerGetActiveScheme(IntPtr.Zero, ref activeGuidPtr);
                if (res != 0)
                    throw new Win32Exception();

                //Get Friendly Name
                uint buffSize = 0;
                StringBuilder buffer = new StringBuilder();
                Guid subGroupGuid = Guid.Empty;
                Guid powerSettingGuid = Guid.Empty;
                res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr,
                    IntPtr.Zero, IntPtr.Zero, buffer, ref buffSize);

                if (res == ERROR_MORE_DATA)
                {
                    buffer.Capacity = (int)buffSize;
                    res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr,
                        IntPtr.Zero, IntPtr.Zero, buffer, ref buffSize);
                }

                if (res != 0)
                    throw new Win32Exception();

                Console.WriteLine("ReadFriendlyName = " +
                    buffer.ToString());

                //Get the Power Settings
                Guid VideoSettingGuid = Guid.Empty;
                uint index = 0;
                uint BufferSize = Convert.ToUInt32(Marshal.SizeOf(typeof(Guid)));

                while (
                    PowerEnumerate(IntPtr.Zero, activeGuidPtr, ref GUID_VIDEO_SUBGROUP,
                    18, index, ref VideoSettingGuid, ref BufferSize) == 0)
                {
                    uint size = 4;
                    IntPtr temp = IntPtr.Zero;
                    int type = 0;

                    // My chenges
                    IntPtr pSubGroup = Marshal.AllocHGlobal(Marshal.SizeOf(GUID_VIDEO_SUBGROUP));
                    res = PowerReadACValue(IntPtr.Zero, activeGuidPtr, pSubGroup, ref VideoSettingGuid, ref type, ref temp, ref size);
                    // end my changes

                    Marshal.StructureToPtr(GUID_VIDEO_SUBGROUP, pSubGroup, false);
                    IntPtr pSetting = Marshal.AllocHGlobal(Marshal.SizeOf(VideoSettingGuid));
                    Marshal.StructureToPtr(VideoSettingGuid, pSetting, false);

                    uint builderSize = 200;
                    StringBuilder builder = new StringBuilder((int)builderSize);
                    res = PowerReadFriendlyName(IntPtr.Zero, activeGuidPtr,
                        pSubGroup, pSetting, builder, ref builderSize);
                    Console.WriteLine(builder.ToString() + " = " + temp.ToString());

                    index++;
                }
            }
            finally
            {
                if (activeGuidPtr != IntPtr.Zero)
                {
                    IntPtr res = LocalFree(activeGuidPtr);
                    if (res != IntPtr.Zero)
                        throw new Win32Exception();
                }
            }
            Console.ReadLine();
        }
    }
}


text:
Q: trying to get a blob from an oracle DB using spring3 and mybatis I am working on a project re factoring an old j2ee project to spring3/mybatis
I am currently having problem retrieving a PDF saved as a blob in an oracle table.
The original code returns a byte[] of 135896bytes and the spring/mybatis returns byte[] of 86bytes. So am i doing something incorrectly. Thanks for any help
The original code looked like::
        byte[] filebytes = null;
        con = SvcsConnection.getDBConnection("drugdb");
        String qry = "SELECT pm_blob FROM pdf_master WHERE pm_id_seq = '" +id + "'";
        oracle.sql.BLOB blob;
        stmt = con.createStatement();
        rs = stmt.executeQuery(qry);
        //set mime type
        if(rs.next()) {
            blob = ((OracleResultSet) rs).getBLOB("pm_blob");
            filebytes = blob.getBytes(1, (int) blob.length());
        }

filebytes after the getBytes is 135896bytes
in my spring stuff i have the following
mapper
<select id="getPdfMaster" parameterType="int"  resultType="org.uhs.formulary.pdf_master.model.Pdf_Master">
    SELECT pm_id_seq, pm_filename, pm_title, pm_blob, pm_update_datetime, pm_update_source,
     to_char(pm_update_datetime, 'MM/DD/YYYY') as pm_update_datetime_str
     FROM pdf_master WHERE pm_id_seq = #{pm_id_seq}
</select>

DAO
@Repository
public interface PdfMasterDao {
    public List<Pdf_Master> getPdfMaster(int pm_id_seq);
}

Model (snippet)
public byte[] getPm_Blob() {
    return pmBlob;
}

getPm_Blob returns a byte[] of 86 for the same thing

A: Specify the jdbcType as blob
<resultMap id="kpDataMap" type="KPData">
        <id property="kpId" jdbcType="INTEGER"  column="KPID" />
        <result property="fName" jdbcType="VARCHAR" column="FNAME" />
        <result property="lName" jdbcType="VARCHAR" column="LNAME" />
        <result property="salary" jdbcType="BIGINT" column="SALARY"/>
        <result property="img" jdbcType="BLOB"  column="IMG" />
    </resultMap>

    <insert id="setKPData" parameterType="KPData">
        INSERT INTO KPDATA(KPID,FNAME,LNAME,SALARY,IMG)
        VALUES(#{kpId},#{fName},#{lName},#{salary, javaType=java.math.BigInteger, jdbcType=BIGINT},#{img,  jdbcType=BLOB})
    </insert>

    <select id="getKPData" resultMap="kpDataMap">
        SELECT KPID,FNAME,LNAME,SALARY,IMG
        FROM KPDATA
        WHERE KPID=#{kpId}
    </select>

public class KPData {

    private int kpId;
    private String fName;
    private String lName;
    private BigInteger salary;
    private byte[] img;

        //getters and setters

}


text:
Q: Книги по java для тех, кто после прочтения книги планирует стать среднечком Желательно на русском
И хорошо бы такие, pdf версии которых можно было бы скачать или купить в инете прям сейчас. Пока бумажка доедет - ждать долго
p.s Мой уровень таков, что я немогу писать ничего тяжелее, чем усложненные helloword -ы
A: Вот, пожалуйста, хорошие книги по java для тех, кто хочет всерьез заняться программированием на этом языке:

*

*Java 2. Библиотека профессионала,
   том 1. Основы

*Java 2. Библиотека
   профессионала, том 2. Тонкости
   программирования
Сам изучал Java по ним.


text:
Q: Are rings of fractions of integral domains closed under finite intersection? Let $D$ be an integral domain with fraction field $K$.  Let $V$, $W$ be multiplicatively closed subsets of $D$.  Consider the rings of fractions $V^{-1}D$ and $W^{-1}D$ as subrings of $K$.  Is $(V^{-1}D) \cap (W^{-1}D)$ also a ring of fractions of $D$?  That is, does there exist a multiplicative subset $S$ of $D$ such that $(V^{-1}D) \cap (W^{-1}D) = S^{-1}D$?
It seems unlikely, but I am unable to come up with a counterexample.

A: I don't know the full answer to the question, but here's a partial answer:

*

*We always have the inclusion $D_{V \cap W} \subseteq D_V \cap D_W$.

*The reverse inclusion holds, provided that both $V$ and $W$ (or their saturations) are complements of finite unions of primes.

I claim (1) is obvious.  Here's my proof of (2):

Say $V=D \setminus \bigcup_{i=1}^n {\frak p}_i$ and $W = D \setminus \bigcup_{j=1}^m {\frak q}_j$.  Let $\alpha \in D_V \cap D_W$.  Let $I := \{d\in D : d\alpha \in D\}$.  Clearly $I$ is an ideal of $D$.
Suppose $I \subseteq (\cup_i {\frak p}_i) \bigcup (\cup_j {\frak q}_j)$.  Then by prime avoidance, either $I \subseteq {\frak p}_i$ for some $1\leq i \leq n$ or $I \subseteq {\frak q}_j$ for some $1\leq j \leq m$.  But the first statement contradicts $\alpha \in D_V$ (since there is some $v\in V$, hence not in any ${\frak p}_i$, with $v\in I$) and the second contradicts $\alpha \in D_W$ for analogous reasons.
Thus, $I \nsubseteq (\cup_i {\frak p}_i) \bigcup (\cup_j {\frak q}_j) = D \setminus (V \cap W)$, which means that $I \cap (V \cap W) \neq \emptyset$.  Let $d\in V \cap W$.  Then $d\alpha \in D$, so that $\alpha \in D_dfd \subseteq D_{V \cap W}$.

However, I don't know whether your question has a positive answer when $V$, $W$ correspond to infinite unions of primes.  An interesting special case would be when $V$, $W$ correspond to (the saturations of) the powers of single elements.  That is, is $D_x \cap D_y$ always a ring of fractions of $D$, where $x, y \in D \setminus \{0\}$?


text:
Q: How do I add select polyfills using Babel 7 and Gulp? I recently upgraded to Babel 7 using Gulp 4. After deploying my code, I realized there are IE 11 compatibility issues, and also issues with early versions of Microsoft Edge browser (16, 17, 18) where a Symbol is undefined is returned. I'm not using much ES6 in my code yet, but am using features like .includes(), .startsWith.(), and the Spread syntax. I need to add some polyfills for this purpose, but all of my attempts at doing this have been unsuccessful.
The compiled code is just plain old JS file used on a website, and is not part of a React build or anything.
package.json
"devDependencies": {
    "@babel/core": "^7.8.4",
    "@babel/plugin-transform-runtime": "^7.8.3",
    "@babel/preset-env": "^7.8.4",
    "@babel/register": "^7.8.3",
    "babel-eslint": "^10.0.3",
    "del": "^5.1.0",
    "eslint": "^6.8.0",
    "gulp": "^4.0.2",
    "gulp-babel": "^8.0.0",
    "gulp-concat": "^2.6.1",
    "gulp-eslint": "^6.0.0",
    "gulp-rename": "^2.0.0",
    "gulp-terser": "^1.2.0"
},
"dependencies": {
    "@babel/runtime": "^7.8.4",
    "core-js": "^3.6.4",
    "lodash": "^4.17.15"
}

gulpfile.babel.js (including only the function used for the build task)
function createBuildTask(destination) {
    var sourceArray = [ // simplified for this posting
        'file1.js', 'file2.js', 'file3.js', 'file4.js'
    ];

    return function () {
        return gulp.src(sourceArray, {'allowEmpty': true})
            .pipe(babel({
                'presets': ['@babel/preset-env'],
                'plugins': []
            }))
            .pipe(concat('desktop-built.js'))
            .pipe(gulp.dest('desktop/dist'))
            .pipe(terser())
            .pipe(rename({
                'extname': '.min.js'
            }))
            .pipe(gulp.dest('desktop/dist'));
    };
}

What I've tried:

*

*Passing in options to @babel/preset-env, but all I get are a several duplicate lines of var _typeof = require("@babel/runtime/helpers/typeof"); in the built code, which does nothing to resolve the aforementioned errors in IE.
'presets': [['@babel/preset-env', {
    'modules': false,
    'useBuiltIns': 'entry',
    'corejs': 3
}]],
'plugins': ['@babel/plugin-transform-runtime']

*Passing in @babel/preset-env without any options:
"presets": ["@babel/preset-env"],
"plugins": []
But all this does is add the following to my code, and the Symbol is undefined error is still returned in IE.
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Surely it must be easier than this?