text:
Q: MRJob: socket.error: [Errno 104] Connection reset by peer In short: "socket.error: [Errno 104] Connection reset by peer" exception while using MRJob. The script actually has access to S3 because it does create buckets and uploads some small files (I've checked manually via AWS console). But the largest file - INPUT - is not uploaded. Hey, it's just 7GB of test data!
Have tried 4 times, always got errors.
mrjob==0.4.2
CONFIG
# cat /etc/mrjob.conf
runners:
  inline:
    base_tmp_dir: /home/tmp
  emr:
    base_tmp_dir: /home/tmp

    aws_access_key_id: [VALID KEY HERE]
    aws_secret_access_key: [VALID SECRET HERE]
    aws_region: us-east-1
    ec2_instance_type: m1.medium
    num_ec2_instances: 7

TRACEBACK
# python /home/bigdata/mr_job_1.py -r emr  /home/filesystem/INPUT > /home/filesystem/OUTPUT
using configs in /etc/mrjob.conf
creating new scratch bucket mrjob-f02b7cd37b2bfffd
using s3://mrjob-f02b7cd37b2bfffd/tmp/ as our scratch dir on S3
creating tmp directory /home/tmp/mr_job_1.root.20131216.152251.298419
writing master bootstrap script to /home/tmp/mr_job_1.root.20131216.152251.298419/b.py
creating S3 bucket 'mrjob-f02b7cd37b2bfffd' to use as scratch space
Copying non-input files into s3://mrjob-f02b7cd37b2bfffd/tmp/mr_job_1.root.20131216.152251.298419/files/
Traceback (most recent call last):
  File "/home/bigdata/workers/process_data/mr_job_1.py", line 178, in <module>
    MRSwapData().run()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/job.py", line 494, in run
    mr_job.execute()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/job.py", line 512, in execute
    super(MRJob, self).execute()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/launch.py", line 147, in execute
    self.run_job()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/launch.py", line 208, in run_job
    runner.run()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/runner.py", line 458, in run
    self._run()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/emr.py", line 806, in _run
    self._prepare_for_launch()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/emr.py", line 817, in _prepare_for_launch
    self._upload_local_files_to_s3()
  File "/usr/local/lib/python2.7/dist-packages/mrjob/emr.py", line 905, in _upload_local_files_to_s3
    s3_key.set_contents_from_filename(path)
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 1290, in set_contents_from_filename
    encrypt_key=encrypt_key)
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 1221, in set_contents_from_file
    chunked_transfer=chunked_transfer, size=size)
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 713, in send_file
    chunked_transfer=chunked_transfer, size=size)
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/key.py", line 889, in _send_file_internal
    query_args=query_args
  File "/usr/local/lib/python2.7/dist-packages/boto/s3/connection.py", line 547, in make_request
    retry_handler=retry_handler
  File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 947, in make_request
    retry_handler=retry_handler)
  File "/usr/local/lib/python2.7/dist-packages/boto/connection.py", line 908, in _mexe
    raise e
socket.error: [Errno 104] Connection reset by peer

A: I ran into this issue too. I poked around in the code and found that boto raises a PleaseRetryException or an exception of the type self.http_exceptions. Since it's not only one type of exception, and I don't want to import those into my code, I'm instead doing something like this:
should_try_again = True

while should_try_again:
  try:
    method_that_calls_boto()
    should_try_again = False
  except Exception as e:
    print('Exception: %s' % e)
    time.sleep(5)


text:
Q: How to remove duplicates based on a condition? I am trying to write a SQL Query to select all the records.
If a GROUP+SEMIGROUP combination is found as a duplicate, I want to pick up the one where "TOTAL" column is filled, and eliminate the other.
Sample input and output:

A: i share two solution.

*

*the first solution used group by.

create table t (
group_ int,
semi_group VARCHAR(30),
total int,
semi_total int
);

INSERT INTO
    t(group_, semi_group, total, semi_total)
VALUES
    (10,'A',56, null),
    (10,'A',null, 34),
    (11,'G',34, null),
    (12,'H',23, null),
    (13,'J',12, null),
    (13,'J',null, 55);

    select
    group_,
    semi_group,
    sum(total) total, sum(semi_total)
    from t
    group by group_, semi_group;

*use condition, for example if you want total is null and semitotal is not null use semitotal value and if inverse use total.

   select
    group_,
    semi_group,
    case when sum(total) is null and  sum(semi_total) is null then
            0
        when sum(total) is null and  sum(semi_total) is not null then
            sum(semi_total)
        else
        sum(total)
    end total
    from t
    group by group_, semi_group;

the result is this.

group_
semi_group
total

10
A
56

11
G
34

12
H
23

13
J
12

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP, posted value "0" in input causes to skip entire validation First i thought that maybe 0 is accepted by script as demanded string beacuse letters dont have numeric value so they are considered 0 but than i have noticed that validation class isnt even runing when you type 0 to input field and submit it.
I also did the simple test, created most simple form with after post rule:
if($_POST['confirm'] != 'YES') { produce error }
and in simple environement like this it is working however in my application, typing 0 into confirm field causes to skip entire validation and exec's the syntax to db which is extremely weird.
This is file which holds the form and fires validation class upon submitting:
if(Input::exists('post')) {
    $validate = new Validate();
    $validation = $validate->check($_POST, array(
        'confirm' => array(
            'required' => true,
            'confirm' => true,
            'field_name' => 'Potwierdzenie'
        )
    ));

    if($validation->passed()) {
        //exec query
    } else {
        //display errors
    }
}
?>
<form action="" method="post">

        Type "YES" (without quotation marks) to confirm
        <input type="text" name="confirm" id="confirm" autocomplete="off" />

    <input type="submit" value="Usuń" />
</form>

now validation class that checks above conditions:
public function check($source, $items = array()) {
    foreach($items as $item => $rules) {
        foreach($rules as $rule => $rule_value) {

            $value = trim($source[$item]);

            if($rule === 'required' && strlen($value) === 0) {
                $this->addError("{$rules['field_name']} jest wymagany");
            } else {
                switch($rule) {
                    case 'confirm':
                        if($value != 'YES') {
                            $this->addError("{$rules['field_name']} wymaga wpisania \"YES\"");
                        }
                    break;
                }
            }

        }
    }

    if(empty($this->_errors)) {
        $this->_passed = true;
    }

    return $this;
}

additionaly:
class Validate {
    private $_passed = false,
            $_errors = array();

private function addError($error) {
    $this->_errors[] = $error;
}

public function errors() {
    return $this->_errors;
}

public function passed() {
    return $this->_passed;
}

now few facts:

*

*if i just click on submit it returns emptyness error

*if i type lets say 'dnedhned' or '23782372' it returns doesnt match error

*if i type 'YES' it is actualy completing check inside class and allowing exec

*if i type '0' it skipps validation part entirely and right away makes it passed

Does anyone has some idea why is that?
EDIT---------15.07.2014------21:32----
Solved problem was here:
if($rule === 'required' && strlen($value) === 0) {
$this->addError("{$rules['field_name']} jest wymagany");
} else {

This } else { must be changed to } else if(strlen($value) !== 0) {
and in some magic way 0 is no longer considered a term YES,

A: You can try this also radio buttton
<form action="" method="post">

        Select to confirm
        YES <input input type="radio" checked="checked" name="confirm" value="YES" />
        NO <input input type="radio" name="confirm"value="NO" />

    <input type="submit" value="Usuń" />
</form>


text:
Q: How to make a div as wide as its sibling but not wider? I have the following HTML:

    foor bar baz

Yes, I know that div with class "label" should be a label.
The simple question is: how do I ensure that the label is always exactly as wide as the picture and never wider?
The width of the picture and the content of the label are unknown. When the content of the label is longer than the width of the image, it should break to the next line.
Right now, I have "display: inline-block" for the wrapper and everything looks fine when the text fits in the label. When the text is longer, it doesn't break, though, but makes the label longer than the image.
I guess there's a simple solution for this but I'm just not seeing it.
Any help appreciated!

A: an element can't be larger than it's parent so if you put the img tag inside the div it will never be larger.

    foor bar baz

A: Give both elements a width:50%; (or width:49%;, just to be safe) attribute, that should do the trick.


text:
Q: Maya – Aligning the center of one object to the center of another object I'm an animation student and this is the first time I study programing and Python.
My doubt is the following: I have two objects in a maya file: "pSphere1" and "pCone1", and I want to place the pSphere1 center at the center of pCone1, (by center I mean pivot; I want both pivots to be aligned). pSphere1 is the one that should move to the position of pCone1. pCone 1 doesn't move.
So, I was wondering if there is a command in Python that can center both object's pivots.

A: At first select pSphere1, then pCone1 and apply the following command:
import maya.cmds as mc

mc.align(x='mid', y='mid', z='mid', alignToLead=True)

Flag alignToLead=True produces the desired result.


text:
Q: sqlsrv_connect function returns empty string I've been working on an web app who retrieves some data from a SQL Server instance (SQL Server 2008 R2). I'm doing it trough Ajax:
function get_data() {
    $.ajax({
        type: 'POST',
        url: 'get_data.php',
        dataType: 'json',
        success: function(data) {
            console.log(data);
        },
        error: function(e) {
            console.log(e.responseText);
        }
    });
}

The "get_data.php" file:
<?php
    $sqlServerConection=sqlServerConnect('(local)', '1366', 'user', 'password', 'database');
    print json_encode($sqlServerConection);

    function sqlServerConnect($server, $port, $user, $password, $database) {
        $serverName = $server.'\\sqlserver,'.$port;
        $connectionInfo = array("Database"=>$database, "UID"=>$user, "PWD"=>$password);
        $conn = sqlsrv_connect($serverName, $connectionInfo);
        if( $conn === false ) {
            die( print_r( sqlsrv_errors(), true));
        }

        return $conn;
    }
?>

The issue here is that that it always returns an error to ajax. When I check the console log the error message is always empty. If I move any parameter the sqlsrv_connect calling it returns an SQL Server access error, so I assume the function is doing it's work correctly. If I check any log on MAMP they don't show anything. Even the SQL Server log doesn't show a thing.
Any recommendation will be welcome.


text:
Q: Stop embedded swf file I have a video that is in SWF format and I need to have it embedded in another SWF file. This I have no problem with. The video get's embedded, plays when it need, but I can't figure out how to stop it. My code is like this:
var k:Object = new videoClass();
video = k as MovieClip;
parentObject.addChild(video);

Now, when I want to unload the video I call this:
parentObject.removeChild(video);
video.stop();
video = null;

Sadly, the video does unload but I can still hear the sound playing. Any idea how to fix this? Thanks.

A: [EDIT] Why not use video into a video format, like FLV ? SWF is not as optimized for video as FLV is.
The loaded SWF have only a static video into it's timeline, or have any programming on it?
Maybe you're dealing with a SWF with code which makes it play it's video.
If that's the case, you can access public methods from it and control it.
var video:MovieClip = new videoClass() as MovieClip;
parentObject.addChild(video);
...
video.publicMethodToStopAllMedia();
parentObject.removeChild(video);


text:
Q: Is closure is the way to avoid global variable? I know that using global variable is not good practice and programmers should avoid it when possible.
func foo(a *A) func() *A {
    return func() *A {
        return a
    }
}

If I call foo_closure inside another function bar it would mean that output of bar will not depend on its input arguments and bar cannot be pure function.
Now I cannot see a difference between accessing a *A variable by closure or by global variable. In both cases they make an output unpredictable.
Can closure be considered an evil thing as global variable?
P.S
Other functions can also call foo_closure and mutate its fields.

A: The output is unpredictable with a global variable if "something else" besides your function yourfunc changes the global variable's value in between the calls to yourfunc.
But if the variable var is enclosed inside a closure and is accessible only to yourfunc, nothing else has access to it so can't change it so yourfunc's output becomes entirely predictable by the arguments to yourfunc and by yourfunc's actions (like, mutating the enclosed variable var, which can only be done from inside yourfunc).
Which increases safety and purity, which is the whole point to having closures in the first place.
The value of a function depends on its environment, comprised of its arguments, and the enclosed variables.
Another use of closures is when the enclosed environment is shared between several functions, so that only those functions can access and alter the enclosed variables' values.
Having variables global unnecessarily, litters the global name space and makes them liable for erroneous access.


text:
Q: Ceedling testing multiple build variants I have Ceedling working well on a particular code base. But this code base can be compiled with different options based on #defines: for example, add -DSUPPORT_FLOAT, or -DSUPPORT_HEX will compile the code differently. I would like to be able to run the whole test suite on each build variant; that is, compile with one define, test all, compile with a different define, test all, etc.
I have not been able to find/understand how to do this from the documentation.


text:
Q: How do I get a Rectangle drawn on an adorner to scale with the Image element its bound to when the window size is changed? I'm using a rectangle drawn on an adorner to mark a region of interest on an image. The issue is that if I resize the window, the rectangle doesn't change size.
I'm new to WPF, so I've done a bunch of research, googling what I can with multiple different search terms. I actually just learned adorners that way, and I've gotten this far on that, but I've hit a wall on how to finish this last piece. I know that my problem is based in the size of the rectangle, but I don't know what to capture/look for to adjust it, since wpf resizes the actual image object on window resize, so there's no scale factor to look at.
Here's the XAML for the application I'm testing things in.
<Window x:Class="TestingAdorners.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestingAdorners"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
        <Grid ClipToBounds="True">
            <AdornerDecorator>
                <Image Name="Btn" Source="nyan.png" Stretch="Uniform"/>
            </AdornerDecorator>
        </Grid>
</Window>

The adorner class:
    class RoiAdorner : Adorner
    {
        public Rect rectangle = new Rect();
        public RoiAdorner(UIElement adornedElement) : base(adornedElement)
        {
            rectangle.Height = 30;
            rectangle.Width = 100;
            IsHitTestVisible = false;

        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            Pen pen = new Pen(Brushes.Green, 5);

            drawingContext.DrawRectangle(null, pen, rectangle);

        }
    }

And the Xaml.cs
public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AdornerLayer.GetAdornerLayer(Btn).Add(new RoiAdorner(Btn));

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
        }
    }

The desired result is that the rectangle scales with the image object so that it always covers the same region of the image. The problem is I don't know how to capture a scale factor to scale it up and down as the window resizes.
Update: After thinking through Frenchy's suggestion I realized the answer is simply: "Normalize your coordinates"

A: you just adapt your render method like this:
class RoiAdorner : Adorner
{
    public double factorX = 0d;
    public double factorY = 0d;
    public Rect rectangle = new Rect();
    public RoiAdorner(UIElement adornedElement) : base(adornedElement)
    {

        rectangle.Height = 30;
        rectangle.Width = 100;
        IsHitTestVisible = false;

    }

    protected override void OnRender(DrawingContext drawingContext)
    {
        if (factorY == 0)
            factorY =  rectangle.Height / AdornedElement.DesiredSize.Height;
        if (factorX == 0)
            factorX = rectangle.Width / AdornedElement.DesiredSize.Width;
        var r = new Rect(new Size(AdornedElement.DesiredSize.Width * factorX, AdornedElement.DesiredSize.Height * factorY));
        //Rect adornedElementRect = new Rect(this.AdornedElement.DesiredSize);
        drawingContext.DrawRectangle(null, new Pen(Brushes.Red, 5), r);

    }

this.AdornedElement.DesiredSize gives you the size of image.

A: The approach I would use is to render the picture and rectangle to the same thing. Then that one thing is stretched, scaled or whatever.
One way to do this would be to use a DrawingImage.  Drawing methods are extremely efficient if rather low level.
    <Grid ClipToBounds="True">
        <AdornerDecorator>
            <Image Name="img" Stretch="Uniform">
                <Image.Source>
                    <DrawingImage PresentationOptions:Freeze="True">
                        <DrawingImage.Drawing>
                            <DrawingGroup>
                                <ImageDrawing Rect="0,0,595,446" ImageSource="DSC00025.jpg"/>
                                <GeometryDrawing Brush="Green">
                                    <GeometryDrawing.Geometry>
                                        <RectangleGeometry Rect="0,0,100,30"  />
                                    </GeometryDrawing.Geometry>
                                </GeometryDrawing>
                            </DrawingGroup>
                        </DrawingImage.Drawing>
                    </DrawingImage>
                </Image.Source>
            </Image>
        </AdornerDecorator>
    </Grid>

Another is with a visualbrush.  Controls inherit from visual - this is somewhat higher level coding.
    <Grid ClipToBounds="True">
        <AdornerDecorator>
            <Rectangle Name="rec">
            <Rectangle.Fill>
                <VisualBrush Stretch="Uniform">
                    <VisualBrush.Visual>
                        <Grid Height="446" Width="595">
                            <Image Source="DSC00025.jpg" Stretch="Fill"/>
                            <Rectangle Height="30" Width="100" Fill="Green"
                                       VerticalAlignment="Top" HorizontalAlignment="Left"/>
                        </Grid>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Rectangle.Fill>
            </Rectangle>
        </AdornerDecorator>
    </Grid>

Note that both of these are quick and dirty illustrations to give you the idea. The image I picked at random off my hard drive is sized 446 * 595.  You could calculate sizes or bind or stretch as suits your requirement best.


text:
Q: Spring Maven DispatcherServlet noHandlerFound I am new to java world. I am following one tutorial to learn java.
The tutorial using Spring framework and maven build.
but when I reached the part to use DispatcherServlet, mine doesn't work as it suppose.
It shows this on console:
org.springframework.web.servlet.PageNotFound noHandlerFound

WARNING: No mapping found for HTTP request with URI [/index.html] in DispatcherServlet with name 'dispatcher'
and browser can't load just simple hello world string. browser says
HTTP ERROR 404
Problem accessing /index.xml. Reason:
Not Found
Powered by Jetty://

This seems common problem becasue there are a lot of discussions about this.
I have read several of them and tried some answers but nothing helps. Can anyone check my code and point out what might cause this problem?
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<display-name>TestApplication</display-name>
<welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
 <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.html</url-pattern>
    <url-pattern>*.htm</url-pattern>
    <url-pattern>*.json</url-pattern>
    <url-pattern>*.xml</url-pattern>
</servlet-mapping>
</web-app>

dispacher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="my.testApplication.controller" />
</beans>

IndexController.java
package my.testApplication.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

@Controller
public class IndexController {

  @RequestMapping("/index")
  public String index(){
    return "WEB-INF/jsp/index.jsp";
  }
}

index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

hello from spring web mvc
</body>
</html>

Additional comment (solution): it was right reference, I made some mistakes and then it didn't work afterwards even with the right code. when this kind of situation (after mistakes and back to right code - still not working), then need to perform 'Project - clean' before run. (maybe the basics.) So that solved. Thanks.

A: It should be @RequestMapping annotation.
@RequestMapping(value="/index")
  public String index(){
    return "WEB-INF/jsp/index.jsp";
  }


text:
Q: Best way to groupby when there are NaN's I have a previously merged panel dataset that looks like this:
ID | date
01 | 01/01/2020
01 | 02/01/2020
01 | 03/01/2020
02 | NaN
03 | 15/02/2020
03 | 17/02/2020

As you can see, there are some IDs that don't have any related date. Date is in string format, not datetime.
I'm interested in getting a dataframe with one row per ID, where only the last date is shown.
It should look like this:
ID | date
01 | 03/01/2020
02 | NaN
03 | 17/02/2020

I tried a few ways like:
grouped = data1.groupby(["ID"]).last() but that will not include the ID's that have NaN date.
Any ideas? I'm sure this is fairly simple but I don't have much experience with merge and groupby's


text:
Q: MySQL NodeJS not getting latest data after write I am having trouble figuring out the problem to an issue where when I write data (create, update, delete) then write a query to get the data after, the data that I receive back is the data prior to the write.
For example:
Let's say I have two functions createApple() and getAppleById. I have a utility function called getConnection() that gets a connection from a pool to be used for transactional queries. I have an endpoint that creates an apple and I get back to the insertId from mysql then I use that to get the apple but when I return it as a response, I get an empty object.
const createApple = async ({ type }) => {
    const connection = await getConnection();
    await connection.beginTransaction();
    return await connection.query(`INSERT INTO apple (type) VALUES (?)`, [type]);
}

const getAppleById = async (appleId) => {
   const connection = await getConnection();
   return await connection.query(`SELECT * FROM apple WHERE id = ?`, [appleId]);
}
router.post(`/api/apples`, async (req, res) => {
    const { insertId: createdAppleId } = await createApple({ ...req.body });
    const apple = await getAppleById(createdAppleId);
    res.status(201).send(apple); // <-- this returns {}
});

I noticed that if I add a console.log() before sending the data back, it does get back the data, for example:
router.post(`/api/apples`, async (req, res) => {
    const { insertId: createdAppleId } = await createApple({ ...req.body });
    const apple = await getAppleById(createdAppleId);
    console.log(apple);
    res.status(201).send(apple); // <-- this now returns the newly created apple
});

Any ideas on why this may be happening? Also, is this considered a good way of getting a newly created/updated entity or would it be better to make two separate calls:

*

*First call to create/edit the entity (a POST or PATCH call)

*Second call to get the entity (a GET call)

Any help is appreciated!
Thanks!

A: const createApple = async ({ type }) => {
    const connection = await getConnection();
    await connection.beginTransaction();
    await connection.query(`INSERT INTO apple (type) VALUES (?)`, [type]);
    await connection.commit();
}

I think error this function when you use transaction, you should commit or rollback transaction after finish query
This is best practice for me, I hope it useful for you
const createApple = async ({ type }) => {
    const connection = await getConnection();
    await connection.beginTransaction();
    try{
        await connection.query(`INSERT INTO apple (type) VALUES (?)`, [type]);
        await connection.commit();
    }catch{
        await connection.rollback()
    }
}


text:
Q: objective c - How to convert nsdata to byte array I am working with UIImage conversion to NSData. And I want to convert NsData to Byte Array and post that Byte array to server with the help of json Parser.
If i am passing following type of static string to server it accept and store. Following is just example string syntax. i want follwoing type of byte array to post data to server.
[255,216,255,224,0,16,74,70,73,70,0,1,1,1,0,96,0,96,0,0,255,219,0,67,0,8,6,6,7,6,5,8,7,7,7,9,9,8,10,12,...]
For above result i am converting image to data as following:
UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);

Now i want to convert NSdata to byte array for that i am using following code:
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);
free(byteData)

and i also store this to NSdata. but cant get about result.
I also typed about code with looping but every time it gives aPNG as result.
Am i doing any thing wrong in the above code?
Please provide me some help and also request to provide any help for this.
Thanks in advance.

A: I'm not 100% sure this is what you are looking for or not. Try:
UIImage *image = [UIImage imageNamed:@"image.png"];
NSData *data = UIImagePNGRepresentation(image);
NSUInteger len = data.length;
uint8_t *bytes = (uint8_t *)[data bytes];
NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
[result appendString:@"["];
for (NSUInteger i = 0; i < len; i++) {
    if (i) {
        [result appendString:@","];
    }
    [result appendFormat:@"%d", bytes[i]];
}
[result appendString:@"]"];

Is this what you need?


text:
Q: Hosting site using xampp server from local network without port-forwarding I want to make my site available world wide. Im using xampp server for hosting. I have no access to any kind of servers and modems. Situation is shown below:
My site server has local ip assigned by wifi router and it runs Windows 8.
Remember I have no access on any kind of servers and modems so port port-forwarding is impossible (out of my scope).

A: Its actually difficult, but not impossible.
One way, I would approach this is:

*

*I would host a page on internet.

*Then take request and store it in database.

*One of my program will always be running from my computer.

*Then check for request and curl the request to localhost. For this you may use Node.js (taking data from database using GET method and curl it to localhost).
This is the best I could think of. And I am working on it, when the code is ready I'll make it open source and notify you :)
But still, it's difficult, as you need to put user's request to sleep for 2 seconds and then transferring it.
Its slow, but may work out for you.

Disadvantages:

*

*Program will be very slow and memory usage will be more.

*Breaking may happen many times.

*High bandwidth wastage

*If not encrypted, MIM (Men in Middle) may possible.
Advantages:

*

*Indirect method of hosting

*Need not to worry about your code being lost.

I am looking forward for a better alternative and I would like to keep this question for bounty once again.

A: If you cannot open the necessary ports within your LAN you will require access to an external server. However, the external server does not need to host any code, e.g.

*

*Create a Linux based ec2 instance using Amazon's free tier.

*Install a package to redirect remote to local ports:
a. using socat:

*

*Install socat using your distributions package manager

*Connect via SSH: ssh -N -R 42500:127.0.0.1:80 -o ServerAliveInterval=60 ubuntu@xxx.xxx.xxx.xxx -N -R 8080:localhost:80 "socat TCP-LISTEN:8080,fork TCP:127.0.0.1:42500"
b. using a webserver and reverse proxy:

*

*Install apache or nginx and any required reverse proxy modules and configure your VirtualHost to proxy requests to a local port, e.g. :8080 -> 127.0.0.1:42500

*Connect via SSH: ssh -N -R 42500:127.0.0.1:80 -o ServerAliveInterval=60 ubuntu@xxx.xxx.xxx.xxx

*Your machine is now reachable via the ec2 instance http://xxx.xxx.xxx.xxx:8080/.
I occasionally use this technique when debugging web service callbacks.

Update 17-02-2014
If you are a Windows user you will need to install a third-party tool to support ssh. Options include:

*

*cygwin

*git bash

*PuTTY
PuTTY is the easiest choice if you are not familiar with *nix tools. To configure remote port forwarding in PuTTY expand the following setting: Connection -> SSH -> Tunnels. Given the previously described scenario, populate Source port as 42500, Desination as 127.0.0.1:80 and tick the Remote option. (You may also need to add the path to a PuTTY compatible private key in the Connection -> SSH -> Auth tab depending on your server configuration.

To test you have successfully forwarded a port, execute the command netstat -lnt on your server. You will see output similar to:
tcp     0    0    127.0.0.1:42500    0.0.0.0:*    LISTEN

Finally you can test with curl http://127.0.0.1:42500. You will see the output of your own machines web root running on port 80.

A: if you don't have a public IP address and cannot use port forwarding it is impossible to host the site

A: As people have said you need a public IP address. However, even if you did you should not use xampp as a public server, as it is designed for development and therefore has some security settings disabled.
I would recommend buying some shared web hosting, and uploading it to that. (you can get cheap hosting if you google 'shared web hosting', plus free .tk domains are avaliable: http://www.dot.tk/)

A: Do your company has any vpn network?
If it does and you have access to the vpn network, you can include your server to the vpn network and your guest will only need to login to your company vpn network then access your site like in a local network without using port forwarding. And since your data is very confidential, I assume that using vpn will also help to increase the security of your data.
Please correct me if I'm wrong.
Thank You.

A: Lets break it into steps.

*

*To host your site locally you will need a IP that is static so that
users can access it specifically.

*You will need a domain so that it can be converted into user friendly name.

*A 24x7 Internet Connection is must! You added a Wifi Router in your Diagram and most of today's router are capable of port forwarding.

What i will do in your scenario is:

*

*Instead of using XAMP, i will install WAMP because i am more familiar with it and easy to configure.(totally personal preference)

*Then i would set my server "ONLINE".(Google how to set WAMP server online)

*Forward port "80" from router settings to my local computer ip address.(mostly it is tagged as "Virtual Server","Firewall","Port Forwarding",etc vary router to router in settings)
Suppose you have a local ip "192.168.1.3" and global/router IP "254.232.123.232" then you would redirect all the HTTP request done towards router to your local IP.
[[[[254.232.123.232]]]] --+ :80 +-- --------->192.168.1.3

*That is good for now, but then you will need to tackle dynamic IP problem of router. But don't worry, thanks to some free sites that will be easy!

*Go to no-ip.org -> Setup Account -> and create a entry, just a subdomain for now to test whether everything is working fine.(subdomain like mysite.no-ip.org, later purchase a real Domain)

*Input your IP address there(Router IP) and download its application which will automatically update their server if your local IP changes.

*Wait for some minutes and Voila! Your site is live.

A: What you are asking is not possible without port forwarding.


text:
Q: php session_write_close() not commit until script execute complete? I test this script in chrome.
<?php
session_start();
if(isset($_SESSION['ddd']) && $_SESSION['ddd']) {
    exit("SESSION is set");
} else {
    $_SESSION['ddd'] = true;
    session_write_close();
    //session_commit() is also not work
    sleep(5);
    exit("SESSION is working");
}

I open the PHP file in Chrome, and it echoes "SESSION is working" after 5 seconds.
If I open the file in a new tab before 5 seconds have elapsed, it echoes "SESSION is working", instead of "SESSION is set".
To confirm, if I open the file in a new tab after 5 seconds have elapsed, it does echo "SESSION is set".
Why? Does session_write_close  not commit session data immediately? If it is so, should I want to commit the session immediately, how might I do?

A: I think you did something wrong:
Never open multiple tabs before you have the PHPSESSID cookie, or you will get the unexpected result.
The first time you run the script, you don't have the PHPSESSID cookie yet. And you run the script again before the first request is done, you will get a NEW session (different session_id), so you won't get the session data of the first request.
Therefore, you should ensure that you have the PHPSESSID in your browser cookies.
Change the code to
session_start();
var_dump($_SESSION);
$_SESSION['val'] = isset($_SESSION['val']) ? ++$_SESSION['val'] : 0;
session_commit();
sleep(5);
exit;

First, run the script once, waiting until it's done.
Then open second tab and third tab in 5 seconds.
Now you will get different values.

1st tab: array(0) { }
2nd tab: array(1) { ["val"]=> int(1) }
3rd tab: array(1) { ["val"]=> int(2) }

It shows that the 3rd tab got the correct value after 2nd tab session_commit.

A: I am sorry that maybe I have found the reason!
1、It is the reason about the sleep function! if using the sleep,the script file will be blocked. When a new request about this php file will be excute after 5 seconds later.If use another php file with same code will be better.
2、Someone said that a new session will be not fast enough.Just look at this link,the third tip!
enter link description here
Now,I should create the session first.
OK,I create three php files.
fisrt - index.php to set the session;
<?php
session_start();
$_SESSION['ddd']=1;
session_commit();
?>

second -index2.php
<?php
session_start();
if(isset($_SESSION['ddd']) && $_SESSION['ddd']==2)
{
echo("SESSION is set");
}
else {
$_SESSION['ddd'] = 2;
session_commit();
echo "SESSION is working";
sleep(5);
}
?>

third index3.php
 <?php
session_start();
if(isset($_SESSION['ddd']) && $_SESSION['ddd']==2)
{
echo("SESSION is set");
}
else {
$_SESSION['ddd'] = 2;
session_commit();
echo "SESSION is working";
for ($i=0;$i<10000000;$i++)
{
if(file_exists('sdsd'));
}
}
?>

It is very interesting.
fisrt lab:
open the index.php first.
then open the index2.php in two tabs,you will see, the second tab of index2.php echo 'SESSION is set'  but,it will return after 5 seconds,yeah,sleep function block it,but the session has written.Good news.
second lab:
open the index.php first.
then open the index2.php,index3.php in two tabs,you will see, the second tab echo 'SESSION is set' very fast!
Someone else if interesting with this can give me more help!


text:
Q: Copy ResourceStream In Stream I need help in this code
This is all code
Request: TIdHTTPRequestInfo
Response: TIdHTTPResponseInfo
JQuery: TResourceStream
procedure TServer.ActiveServer;
begin
  DefaultPort := 8117;
  Active := True;
  OnCommandGet := FServerCommandGet;
  JQuery := TResourceStream.Create(HInstance,'JQuery',RT_RCDATA);
end;

function TServer.FindFiles: Boolean;
var
  Stream : TStream;
begin
  if Request.Document = '/jquery.js' then
  begin
    Response.ContentType := 'application/x-javascript';
    Stream := TStream.Create;
    Stream.Position := 0;
    Stream.CopyFrom(JQuery,JQuery.Size);
    Response.ContentStream := Stream;
    Result := True;
  end else
    Result := False;
end;

error : TStream.Seek not implemented
The problem is in the copy TResourceStream in TStream

A: TStream is an abstract class so it cannot be used directly, you must use one it's descendants. TResourceStream for example.
P.S : I see that you are dealing with Indy, no need to free the stream when assigned to ContentStream, Indy will handle that for you.
function TServer.FindFiles: Boolean;
var
  Stream : TResourceStream;
begin
  if Request.Document = '/jquery.js' then
  begin
    Response.ContentType := 'application/x-javascript';
    Response.ContentStream := TResourceStream.Create(HInstance, 'JQuery', RT_RCDATA);
    Result := True;
  end else
  begin
    Result := False;
  end;
end;


text:
Q: How do you disable a checkbox on the page_load event? how to auto disable asp.net checkbox1 on page_load event ?
only vb.net code required !!

A: Disabling a checkbox is easy
checkbox1.Enabled = False

In the Page_Load event, it would look something like this.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    ''# checkbox1 should not be enabled on page load.
    checkbox1.Enabled = False
End Sub

A: protected sub page_load
 checkboxname.Enabled = false
end sub


text:
Q: How to use Sys.Services.AuthenticationService works and what could prevent it from working My website uses Sys.Services.AuthenticationService in order to do an ajax style login.
Right now it's contained within
$(document).ready(function() { });

here's the very beginning of the javascript code... (You can read the full implementation here)
alert("1");
var ssa = Sys.Services.AuthenticationService;
alert("2");

The first alert fires and the second one doesn't... any idea of why this wouldn't work? Is there something I need to include in my website like an external resource? Or could it be that it's within the $(document).ready function?
Any ideas/suggestions are greatly appreciated! If you need any more information just let me know. I'll add updates as I find out more.
Update: I just wanted to add a few things...

*

*I'm running on Asp.Net MVC

*Here is the tutorial I followed -- Client-side Ajax Login
Thanks,
Matt

A: I didn't include the MicrosoftAjax.js and MicrosoftMvcAjax.js files so it couldn't find the Sys.Services.AuthenticationService.
Didn't notice this because in WebForms, asp.net ajax is built right in, there's no need to reference the file.


text:
Q: Providing readonly value in twig file returns null in symfony3.2 In my application form updation twig is as follows:
<div class="form-group">
    {{form_label(formUser.name)}} :
   <input class="form-control" disabled="disabled" value="{{formUser.name.vars.value}}" type="text">
   <input id="appbundle_user_name" name="appbundle_user[name]" value="{{formUser.name.vars.value}}" type="hidden">
</div>

It returns null value when updating the form how to solve this issue,to get the output?

A: disabled is not the same as readonly, it will not be included in the POST variables if that is where the value is null.


text:
Q: Modular which is metrizing but does not satisfy the $\Delta_2$ condition Let $\Phi$ be a nice Young function (N-function) and $(\Omega,\mathcal{F},P)$ a probability space such that either $P$ is diffuse on a set of non-zero probability or $P$ is purely atomic and there are infinitely many atoms. In other words $(\Omega,\mathcal{F},P)$ is not a finite probability space.
It is said that function $\Phi$ satisfies the $\Delta_2$ condition at infinity if there is $K>0$ and $u_0\ge 0$ such that
$$ \Phi(2u)\le K\Phi(u) \text{ for all }u\ge u_0.$$
It is said that modular $m$ given by $m(X):=E[\Phi(X)]$ is metrizing if for every sequence of random variables $\{ X_n\} $ one has that $m(X_n)\to 0$ implies $m(2X_n)\to 0$.
Give an example of a Young function that does not satisfy the $\Delta_2$ condition, together with a (purely atomic but infinite) probability space on which the corresponding modular is metrizing; or,
prove that such an example does not exist.
It is known that

*

*such an example does not exist if $P$ is diffuse on a set of non-zero probability;

*such an example does exist on a purely atomic space with infinitely many atoms if the measure $P$ is allowed to be infinite (not a probability measure anymore);

*on a finite probability space every N-function modular is trivially metrizing regardless of the $\Delta_2$ condition on $\Phi$.


text:
Q: Closure of an operator I am wondering what is the closure of the domain of the operator $A_0:D(A_0)(\subset H)\to H$in $H=L^2(0,1)$
$$A_0= f^{(4)}-f^{(6)}$$
$$D(A_0)=\big\{ f\in H^6(0,1)\cap H_0^3(0,1) |f^{(3)}(1)=f^{(4)}(1)=f^{(5)}(1)=0\big\}$$

A: The closure of the domain in $L^2$ is simply $L^2$: Obviously it holds $C_0^\infty(0,1)\subset D(A_0)$. The set of smooth function is dense in $L^2(0,1)$, hence its closure is $L^2(0,1)$. This implies that the closure of $D(A_0)$ is $L^2(0,1)$ as well.


text:
Q: How to use datetime filter in django just for day and month? I need to filter objects of users in a viewset whose birthday is today. Here, I will just need to check it with today's day and month irrespective of year. How do I do that?

A: *

*get the date and month of day.

from datetime import datetime

today_day = datetime.now().day
today_month = datetime.now().month

*filter objects like following.

today_birthdays = YourModelName.objects.filter(
    birthdate__day=today_day, birthdate__month=today_month
    )

here birthdate is your datetime field on which you want to filter.
if you want to add year also in the filter, you ll have to add birthdate__year. it is double underscore which does the magic.


text:
Q: Live update international space station location in Cartopy map I'm working on simple script to locate ISS on a world map using cartopy. Here's the code and its output
import requests
from datetime import datetime
import cartopy.crs as ccrs
import matplotlib.pyplot as plt

# finding the current location
url = 'http://api.open-notify.org/iss-now.json'

r = requests.get(url)
data = r.json()

dt = data['timestamp']
lat = data['iss_position']['latitude']
lon = data['iss_position']['longitude']

print('Date and time : ',datetime.fromtimestamp(dt))
print('Latitude :',lat)
print('Longitude :',lon)

# plotting the location on map
plt.figure(figsize=(10,8))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

# lon lat
plt.scatter(float(lon),float(lat),color='blue', marker='o')
plt.show()

This part is working fine and here is the output.

Now what i want is that after every 30 seconds to make a request to the url, and plot the location on the map clearing the previous location. Is it possible to do with matplotlib. I don't know much about matplotlib. Kindly help.
My current code creates new plots everytime with scatters on them. I want only one map with current location and previous location erased.
Here's my current code
import requests
import matplotlib.pyplot as plt
import time
import cartopy.crs as ccrs

url = 'http://api.open-notify.org/iss-now.json'

plt.figure(figsize=(10,8))

ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

plt.ion()

while True:
    r = requests.get(url)
    data = r.json()

    dt = data['timestamp']
    lat = data['iss_position']['latitude']
    lon = data['iss_position']['longitude']

    plt.scatter(float(lon),float(lat),color='blue', marker='o')
    plt.show()
    time.sleep(30)

A: matplotlib.animation.FuncAnimation exists specifically for this kind of plot. Try this
import requests
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import time
import cartopy.crs as ccrs

url = 'http://api.open-notify.org/iss-now.json'

plt.figure(figsize=(10,8))
ax = plt.axes(projection=ccrs.PlateCarree())
ax.stock_img()

plt.ion()
plt.show()
s = plt.scatter([], [], color='blue', marker='o')

def animate(i):
    r = requests.get(url)
    data = r.json()

    dt = data['timestamp']
    lat = data['iss_position']['latitude']
    lon = data['iss_position']['longitude']

    s.set_offsets([float(lon), float(lat)])
    time.sleep(30)

anim = FuncAnimation(plt.gcf(), animate)
plt.show()

This will show (sped up for demonstration):


text:
Q: How to print \unit with "quantity-product" in siunitx? siunitx allows us to print numbers, units and quantities, the later understood as a combination of numbers and units. For that we have, respectively, \num, \unit and \qty.
Using \qty{<number>}{<unit>} is not the same as just juxtaposing \num{<number>}\unit{<unit>}, since \qty takes care of proper spacing between number and unit, as per the option quantity-product. So far, so good.
However, I'd like to be able to split the number from the unit and still get the spacing from quantity-product. The use case is a table, where I'd like to use an S column, and pass the unit in the table's preamble to all numbers in the column.
Now, I know most everyone here will tell me I should not add the unit to each number but should rather just give it once in the table's header. I agree this is usually best practice. But I have a case where the header is already crammed, and the numbers and units are short, so I think my table would look better if I did it this way. So, regardless of table formatting best practices and taste, I'm looking for a technical solution for the situation.
The MWE below summarizes the situation:
\documentclass{article}

\usepackage{siunitx}
\usepackage{array}

\begin{document}

\begin{tabular}{
  S[table-format = 4.0, group-digits = false]
  S[table-format = 1.1{\unit{\percent}}]<{{\unit{\percent}}}
  }
  \hline
  & \multicolumn{1}{c}{$\frac{\text{imports}}{\text{apparent consumption}}$} \\
  \hline
  1924 & 3,7 \\
  1925 & 3,4 \\
  1926 & 3,6 \\
  1927 & 4,0 \\
  1928 & 3,8 \\
  1929 & 4,0 \\
  1930 & 4,5 \\
  1935 & 4,7 \\
  1936 & 4,4 \\
  1937 & 3,3 \\
  \hline
\end{tabular}

\end{document}

The above example, of course, is missing the space between the numbers and the units in the second column. So I'm trying to get a, let's say, \qtyunit macro to use instead of \unit there.
I have tried a couple of alternatives, but I'm not really confident in or satisfied with either. The first one was:
\NewDocumentCommand\qtyunit{m}{\qty[print-unity-mantissa=false]{1}{#1}}

This looks nice, and gets the job done. But I'm not really sure if I should rely on passing 1 as number with print-unity-mantissa=false actually printing the quantity-product. This seems very much as a side-effect, which might change (one could argue it should not be printed), and the effect is not documented.
(siunitx does allow to pass an empty number argument to \qty, but the case is treated specially, and quantity-product is skipped).
So I went to siunitx.sty and cooked (based on the definition of \unit):
\ExplSyntaxOn
\NewDocumentCommand \qtyunit { O { } > { \TrimSpaces } m }
  {
    \mode_leave_vertical:
    \group_begin:
      \siunitx_unit_options_apply:n {#2}
      \keys_set:nn { siunitx } {#1}
      % print quantity-product spacing, from '\siunitx_quantity_print'
      \tl_use:N \l__siunitx_quantity_product_tl
      \bool_if:NTF \l__siunitx_quantity_break_bool
        { \penalty \binoppenalty }
        { \nobreak }
      % now print the unit proper
      \siunitx_unit_format:nN {#2} \l__siunitx_tmp_tl
      \siunitx_print_unit:V \l__siunitx_tmp_tl
    \group_end:
  }
\ExplSyntaxOff

But this, while it works, leaves me the sensation of being much overkill for this purpose.
So, the question is, am I missing something in siunitx from which I could get this in a more straightforward and robust way? If not, does anyone see an alternative which would be better than either of the two above?
Edit: I came up with a third alternative:
\NewDocumentCommand\qtyunit{m}{\qty[parse-numbers=false]{\relax}{#1}}

Looks promising, but it still feels like cheating somewhat.

A: In the example below, the contents of each cell in the second column is collected, using collcell package, then passed to \mynum as its argument (like \mynum{<cell contents>}).
That is, the spec for the second column
S[table-format = 1.1{\unit{\percent}}]<{{\unit{\percent}}}
% is replace with
>{\collectcell\mynum}c<{\endcollectcell}

\documentclass{article}

\usepackage{siunitx}
\usepackage{array}
\usepackage{collcell}

\newcommand\mynum[1]{%
  \qty{#1}{\percent}%
}

\begin{document}

\begin{tabular}{
  S[table-format = 4.0, group-digits = false]
  >{\collectcell\mynum}c<{\endcollectcell}
  }
  \hline
  & \multicolumn{1}{c}{$\frac{\text{imports}}{\text{apparent consumption}}$} \\
  \hline
  1924 & 3,7 \\
  1925 & 3,4 \\
  1926 & 3,6 \\
  1927 & 4,0 \\
  1928 & 3,8 \\
  1929 & 4,0 \\
  1930 & 4,5 \\
  1935 & 4,7 \\
  1936 & 4,4 \\
  1937 & 3,3 \\
  \hline
\end{tabular}

\end{document}

See more collcell examples in package manuals of both collcell and siunitx.

A: In v3 there are a number of code-level interfaces that are used for communication between sub-modules, but which are not directly exposed as document commands. Here, you are really after \siunitx_quantity_print:nn, which prints a pre-formatted quantity and which will accept a missing numerical part. (This is needed for example in printing complex quantities.)
We first need to format the unit, then pass it to the printing routine.
\documentclass{article}

\usepackage{siunitx}
\usepackage{array}
\ExplSyntaxOn
\NewDocumentCommand \qtyunit { m }
  {
    \siunitx_unit_format:nN {#1} \l_tmpa_tl
    \siunitx_quantity_print:nV { } \l_tmpa_tl
  }
\ExplSyntaxOff

\begin{document}

\begin{tabular}{
  S[table-format = 4]
  S[table-format = 1.1{\qtyunit{\percent}}]<{{\qtyunit{\percent}}}
  }
  \hline
  & \multicolumn{1}{c}{$\frac{\text{imports}}{\text{apparent consumption}}$} \\
  \hline
  1924 & 3,7 \\
  1925 & 3,4 \\
  1926 & 3,6 \\
  1927 & 4,0 \\
  1928 & 3,8 \\
  1929 & 4,0 \\
  1930 & 4,5 \\
  1935 & 4,7 \\
  1936 & 4,4 \\
  1937 & 3,3 \\
  \hline
\end{tabular}

\end{document}


text:
Q: nginx proxy_cache: limit parallel requests for the same URL We're using nginx as a reverse proxy to get files from upstream servers.
The files are not dynamic – at least not on a per request basis – and are (sometimes) behind high latency.
I would like to limit the request for the same URL to exactly 1.
An example of the behaviour I want to avoid:
127.0.0.1 - - [03/Jan/2013:16:08:15 +0100] "GET /part-00132.ts HTTP/1.0" 200 1506068 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:28 +0100] "GET /part-00133.ts HTTP/1.0" 200 1189476 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:29 +0100] "GET /part-00133.ts HTTP/1.0" 200 1189476 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17" "-"
127.0.0.1 - - [03/Jan/2013:16:08:34 +0100] "GET /part-00133.ts HTTP/1.0" 200 1189476 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:44 +0100] "GET /part-00134.ts HTTP/1.0" 200 1762876 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17" "-"
127.0.0.1 - - [03/Jan/2013:16:08:53 +0100] "GET /part-00135.ts HTTP/1.0" 200 1627704 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:59 +0100] "GET /part-00136.ts HTTP/1.0" 200 1252456 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:03 +0100] "GET /part-00134.ts HTTP/1.0" 200 1762876 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:04 +0100] "GET /part-00137.ts HTTP/1.0" 200 1120292 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:07 +0100] "GET /part-00135.ts HTTP/1.0" 200 1627704 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17" "-"
127.0.0.1 - - [03/Jan/2013:16:09:12 +0100] "GET /part-00134.ts HTTP/1.0" 200 1762876 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:14 +0100] "GET /part-00136.ts HTTP/1.0" 200 1252456 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:17 +0100] "GET /part-00135.ts HTTP/1.0" 200 1627704 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:17 +0100] "GET /part-00138.ts HTTP/1.0" 200 1248884 "-" "Prefetch" "-"

It should be like this:
127.0.0.1 - - [03/Jan/2013:16:08:15 +0100] "GET /part-00132.ts HTTP/1.0" 200 1506068 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:28 +0100] "GET /part-00133.ts HTTP/1.0" 200 1189476 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:44 +0100] "GET /part-00134.ts HTTP/1.0" 200 1762876 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17" "-"
127.0.0.1 - - [03/Jan/2013:16:08:53 +0100] "GET /part-00135.ts HTTP/1.0" 200 1627704 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:08:59 +0100] "GET /part-00136.ts HTTP/1.0" 200 1252456 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:04 +0100] "GET /part-00137.ts HTTP/1.0" 200 1120292 "-" "Prefetch" "-"
127.0.0.1 - - [03/Jan/2013:16:09:17 +0100] "GET /part-00138.ts HTTP/1.0" 200 1248884 "-" "Prefetch" "-"

Update:
A diagram to describe the problem a little bit:
            nginx              upstream
           +-----+            +--------+
           |     |            |        |
   A +----->     +-----------------+   |
           |     |            |    |   |
   B +----->     +--------------+  |   |
           |     |            | |  |   |
     <-----+     <--------------|--+   |
           |     |            | |      |
     <-----+     <--------------+      |
           |     |            |        |
   C +----->     +---+        |        |
           |     |   |        |        |
     <-----+     <---+        |        |
           |     |            |        |
           +-----+            +--------+

So I want client B to wait for the A response.

A: One potential solution for you is caching. When using either proxy pass or fcgi pass with nginx, you have the option to cache the return data for a period of time. You can read more about it in the docs: proxy pass and fcgi version. The two are virtually identical to each other in how they work.
I also suggest looking up some tutorials on it since how the parts of the caching operatives work together aren't entirely trivial from the docs.
But the main idea is that you make a proxy "key" from your URL (in your case). And you can then set it to cache it for 10min or something. So the subsequent calls are served from the local cache instead of fetching it again.
You can then prevent subsequent requests during update by setting:
proxy_cache_use_stale updating;

A: Taken from answer to Nginx how to disable multithread downloads:
Use the nginx example for the limit_conn configuration:
limit_zone one $binary_remote_addr 10m;

server {
  location /download/ {
    limit_conn one 1;
  }
}

It's not just download managers with Range requests that multiplex downloads (and this does not disable Range headers); modern browsers loading pages multiplex requests as well.  Be very careful about using this configuration anywhere expect a location that you need to specifically prevent multiplexed downloads for.


text:
Q: How do I disable CakePHP's client side email validation? The kind of validation that pops out even before sending the data to the server. The other fields in my form, namely 'name', 'message', had these too but I removed that by taking their respective validators in my FormTable. Did the same for the email validator  but its still there.
The email field checks for the email's validity (having '@' and dots).
This is the form in my view. $form is just an array that will contain values passed through sessions.:
<?= $this->Form->create($message, ['class' => 'form-group']) ?>
<?= $this->Form->input('name', ['value' => $form['name']]) ?>
<?= $this->Form->input('email', ['value' => $form['email']]) ?>
<?= $this->Form->input('message', ['value' => $form['message']]); ?>
<?= $this->Form->button('Submit', ['class' => 'btn btn-primary btn-lg btn-block']) ?>
<?= $this->Form->end() ?>

Im not really sure why my code is needed so sorry, but when creating an email field, following the cake's convention, the client side validation is built in and that's what I'm trying to get rid of.

A: It is not cake that does that, its HTML5
If you want to disable client side validation for a form in HTML5 add a novalidate attribute to the form element. Fx:
   <?= $this->Form->create($message, ['class' => 'form-group', 'novalidate' => true]) ?>

wich will result in something like:
<form method="post" action="/foo" novalidate>...</form>

See https://www.w3.org/TR/html5/sec-forms.html#element-attrdef-form-novalidate


text:
Q: Updating an activity's data from a service I have a service running, and one of its tasks is to regularly fetch data from an external web host. Upon finding new data, the service should update the main activity to show the most recent text. There is no need for the activity to be in the foreground during an update, but when the activity is resumed, it should reflect the most recent data from the service.
My current implementation is a bit odd, and I cannot help but think there should be a better way to do it. My approach is the following:
The activity (MainActivity) implements a custom interface OnDataChangedListener. In the MainActivity's onCreate, it calls a static method of the service to register itself (MyService.addDataChangedListener(this)).
When the service finds a data changed, it iterates over its list of listeners and calls onDataChanged(newData). Finally, the MainActivity's onDataChanged method will change the activity's text to reflect the new data.
In onPaused, I plan to unregister the listener, and re-register it in onResume. onResume will also call MyService.getDataset() to get the most recent data upon resuming the application.
This approach seems like it would not live well within the lifecycle of Android applications. Does anybody know of a better way to handle this?
Thanks!

A: When service gets new data:

*

*Saves data to your custom Application class: How to declare global variables in Android?

*Sends a broadcast that (possibly multiple) interested Activities listen to. Activities that are not active do not receive broadcasts.

*When Activity is activated, it checks if there is new data in Application (since it did not get update broadcasts when inactive).

A: I'd rathter use BroadcastReceiver instead of custom interface. But the technique is the same:  register it in onResume(), unregister in onPause(). Service fires Intents, obviously.


text:
Q: Can we establish connection with Cognos 10.2.1 with Hive 0.11 or 0.12? I am new to Cognos and I am trying have a connection between Cognos 10.2.1 and Hive 0.11 through JDBC Connectivity. I installed Cognos 10.2.1 on Windows machine and Hadoop on Ubuntu. Can I establish connection between them, it would be helpful for me if you provide the different Jar file names that I need to copy from the Hive to Cognos server.
Thank you.

A: It is the recommendation from Hive to use higher versions of hive (higher than hive 1.0.0)  for JDBC with Hiverserver2 support.
Reference: https://cwiki.apache.org/confluence/display/Hive/HiveClient
You need following jars for JDBC connectivity
 hive-jdbc-<version no>.jar
 hive-jdbc-<version no>-standalone.jar


text:
Q: When relative Lie algebra cohomology of a parabolic subalgebra is trivial? ${\bf Question}$:
List parabolic subalgebras whose relative Lie algebra cohomology with respect to its semi-simple subalgebra are trivial.
In other words, list all pairs of a Dynkin graph $\Gamma$ and its subgraph $S$ such that the relative Lie algebga cohomology of a parabolic subalgebra $p_S$ of the Kac-Moody Lie algebra $\mathfrak{g}_{\Gamma}$ assigned with the graph $\Gamma$ relative to the Kac--Moody subalgebra assigned to a subgraph $S$ with trivial coefficients is trivial:
$H^{>0}(p_s, g_S;\mathbb{C}) = 0$ and $H^{0}( p_S, \mathfrak{g}_S;\mathbb{C})=\mathbb{C}$.
Note that by a parabolic subalgebra $p_S$ I mean the subalgebra generated by  $e_{\alpha}$ with $\alpha\in \Gamma$ and $f_{\alpha}$ with $\alpha\in S$.
Where $\langle e_{\alpha},h_{\alpha}, f_{\alpha}\rangle$ is an $sl_2$ triple assigned with a simple root $\alpha$. What means that parabolic Lie subalgebra does not contain the entire Cartan subalgebra. I.e. $h_\alpha\in p_S$ iff $\alpha\in S$.
${\bf \text{Equivalent formulation using BGG resolution:}}$
list the cases of  $\Gamma\supset S$ when
 $\forall\omega\in W_{\Gamma} / W_{S}$ (all elements of the quotient of the Weyl group of $\Gamma$ by the Weyl group of $S$) there exists $\alpha=\alpha(\omega)\in S$ such that the corresponding scalar product
 $\langle\omega(\rho)-\rho, \alpha\rangle\neq 0$ is different from zero.
In particular, there are no examples when $\Gamma=A_n$.
However, relative cohomology vanishes when $\mathfrak{g}_{\Gamma}$ is affine Lie algebra and $\mathfrak{g}_S$ is the corresponding finite-dimensional semisimple Lie algebra.
Are there any other examples?


text:
Q: Trying to create individual integer values for lists of tuples I'm trying to create a rudimentary sentiment analyzer. I have lists of words in categories, and two csv files from reddit threads which I'm taking comments from. I've managed to tag my data sets with the appropriate tags, and I now have sets of tuples in lists of lists which are separated by comments. I have a piece of code which I hoped to use to make an integer value for each comment based on the tags present, however I'm hitting a brick wall mentally.
I've tried the below code which results in a 0 at best, and a ValueError at worst. I know it's gotta be chock full of bad ideas, but I'm at a loss. At this point I just want something to FUNCTION T_T
tLOTR = [[('terrible', 'negative'),
  ('so', 'intensifier'),
  ('awesome', 'positive'),
  ('so', 'intensifier'),
  ('but', 'shifter'),
  ('agree', 'positive'),
  ('like', 'positive'),
  ('really', 'intensifier'),
  ('but', 'shifter'),
  ('but', 'shifter'),
  ('so', 'intensifier'),
  ('not', 'shifter'),
  ('like', 'positive'),
  ('really', 'intensifier'),
  ('like', 'positive'),
  ('so', 'intensifier')],
 [('not', 'shifter'),
  ('amazing', 'positive'),
  ('but', 'shifter'),
  ('bad', 'negative'),
  ('but', 'shifter'),
  ('like', 'positive'),
  ('awful', 'negative'),
  ('but', 'shifter'),
  ('like', 'positive'),
  ('but', 'shifter'),
  ('so', 'intensifier'),
  ('completely', 'intensifier'),
  ('wrong', 'negative')]]

#this is just a few of my tagged sets

def sentalize(text):
    value = 0
    for x in text:
        for (word, tag) in x:
            if tag == "positive":
                value += 1
            elif tag == "negative":
                value -= 1
            elif tag == "shifter":
                value *= -1
            elif tag == "intensifier":
                value *= 1.25
    return value

So I'm getting either 0 or ValueError when I run a single thing (tLOTR[0] for instance) - what I'd like ideally is to have a list of values for each comment (comment 1 = -0.348) or something of the sort.

A: Assuming you want sentalize() to process individual elements of tLOTR, your problem is the loop:
def sentalize(text):
    value = 0
    for word, tag in text:
        if tag == "positive":
            value += 1
        elif tag == "negative":
            value -= 1
        elif tag == "shifter":
            value *= -1
        elif tag == "intensifier":
            value *= 1.25
    return value

print(sentalize(tLOTR[0]))

Note how word, tag can be captured in one line by iterating over text, instead of first extracting a tuple x and then trying to somehow loop over the components of that tuple, like in your example.
With that change you can do: values = list(map(sentalize, tLOTR)) and get the result [-2.833251953125, 0.5625]
Some additional comments:

*

*storing each word with its type as a string (i.e. "positive", "negative", etc.) is not very efficient; instead, consider representing that with a simpler value

*since you've already parsed the comments and have apparently matched each word with the type of modifier / tag, that would possibly be the right time to update value, instead of having this tLOTR list of intermediate values.

*combining operators like -= and += with positive and negative constant values like 1 and -1 is very confusing. I'd recommend only using += and *= and using negative or positive values where appropriate.


text:
Q: "without any core banking words" What is a better way of saying this sentence?

The banker explained the working of bank in an easy way for a layman to understand without any core banking words.

The emphasis is on the highlighted part.

A: "The banker explained how a bank works in layman's terms"
and
"The banker explained in layman's terms how a bank works"
are shorter and incorporate the highlighted portion of your original sentence in the phrase in layman's terms.

A: If the emphasis is meant to be on the bolded words (that is, the avoidance of jargon is the key message to be conveyed) then you could move it to a more prominent position.

The banker needed no specialist vocabulary to explain the business in terms a layman could understand.

A: ..without any banking industry jargon
Jargon's definition from dictionary.reference.com/browse/jargon
"The language, especially the vocabulary, peculiar to a particular trade, profession, or group"


text:
Q: Node.js server changing from localhost to apache How am i supposed to run my node.js code on apache server, which is currently using localhost and port 5000 to apache server,port 8080.
This is my serverside code chatserver.js
var httpd = require('http').createServer(handler);
var io = require('socket.io').listen(httpd);
var fs = require('fs');

httpd.listen(5000);

function handler(req, res) {
  fs.readFile(__dirname + '/index.html',
    function(err, data) {
      if (err) {
       res.writeHead(500);
       return res.end('Error loading index.html');
      }

      res.writeHead(200);
      res.end(data);
    }
  );
}

io.sockets.on('connection', function (socket) {
  socket.on('clientMessage', function(content) {
    socket.emit('serverMessage', 'You said: ' + content);
    socket.broadcast.emit('serverMessage', socket.id + ' said: ' +
      content);
  });
});

This is my client side code.
index.html

    <title>Node.js WebSocket chat</title>

    Your message:
    <input type="text" id="input">

A: You will need to use a reverse proxy configured in the httpd.conf file. I use nginx to do this as it is a little faster and more capable than apache2.
This is my nginx config file:
server {
    listen 80;
    server_name personal.dev.x.onmylemon.co.uk;

    access_log  /var/log/nginx/dev.x.oml.access.log;
    error_log   /var/log/nginx/dev.x.oml.error.log;

    location / {
        # This is the url to your node app on the localhost
        proxy_pass              http://localhost:30450;

        proxy_set_header        Host $host;
        proxy_set_header        X-Real-IP $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_connect_timeout   150;
        proxy_send_timeout      100;
        proxy_read_timeout      100;

        proxy_buffers           4 32k;

        client_max_body_size    8m;
        client_body_buffer_size 128k;
    }
}

There is some documentation here for setting up a reverse proxy in apache.


text:
Q: Is there any way of forcing a set of jquery ajax calls into a queue? I have an array of data (arrData) which I loop around (10 elements), calling an ajax request on each. As it stands at the moment each ajax call is made in parallel. This means the server receives 10 calls all at once and sends back the data in whatever order it calculates each in. To relieve the server slightly I want to now queue my calls. Therefore, when one set of data is received by ajax it calls the next lookup. Is there any way method of doing this built in to jquery or should I hack my loop and add a recursive callback to each?
$.each(arrData, function(k,v) {
    $.getJSON(lookupPath,
        { key:k, val:v },
        function(data) {
            console.log(data); //loopback here?
        }
    );
});

UPDATE: I went with the following (as suggested by Scott M.) to get this done:
function doLookup() {
    if(k < arrData.length) {
        var v = arrData[k];
        $.getJSON(lookupPath,
            { key:k, val:v },
            function(data) {
                console.log(data);
                k++;
                doLookup();
            }
        );
    }
}

var k = 0;
doLookup();

A: perhaps you could refactor your server-side code so that it can accept one request and provide one response with all the data you need. This would let you process your data sequentially and within only one thread.
EDIT:
In response to the comment below:
if you absolutely need the calls to be sequential, then you will need to recursively call the getJSON() method. This will guarantee your AJAX requests are separate and in order.

A: I don't think there is any way to do this in jQuery out of the box. It looks like you're going to have to create a callback function on the Ajax call's success and run it for each element of your array.

A: ajax in jQuery has an option to enable synchronous mode or not.
$.ajax({async: false});

http://api.jquery.com/jQuery.ajax/


text:
Q: How to solve unregnised certificate from my Asha X201 I am developing a application in nokia asha but I got the http connection  error
Certificate was issued by an unrecognized entity ssl error ver 49.
I am developing app with nokia asha sdk

A: Most likely the server is using a self signed certificate, you will have to change the certificate on the serve to match one of the trusted root CA's on the device.


text:
Q: Slope of line if Δx is equal to 0 To calculate slope of line, I use $m = \frac{Δy}{Δx}$, but it doesn't work if $Δx = 0$. Is there a way to calculate slope of straight line? Is there anything I didn't notice?

A: The above formula for $m$ works for any line, except for $x=constant$. Suppose your line is described by $$y=mx+b$$
Take any two values of $x$ that are different. Then $$y_1=mx_1+b\\y_2=mx_2+b$$
You can subtract one from the other, and get $$y_1-y_2=m(x_1-x_2)$$If $x_1\ne x_2$ then $\Delta x=x_1-x_2$, $\Delta y=y_1-y_2$, and you get $$m=\frac{\Delta y}{\Delta x}$$
Note for $x=constant$, two different points will have $y_1\ne y_2$ and $x_1=x_2$. The same line can be described by $y_1>y_2$, which yields a slope of $m=\infty$, or $y_1< y_2$, which yields $m=-\infty$


text:
Q: How to Scroll a Cell to visible location automatically when i tap the cell I have the table view, that contain a customized tableview cell. The cell contain UILabel and UIView.Initially UIview is hidden.After tapping that cell only i make it visible.In order to make the auto scrolling i use ScrollRecttoVisible function. But it is not working for last few cell.Could anybody help me?
Thanks in advance

A: I personally use – scrollToRowAtIndexPath:atScrollPosition:animated: to scroll to the cell at the given position, with UITableViewScrollPositionMiddle for the atScrollPosition argument.


text:
Q: Standardize date of birth in JSON in postgres I have a mix of date of births in my database. Some are of the format yyyyy-mm-dd and some are of form mm:dd:yyyy. I am trying to calculate age and that makes it difficult for me to do date. How can i standardize the dates?
SELECT date_of_birth
  FROM ( SELECT attrs::JSON->'info'->>'date_of_birth'
           FROM users ) AS date_of_birth;

date_of_birth
--------------
 (2000-11-03)
 (2000-06-11)
 (2000-05-31)
 (2008-11-26)
 (2007-11-09)
 (2020-03-26)
 (2018-06-30)
 (02:21:2020)

 (2007-10-09)

There are only a couple of mm:dd:yyyy date of births. I tried updating the field in the JSON by
UPDATE users
   SET attrs::JSON->'info'->>'date_of_birth'='02-21-2020'
 WHERE attrs::JSON->'info'->>'date_of_birth'='02:21:2020'

but its erroring out

ERROR:  syntax error at or near "::"

A: You can convert the data type of attrs from JSON to JSONB
ALTER TABLE users ALTER COLUMN attrs
  SET DATA TYPE JSONB USING attrs::JSONB

Then, update the related data(which contains semi-colon within the date_of_birth data) by using JSONB_SET() function such as
UPDATE users
   SET attrs = JSONB_SET( attrs, '{info,date_of_birth}',
                          ('"'||TO_DATE(
                                  attrs::JSONB->'info'->>'date_of_birth', 'mm:dd:yyyy'
                                  )::TEXT||'"')::JSONB
                        )
  WHERE POSITION( ':' IN attrs::JSON->'info'->>'date_of_birth'::TEXT ) > 0

Demo


text:
Q: Computation of autocorrelation with non-constant denominator through Fourier transforms Consider a vector $\boldsymbol{X}$ of $N$ equispaced points whose autocorrelation $C(k)$ is to be estimated:
\begin{equation}
C(k)=\frac{1}{N} \sum_{t=0}^{N-k-1} X_t\cdot X_{t+k}
\end{equation}
It is well-known that this can be computed efficiently using Fourier transforms:
\begin{equation}
C(k) = \mathcal{F}^{-1}\big\{\mathcal{F}\{\boldsymbol{X}\}\cdot\overline{\mathcal{F}\{\boldsymbol{X}\}}\big\}
\end{equation}
where $\mathcal{F}\{.\}$ is the Fourier transform and $\overline{\mathcal{F}\{.\}}$ is its complex conjugate. However in the case that the denominator of $C(k)$ is not a constant $N$ but rather dependent on $k$:
\begin{equation}
 C(k)=\frac{1}{N-k} \sum_{t=0}^{N-k-1} X_t \cdot X_{t+k}
\end{equation}
Can this also be computed using Fourier transforms? If so can you provide guidance on how to do this?

A: You could use
$$\frac{N}{N-k}C(k)$$


text:
Q: Cannot remove header plus won't find my file I have this main funtion and inside I have the removeHeader one which I have defined as:
def removeHeader (file_name):
     f = open(file_name).readlines()
     firstLine = f.pop(6)
     return firstLine

main funtion:
def readTasksFile(file_name):
    """Reads a file with a list of translation tasks into a collection.
"""

    inFile = removeHeader(open(file_name, "r"))

    tasksList = []
    for line in inFile:
        taskData = line.rstrip().split(", ")
        tasksList.append(taskData)

    return tasksList

the problem is, it won't find my file plus I'm pretty sure the removeHeader one is missing something, I have looked at some questions about removing lines that have already been asked here but I don't really understand most of them because as a freshman in college right now I'm very bad at programming

A: In your removeHeader method you're trying open a file, but while calling the method removeHeader you're already passing the file handler.
Replacing inFile = removeHeader(open(file_name, "r"))  with
inFile = removeHeader(file_name) in your readTasksFile should work


text:
Q: Split multiple inconsistent columns into rows in R I have a dataset which looks like below:
P_ID    S_ID    Action    A1    A2    A4    A5    A6   A8
 101    1001         1  1015     0
 102    1002         1  1016     0  1027           0
 103    1003         1        1019     1        1030    1
 104    1004         1  1017     0  1028           0

Just attaching a snapshot if the indentation is not correct:

I want the output file to look like this:
P_ID    S_ID    Action
 101    1001         1
 101    1015         0
 102    1002         1
 102    1016         0
 102    1027         0
 103    1003         1
 103    1019         1
 103    1030         1
 104    1004         1
 104    1017         0
 104    1028         0

I am able to split the columns into rows but when there's a blank cell in between(see for P_ID=104) I am unable to get that working. Can someone suggest a way to deal with this? I checked similar questions posted earlier but couldn't find something relevant to this issue.
Here is the output of dput():
This is the updated dput output:

structure(list(P_ID = c(10264547L, 28790961L, 25389968L, 20368912L,
12335739L, 28386707L, 29613504L, 13241475L, 7641351L, 7642873L,
30836625L, 20437550L, 29363410L, 7641147L), S_ID = c(13324763L,
13083449L, 13324759L, 13393573L, 13516358L, 13083449L, 13324763L,
13324763L, 13432404L, 13432474L, 13324763L, 13324763L, 13324763L,
13433044L), Action = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 0L, 1L,
1L, 0L, 0L, 1L), A1 = c(13324759L, 13324763L, NA, 13324763L,
NA, NA, NA, NA, NA, NA, NA, NA, NA, 13324763L), A2 = c(0L, 0L,
13083466L, 0L, NA, 13432417L, 13324759L, 13432457L, NA, 13432449L,
13324759L, 13324759L, 13324759L, 0L), A4 = c(NA, 13324759L, 1L,
13324759L, NA, 1L, 1L, 1L, NA, 1L, 1L, 0L, 0L, 13324759L), A5 = c(NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA), A6 = c(NA,
0L, 13432524L, 0L, NA, 13432457L, NA, NA, NA, 13432538L, NA,
NA, NA, 0L), A8 = c(NA, NA, 1L, NA, NA, 1L, NA, NA, NA, 1L, NA,
NA, NA, 13083449L), A9 = c(NA, NA, 13324763L, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA), A10 = c(NA, NA, 0L, NA, NA, 13432449L,
NA, NA, NA, 13432530L, NA, NA, NA, 0L), A12 = c(NA, NA, NA, NA,
NA, 1L, NA, NA, NA, 1L, NA, NA, NA, NA), A13 = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, 13083449L, NA, NA, NA, NA), A14 = c(NA,
NA, NA, NA, NA, 13432538L, NA, NA, NA, 0L, NA, NA, NA, NA), A16 = c(NA,
NA, NA, NA, NA, 1L, NA, NA, NA, NA, NA, NA, NA, NA), A17 = c(NA,
NA, NA, NA, NA, 13324763L, NA, NA, NA, NA, NA, NA, NA, NA), A18 = c(NA,
NA, NA, NA, NA, 0L, NA, NA, NA, NA, NA, NA, NA, NA), A20 = c(NA,
NA, NA, NA, NA, 13324759L, NA, NA, NA, NA, NA, NA, NA, NA)), .Names = c("P_ID",
"S_ID", "Action", "A1", "A2", "A4", "A5", "A6", "A8", "A9", "A10",
"A12", "A13", "A14", "A16", "A17", "A18", "A20"), class = "data.frame", row.names = c(NA,
-14L))

A: df = read.table(text=gsub('NA','',do.call(paste,df)),fill=T)
b = na.omit(reshape(df,matrix(2:ncol(df),2),idvar = 'V1',dir='long'))
`rownames<-`(b[order(b$V1),][-2], NULL)
    V1   V2 V3
1  101 1001  1
2  101 1015  0
3  102 1002  1
4  102 1016  0
5  102 1027  0
6  103 1003  1
7  103 1019  1
8  103 1030  1
9  104 1004  1
10 104 1017  0
11 104 1028  0

A: If I understand correctly, there are two issues:

*

*There are multiple pairs of S_ID and Action values in each P_ID row but the values aren't properly aligned due to interspersed empty (NA) cells.

*The data need to be reshaped from wide to long format resulting in triplets of P_ID, S_ID, and Action.

The approach below uses melt(), dcast(), and rowid() from the data.table package:
library(data.table)
melt(setDT(df), "P_ID", na.rm = TRUE)[
  order(P_ID), variable := 1:2][
    , dcast(.SD, P_ID + rowid(P_ID, variable) ~ variable)][, P_ID_1 := NULL][]

    P_ID S_ID Action
 1:  101 1001      1
 2:  101 1015      0
 3:  102 1002      1
 4:  102 1016      0
 5:  102 1027      0
 6:  103 1003      1
 7:  103 1019      1
 8:  103 1030      1
 9:  104 1004      1
10:  104 1017      0
11:  104 1028      0


text:
Q: Lowering the speed of a plot loop to see movements in R (without clicking) I was wondering how I could lower the speed (i.e., the timing) of the for() loop below to allow plot changes to be visible and tangible by human eye in R (without having to click enter and just watching the looping run slowly)?
Here is a piece of R code:
for (i in 1:50) {

  plot(rnorm(40))
  readline(prompt="Press [enter] to continue")

}

A: pauseLength = 4   # length of pause in seconds

for (i in 1:50) {
    plot(rnorm(40))
    Sys.sleep(pauseLength)
}


text:
Q: Diferencia entre InnerHTML y Nodes? Necesito ayuda ya que no se si utilizar innerhtml o nodes para cambiar, agregar o quitar elementos html, tampoco encuentro la diferencia del mismo mas allá de la syntax que requiere cada uno, ¿y si son los mismo debería usar el más "fácil" en cuanto a syntax?

A: element.innerHTML
La propiedad Element.innerHTML cambia o devuelve la sintaxis HTML describiendo los descendientes del elemento.
Sintaxis
const content = element.innerHTML;

Después de la llamada, content contiene el código HTML serializado describiendo todos los descendientes de element.
element.innerHTML = content;

Elimina todos los descendientes de element, analiza la cadena content y asigna los nodos resultantes como descendientes de element.
Ejemplo:
html

primer parrafo hijo de div id="txt"

segundo parrafo hijo de id="txt" txt

js
 txt = document.getElementById("txt");
 console.log(txt.innerHTML);
 /*
 La siguiente cadena (string) se muestra en la ventana de la consola:

primer parrafo hijo de div id="txt"

segundo parrafo hijo de id="txt" txt

  */

Ejemplo funcional

txt = document.getElementById("txt");
console.log(txt.innerHTML);

primer parrafo hijo de div id="txt"

segundo parrafo hijo de id="txt" txt

Nodo
A Node es una interfaz de la que heredan varios tipos de DOM, y permite que estos diversos tipos sean tratados (o probados) de manera similar.
Las siguientes interfaces todos heredan de Nodesus métodos y propiedades: Document, Element, CharacterData(que Text, Commenty CDATASectionhereda), ProcessingInstruction, DocumentFragment, DocumentType, Notation, Entity,EntityReference
Estas interfaces pueden devolver nulo en casos particulares donde los métodos y propiedades no son relevantes. Pueden arrojar una excepción, por ejemplo, al agregar niños a un tipo de nodo para el que no pueden existir niños.
Propiedades
Hereda propiedades de sus padresEventTarget
Node.baseURI Solo lectura

Devuelve a que DOMStringrepresenta la URL base. El concepto de URL base cambia de un idioma a otro; en HTML, corresponde al protocolo, el nombre de dominio y la estructura del directorio, eso es todo hasta el último '/'.

Node.baseURIObject Esta api no ha sido estandarizada

(No disponible para contenido web.) El nsIURI objeto de solo lectura que representa el URI base para el elemento.

Node.childNodes Solo lectura

Devuelve un vivo que NodeList contiene todos los hijos de este nodo. NodeList estar vivo significa que si los hijos del Node cambio, el NodeList objeto se actualiza automáticamente.

Node.firstChild Solo lectura

Devuelve a que Node representa el primer nodo hijo directo del nodo, o null si el nodo no tiene hijo.

Node.lastChild Solo lectura
Devuelve a que Node representa el último nodo hijo directo del nodo, o null si el nodo no tiene hijo.
Node.nextSibling Solo lectura

Devuelve a que Node representa el siguiente nodo en el árbol, o null si no hay tal nodo.

Node.nodeName Solo lectura
Devuelve un que DOMString contiene el nombre de Node. La estructura del nombre diferirá con el tipo de nombre. Por ejemplo, An HTMLElement contendrá el nombre de la etiqueta correspondiente, al igual que 'audio'para an HTMLAudioElement, un Text nodo tendrá la '#text'cadena o un Document nodo tendrá la '#document'cadena.
Documentacion completa
Enlaces:

*

*MDN element.innerHTML

*MDN Node


text:
Q: There is an item that is stuck in my inventory on a Minecraft server and if I destroy it, it just comes back! I am on the beanblockz server in crea build, and there are a bunch of enchanted boots stuck in my inventory. I can pick them up if I double click, and I can put them in destroy item, but then i put another item in the slot that they where in and it just changes back to the boots and that item is gone. And I can't contact the server because there is no 'help' option on the beanblockz website. I'm really annoyed. Can anyone help?

A: We can't really help with how server admins run their servers, so if they are forcing an item into your inventory, then you would have to talk to a server admin about it.


text:
Q: mounting a pseudo-tty in a docker container My docker container has a script that opens a serial connection to a real TTY device in the production environment, something like an Arduino.  For local testing without real connected devices, I would like to create an emulated TTY and then run the same docker container pointed at this pseudo-tty.  When I create the pseudo-tty and run docker run --device=/dev/pts/2 test I get the error:
docker: Error response from daemon: oci runtime error: container_linux.go:247: starting container process caused "process_linux.go:359: container init caused \"rootfs_linux.go:65: creating device nodes caused \\\"open /var/lib/docker/aufs/mnt/242a13eadb75e802b2eab8dc01c701c4ad671195b93f7b956000f32ac0911e24/dev/pts/2: permission denied\\\"\"".

If I run with --privileged and connect into the running container, the path is not present in /dev/pts.  My host is a Debian jessie instance.
Is there a way to connect to this pseudo-tty from inside the container?  Or is there a better way to do this testing that comes to mind?


text:
Q: Swift 3 - NSString.draw(in: rect, withAttributes:) -- Text not being drawn at expected point Teeing off of this Stackoverflow post, which was very helpful, I've been able to successfully draw text onto a full-screen image (I'm tagging the image with pre-canned, short strings, e.g., "Trash").  However, the text isn't appearing where I want, which is centered at the exact point the user has tapped. Here's my code, based on some code from the above post but updated for Swift3 --
    func addTextToImage(text: NSString, inImage: UIImage, atPoint:CGPoint)     -> UIImage{

    // Setup the font specific variables
    let textColor: UIColor = UIColor.red
    let textFont: UIFont = UIFont(name: "Helvetica Bold", size: 80)!

    //Setups up the font attributes that will be later used to dictate how the text should be drawn
    let textFontAttributes = [
        NSFontAttributeName: textFont,
        NSForegroundColorAttributeName: textColor,
        ]

    // Create bitmap based graphics context
    UIGraphicsBeginImageContextWithOptions(inImage.size, false, 0.0)

    //Put the image into a rectangle as large as the original image.
    inImage.draw(in: CGRect(x:0, y:0, width:inImage.size.width, height: inImage.size.height))

    // Create the rectangle where the text will be written
    let rect: CGRect = CGRect(x:atPoint.x, y:atPoint.y, width:inImage.size.width, height: inImage.size.height)

    // Draft the text in the rectangle
    text.draw(in: rect, withAttributes: textFontAttributes)

    // Get the image from the graphics context
    let newImag = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImag!
}

In the above, atPoint is the location of the user's tap.  This is where I want the text to be drawn.  However, the text is always written toward the upper left corner of the image.  For example, in the attached image, I have tapped half way down the waterfall as that is where I want the text string "Trash" to be written.  But instead, you can see that it is written way up in the left-hand corner.  I've tried a bunch of stuff but can't get a solution.  I appreciate any help.
enter image description here
TrashShouldBeInMiddleOfWaterfallButIsNot

A: How are you setting atPoint? If you are using the same coordinate space as the screen, that won't work... which is what I suspect is happening.
Suppose your image is 1000 x 2000, and you are showing it in a UIImageView that is 100 x 200. If you tap at x: 50 y: 100 in the view (at the center), and then send that point to your function, it will draw the text at x: 50 y: 100 of the image -- which will be in the upper-left corner, instead of in the center.
So, you need to convert your point from the Image View size to the actual image size.. either before you call your function, or by modifying your function to handle it.
An example (not necessarily the best way to do it):
    // assume:
    //    View Size is 100 x 200
    //    Image Size is 1000 x 2000
    //    tapPoint is CGPoint(x: 50, y: 100)

    let xFactor = image.size.width / imageView.frame.size.width
    // xFactor now equals 10

    let yFactor = image.size.height / imageView.frame.size.height
    // yFactor now equals 10

    let convertedPoint = CGPoint(x: tapPoint.x * xFactor, y: tapPoint.y * yFactor)

convertedPoint now equals CGPoint(x: 500, y: 1000), and you can send that as the atPoint value in your call to addTextToImage.


text:
Q: How to obfuscate an Android library (.jar file) using Proguard in Eclipse I have seen many posts about how to obfuscate an Android application (.apk file) using ProGuard in Eclipse.  Also see http://developer.android.com/guide/developing/tools/proguard.html:
"When you build your application in release mode, either by running ant release or by using the Export Wizard in Eclipse, the build system automatically checks to see if the proguard.config property is set. If it is, ProGuard automatically processes the application's bytecode before packaging everything into an .apk file."
But in case of exporting an Android project in a .jar file using Eclipse Export Wizard, following the described steps (of creating a file proguard.cfg, configuring proguard.config property to proguard.cfg in the file default.properties, using Export Wizard etc.) does not seem to work - I see no obfuscation of class names, etc. in the resulting jar file.  I also have the following settings in my proguard.cfg file, but I don't see any output files in my project directory or in the proguard directory (that directory is not even created).
-dump class_files.txt
-printseeds seeds.txt
-printusage unused.txt
-printmapping mapping.txt

I have even created a file project.properties in my project directory with the following line but that did not seem to entice ProGuard into action:
proguard.config=proguard.cfg

There are no activities defined in this project.  I am using Android 2.3.1 and Eclipse Galileo 3.5.2 on Windows.  Same results with Android 3.0.  Seems like the obfuscation step has to be somehow interjected explicitly in the Eclipse Export Wizard. I will appreciate any help or insight.  Thanks.

A: java -jar proguard.jar @yourconfig.pro

yourconfig.pro (extended  from http://proguard.sourceforge.net/index.html#manual/examples.html):
-injars yourjar.jar
-outjars yourjar_out.jar

-libraryjars 'C:\android\sdk\platforms\android-10\android.jar'

-printmapping mapping.txt
-verbose
-dontoptimize
-dontpreverify
-dontshrink
-dontskipnonpubliclibraryclassmembers
-dontusemixedcaseclassnames
-keepparameternames
-renamesourcefileattribute SourceFile
-keepattributes Exceptions,InnerClasses,Signature,Deprecated,
                SourceFile,LineNumberTable,*Annotation*,EnclosingMethod

-keep public class * {
    public protected *;
}

-keepclassmembernames class * {
    java.lang.Class class$(java.lang.String);
    java.lang.Class class$(java.lang.String, boolean);
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keepclassmembers class * implements java.io.Serializable {
    static final long serialVersionUID;
    private static final java.io.ObjectStreamField[] serialPersistentFields;
    private void writeObject(java.io.ObjectOutputStream);
    private void readObject(java.io.ObjectInputStream);
    java.lang.Object writeReplace();
    java.lang.Object readResolve();
}

Result can be verified with jd-gui

A: The way to invoke ProGuard is fairly straightforward:

*

*Add the line proguard.config=proguard.cfg to project.properties

*Export the application package

A default proguard.cfg file should have been automatically created by the new project wizard.

A: Do not obfuscated your pure Java Jar. Skip that phase completely while producing the Jar (whether manually in Eclipse or via Ant build from command line).
Instead, setup and perform proper obfuscation in the client project, the one using the Jar, where you add the library as external Jar. Proguard will be able to obfuscate code within the Jar too.
I stumbled upon this issue, and ended up successfully as I described here.

A: as suggested in the comments to one of the answers above (but which i didn't notice at first because it was buried amongst one of the "additional comments") …
we simply run progruard on the command line (see the first block below) on the library outside of eclipse with the parameters in the second block below in our our proguard.cfg file (and definitely do not use -dontpreverify, or projects that use your project as an android library won't be able to properly be obfuscated due to StackMapTable problems from your project.jar).
command line:
$ java -jar $ANDROID_SDK/tools/proguard/lib/proguard.jar \
  -libraryjars $ANDROID_SDK/platforms/android-18/android.jar @proguard.cfg
  -outjars /tmp/project.jar -verbose

proguard.cfg:
-optimizationpasses 5
-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontwarn our.company.project.R*
-injars bin/project.jar
-verbose
-optimizations !code/simplification/arithmetic,!field/*,!class/merging/*

-keep class org.apache.3rdparty.stuff.**
-keep public class our.company.project.ProjectAPI
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference

-keepclassmembers public class our.company.project.ProjectAPI {
    public static <fields>;
}

-keepclasseswithmembernames class * {
    native <methods>;
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet);
}

-keepclasseswithmembers class * {
    public <init>(android.content.Context, android.util.AttributeSet, int);
}

-keepclassmembers class * extends android.app.Activity {
    public void *(android.view.View);
}

-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
    public static final android.os.Parcelable$Creator *;
}

it's possible not all of the parameters and -keep items are strictly necessary (other than not using -dontpreverify as previously mentioned), but most of these make sense to me as items that need to be there if you have an Activity class extension in the library you are exporting.

A: I use an indirect way to generate a exported android obfuscate jar, my way is:

*

*export a signed apk use eclipse

*unzip the apk, find the classes.dex

*use dex2jar.bat ,change the classes.dex to a jar

*unzip the jar and delete the class you do not need,then zip it and
change the file name to XXX.jar

*Then you use this jar in other project,or give it to customer, it
is  obfuscate!
I am sure this will help you! Enjoy it!


text:
Q: Tried factory resetting my Macbook Air but won't erase disk I tried factory resetting my Macbook Air following a guide on Macworld, and the first thing I did I went to Disk Utility (in Recovery Mode) and erased Macintosh HD - Data, but now it won't let me erase Macintosh HD. It says that it couldn't be unmounted because it is in use by process 712 (kextcache). Tried unmounting and it won't let me either. What should I do? Right now i can't even book an appointment at the Genius Bar because of Covid.

A: Try erasing the entire drive, not just the volumes.
In Disk Utility, Hit  Cmd ⌘   2   (or see the View menu) to show Devices instead of just Volumes.  Select the overall drive you will now see over the volumes (now in a disclosure triangle instead of separate) and Erase that, GUID/APFS.
If you aren't following an internet recovery factory erase, here is the best one:

*

*https://support.apple.com/en-us/HT204904
Click through to the erase portion.
Selecting the correct item in Disk Utility almost always gets an erase completed without reverting to the terminal app and command-line tools.  Also, Apple Support is now delivered almost entirely without Genius Bar visits.