text:
Q: Phonegap Android configurations failed:could not build android template project of phonegap I created a project of phonegap and complied for ios, it worked well. But for Android,when I used "cordova platform add android"or "cordova -d platform add android" commands, I got this error: "The command android failed. Make sure you have the latest Android SDK installed, and the android command (inside the tools/ folder) added to your path."
When I used "phonegap build android" to built project it prompted for username and password of github.com or build.phonegap.com. I made accounts of both. But when I entered username and password,it said its invalid. How should I build phonegap android app ?

A: You just need to install the Latest version of Android i.e 4.3
Go to SDK Manager and install the latest SDK Platform.
And try run the command again.
cordova platform add android

Hope this will help you.


text:
Q: Split array basing on chunk weight I have an array with 2 <= n <= 100 doubles:
A = [a1, a2, ... , an], ai > 0

and an integer 2 <= k <= min(n, 20). I need to split A into k  subarrays:
B1 = [a1,     a2, ... , ap]
B2 = [ap+1, ap+2, ... , aq]

             ...

Bk = [aw+1, aw+2, ... , an]

such that the sum in each B is almost equal (it's hard to give a strict definition what this means - I'm interested in an approximate solution).
Example:
Input: A = [1, 2, 1, 2, 1], k=2
Output: [[1, 2, 1], [2, 1]] or [[1, 2], [1, 2, 1]]

I tried a probabilistic approach:

*

*sample from [1, 2, .., n] using A as probability weights

*cut the sample into quantiles to find a good partition,
but this was not stable enough for production.
tl;dr This question asks about 2-chunk divisions. I need k-chunk division.

A: Calculate overall sum of array S. Every chunk sum should be near S / K.
Then walk through array, calculating running sum R. When R+A[i+1] - S/K becomes larger than S/K - R, close current chunk and make R=0. Continue with the next chunk.
You also can compensate accumulating error (if it occurs), comparing overall sum of M chunks with M * S / K
Quick-made code for the last approach (not thoroughly checked)
def chunks(lst, k):
    s = sum(lst)
    sk = s / k
    #sk = max(s / k, max(lst))
    #variant from user2052436 in comments
    idx = 0
    chunkstart = 0
    r = 0
    res = []
    for m in range(1, k):
        for idx in range(chunkstart, len(lst)):
            km = k -m
            irest = len(lst)-idx
            if((km>=irest) or (2*r+lst[idx]>2*m*sk)) and (idx>chunkstart):
                res.append(lst[chunkstart:idx])
                chunkstart = idx
                break
            r += lst[idx]
    res.append(lst[idx:len(lst)])
    return res

print(chunks([3,1,5,2,8,3,2], 3))
print(chunks([1,1,1,100], 3))

>>>[[3, 1, 5], [2, 8], [3, 2]]
   [[1, 1], [1], [100]]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase cloud functions on an offline device I use Firebase Cloud Functions in a Flutter app. How does cloud functions behave when a device is offline in these cases? Is there any situation I can't reliably use cloud functions when the device is offline?

*

*Trigger functions (onUpdate(), onDelete() etc)

*Function invocations using function name

A: If an app is offline, there is nothing it can do to trigger any function.  Without network connectivity, the app has no ability to invoke a function directly, no make any changes to a cloud-hosted product that would fire a trigger on the backend.


text:
Q: Why isn't a qualified static final variable allowed in a static initialization block? Case 1
class Program {
    static final int var;

    static {
        Program.var = 8;  // Compilation error
    }

    public static void main(String[] args) {
        int i;
        i = Program.var;
        System.out.println(Program.var);
    }
}

Case 2
class Program {
    static final int var;

    static {
        var = 8;  //OK
    }

    public static void main(String[] args) {
        System.out.println(Program.var);
    }
}

Why does Case 1 cause a compilation error?

A: Apparently this is a cheap syntactic trick to limit definite (un)assignment analysis within the class itself.
If the field is syntactically qualified with a class name, the code is usually in another class, where the analysis cannot reach.
This trick fails in your example. Other examples of oddity:
static class A
{
    static final int a;
    static
    {
        // System.out.println(a); // illegal
        System.out.println(A.a);  // compiles!
        a = 1;
    }
}

If they had more resources, they probably would've made a finer rule. But we can't change spec now.

A: The JLS holds the answer (note the bold statement):

Similarly, every blank final variable must be assigned at most once; it must be definitely unassigned when an assignment to it occurs. Such an assignment is defined to occur if and only if either the simple name of the variable (or, for a field, its simple name qualified by this) occurs on the left hand side of an assignment operator. [§16]

This means that the 'simple name' must be used when assigning static final variables - i.e. the var name without any qualifiers.


text:
Q: Range Slider - JavaScript not running - Error I created this range slider inside of CodePen My Code. I wanted to save the code in Atom for later use locally, but anytime i try to run the program i get a console error saying "Uncaught ReferenceError: $ is not defined".
I'm new to JS/Jquery. Could someone take a look at my code and let me know why it would run in codepen, but not locally from my computer?
https://codepen.io/stinkytofu3311/pen/GmKxoW

var sizeRange = ["11x17 - Starting Price - $19.99", // Store string inside of an Array

       "24x36 - Starting Price - $29.99",

       "70x90 - Starting Price - $39.99",

       "120x50 - Starting Price - $49.99",

       "67x18 - Starting Price - $59.99",

       "19x30 - Starting Price - $69.99"]

var imageUrl = new Array(); // Store images inside of an Array

       imageUrl[0] = 'http://svgshare.com/i/1Ak.svg';

       imageUrl[1] = 'http://svgshare.com/i/1AQ.svg';

       imageUrl[2] = 'http://svgshare.com/i/1Bb.svg';

       imageUrl[3] = 'http://svgshare.com/i/1Am.svg';

       imageUrl[4] = 'http://svgshare.com/i/1CG.svg';

       imageUrl[5] = 'http://svgshare.com/i/1By.svg';

$('#sliderPrice').html( sizeRange[0] );

$(document).on('input change', '#range-slider', function() { //Listen to slider changes (input changes)
   var v=$(this).val(); //Create a Variable (v), and store the value of the input change (Ex. Image 2 [imageURL])

  $('#sliderStatus').html( $(this).val() );
  $('#sliderPrice').html( sizeRange[v] );

 $("#img").prop("src", imageUrl[v]); // Modify the Images attribute src based on the sliders value, and input the value inside the imageURL[v] to display image
});

// ::::: Range Slider Thumb ::::: //

$("#range-slider").on("mousedown", function() { //1. When user clicks their mouse down on the Range-Slider
   $(this).removeClass().addClass("thumb-down");//1.1 Remove default class from CSS, and add the class .thumb-down (changes background color)
   $(this).addClass("hover-ring");//1.2 Remove default class from CSS, and add the class .hover-ring (changes box-shadow to a green color)
});

$("#range-slider").on("mouseup", function() { //2. When user mouse-up on Range-Slider

   $(this).addClass("thumb-up"); //2.1 Changes thumb color back to light green

   $(this).addClass("hover-ring-out"); //2.2 Removes Box-Shadow
});

alert("Range Slider Script is loading");
@import url('https://fonts.googleapis.com/css?family=Roboto');

.product-range-wrapper {
  displat: -webkit-flex;
  displat:flex;
  -webkit-flex-direction: column;
  flex-direction:column;
  max-width:600px;
  margin:0px auto;
  /*outline: 1px solid purple;*/
 }
.product-range-block {
  display: -webkit-flex;
  display:flex;
  -webkit-flex-direction: row;
  flex-direction: row;
  width:100%;
  height:100%;
  /*outline: 1px solid red;*/
}
.ref-height-block {
  flex-grow:3;
  /*background-color:red;*/
}
.size-chart-block {
  flex-grow:9;
  /*background-color:green;*/
}
.product-range-block img {
  width:90%;
  /*outline: 1px solid blue;*/
}
#img {
  width: 100% !important;
}

/* ::::::::::::::::::::Range Slider Styles::::::::::::::::::::::::: */
.range-slider-block {
  margin:0px auto;
  width:90%;
  }
#range-slider {
  padding:40px 0px;
  width:100%;
  /*outline: 1px solid green;*/
}
/* Remove Range Sliders Default Styles*/
input[type=range]{
    -webkit-appearance: none;
}
/* Track */
input[type=range]::-webkit-slider-runnable-track {
    height: 10px;
    background: #d7d7d7;
    border: none;
    border-radius: 6px;
}
input[type=range]:focus {
    outline: none;
}
/* Thumb */
input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    border: none;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    background: #46947F;
    margin-top: -9px;
    transition: box-shadow 0.5s;
}
input[type=range]:hover::-webkit-slider-thumb {
    box-shadow: 0 0 0 10pt rgba(190,190,190,0.4);
    cursor:pointer;
}

/* JS Styles */
/* Changes Thumb color to darker green when mousedownn */
input[type=range].thumb-down::-webkit-slider-thumb {
  background:#316557;
}
/* Changes Thumb color back to light green when mouseup */
input[type=range].thumb-up::-webkit-slider-thumb {
  background:#46947F;
}
/* Changes Ring color Green */
input[type=range].hover-ring::-webkit-slider-thumb {
    box-shadow: 0 0 0 6pt rgba(70,148,127,0.46);
    cursor:pointer;
}
input[type=range].hover-ring-out::-webkit-slider-thumb {
    box-shadow: 0 0 0 0pt rgba(0,0,0,0);
    cursor:pointer;
}

/* Input Value Styles */
#slider_count {
  margin:0px auto;
  width:100%;
  padding:0px 20px;
  text-align:center;
}
#sliderPrice {
  font-family: 'Roboto', sans-serif;
  font-size:22px;
  font-weight:600;
}
#sliderPrice span {
  font-weight:600;
  color:red;
}

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
 <title>Banner Range Slider</title>

  <link href="style.css" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

0

    <input type="range" id="range-slider" value="0.0" min="0" max="5" step="1" />

Slider Value = 0


text:
Q: Virtual filesytem over multiples files is it possible to create and mount a virtual filesystem what is made over normal files and not over disk/partition?
Firstly I though in LVM, and instead of use disks or partitions, use files. But it isn't possible, or I don't know how to dot it.
I'm think in something like use Truecrypt over Dropbox with a large Truecrypt container (1Gb for example).
Because synchronize 1Gb in Dropbox is very slow, I thint that if the virtual filesystem is made over small files (with size of 100Kb for example), it would be equivalent as blocks (with size of 100Kb) of a conventional filesystem. All modifications in the virtual filesystem will correspond to some physical files which will be synchronized over Dropbox.
This synchronization is light compared to the size of the virtual filesystem, and would enable the Truecryp container.
I would be it possible to Linux operating system, but it would be good idea to be possible to Windows/Mac/etc OS.
What do you think about it?
Any other alternative?

A: Not sure what exactly you want but I think "synchronize securely an encrypted containter" is ok?
I suggest you to synchronize securely the content of your containter becouse to sync all the containter will take always too much time.
To do that you can sync the containter while you are working in the files that is unencrypted(truecrypt).
Take a look at http://sparkleshare.org/
It syncronize your files through ssh that is a secure connection and you can store remotely in an encrypted manner.
Hope it helps, regards.

A: I've discovered one solution, perhaps it isn't the best. It is based on lvm on files.
Example of creation:
# dd if=/dev/zero of=test00.lvm count=10k bs=1024
# dd if=/dev/zero of=test01.lvm count=10k bs=1024
# losetup /dev/loop0 test00.lvm
# losetup /dev/loop1 test01.lvm
# pvcreate /dev/loop0
# pvcreate /dev/loop1
# vgcreate testvg /dev/loop0
# vgextend testvg /dev/loop1
# lvcreate -l 100%FREE -n testlv testvg
# mkfs.ext3 /dev/mapper/testvg-testlv
# mount /dev/mapper/testvg-testlv /mnt

Example of use (after dismount):
# losetup /dev/loop0 test00.lvm
# losetup /dev/loop1 test01.lvm
# pvscan; vgscan; lvscan
# mount /dev/mapper/testvg-testlv /mnt

A: This is my best solution.
What I wanted was to dispose of a encrypted container efficient and compatible with some File Hosting services like Dropbox, Barracuda Copy, etc.
The problem of using TrueCrypt is that the container is fixed and when it is synchronized over internet it is not efficient (when it is big).
My solution is use EncFS. It is ported to Linux, Windows, OSX, Android and iOS. I've been making test in Linux and Windows using Barracuda Copy and it runs very well, because it run encrypting file per file and syncing each one.
Another solution is ECryptfs but I prefer EncFS because is easier to use and is ported to more platform.


text:
Q: usage of terms "as well as " and "as well" Can anyone describe the usage of the terms "as well as" and "as well" in sentences? Are they interchangeable?

A:
1) 'John is coming as well as Henry'.
2) 'John is coming, and Henry as well'

Does that help?


text:
Q: GD blurry images Opencart I have this problem with GD image processing in Opencart that creates real bad blurry images after resize. Nothing I have tried so far has helped.
Below is the code for the image.php
<?php
class Image {
    private $file;
    private $image;
    private $info;

    public function __construct($file) {
        if (file_exists($file)) {
            $this->file = $file;

            $info = getimagesize($file);

            $this->info = array(
                'width'  => $info[0],
                'height' => $info[1],
                'bits'   => $info['bits'],
                'mime'   => $info['mime']
            );

            $this->image = $this->create($file);
        } else {
            exit('Error: Could not load image ' . $file . '!');
        }
    }

    private function create($image) {
        $mime = $this->info['mime'];

        if ($mime == 'image/gif') {
            return imagecreatefromgif($image);
        } elseif ($mime == 'image/png') {
            return imagecreatefrompng($image);
        } elseif ($mime == 'image/jpeg') {
            return imagecreatefromjpeg($image);
        }
    }

    public function save($file, $quality = 100) {
        $info = pathinfo($file);

        $extension = strtolower($info['extension']);

        if (is_resource($this->image)) {
            if ($extension == 'jpeg' || $extension == 'jpg') {
                imagejpeg($this->image, $file, $quality);
            } elseif($extension == 'png') {
                imagepng($this->image, $file);
            } elseif($extension == 'gif') {
                imagegif($this->image, $file);
            }

            imagedestroy($this->image);
        }
    }

/**
*
*   @param width
*   @param height
*   @param default char [default, w, h]
*                  default = scale with white space,
*                  w = fill according to width,
*                  h = fill according to height
    *
    */
    public function resize($width = 0, $height = 0, $default = '') {
        if (!$this->info['width'] || !$this->info['height']) {
            return;
        }

        $xpos = 0;
        $ypos = 0;
        $scale = 1;

        $scale_w = $width / $this->info['width'];
        $scale_h = $height / $this->info['height'];

        if ($default == 'w') {
            $scale = $scale_w;
        } elseif ($default == 'h'){
            $scale = $scale_h;
        } else {
            $scale = min($scale_w, $scale_h);
        }

        if ($scale == 1 && $scale_h == $scale_w && $this->info['mime'] != 'image/png')
 {
            return;
        }

        $new_width = (int)($this->info['width'] * $scale);
        $new_height = (int)($this->info['height'] * $scale);
        $xpos = (int)(($width - $new_width) / 2);
        $ypos = (int)(($height - $new_height) / 2);

        $image_old = $this->image;
        $this->image = imagecreatetruecolor($width, $height);

        if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
            imagealphablending($this->image, false);
            imagesavealpha($this->image, true);
            $background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
            imagecolortransparent($this->image, $background);
        } else {
            $background = imagecolorallocate($this->image, 255, 255, 255);
        }

        imagefilledrectangle($this->image, 0, 0, $width, $height, $background);

        imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width,
 $new_height, $this->info['width'], $this->info['height']);
        imagedestroy($image_old);

        $this->info['width']  = $width;
        $this->info['height'] = $height;
    }

    public function watermark($file, $position = 'bottomright') {
        $watermark = $this->create($file);

        $watermark_width = imagesx($watermark);
        $watermark_height = imagesy($watermark);

        switch($position) {
            case 'topleft':
                $watermark_pos_x = 0;
                $watermark_pos_y = 0;
                break;
            case 'topright':
                $watermark_pos_x = $this->info['width'] - $watermark_width;
                $watermark_pos_y = 0;
                break;
            case 'bottomleft':
                $watermark_pos_x = 0;
                $watermark_pos_y = $this->info['height'] - $watermark_height;
                break;
            case 'bottomright':
                $watermark_pos_x = $this->info['width'] - $watermark_width;
                $watermark_pos_y = $this->info['height'] - $watermark_height;
                break;
        }

        imagecopy($this->image, $watermark,
$watermark_pos_x, $watermark_pos_y, 0, 0, 120, 40);

        imagedestroy($watermark);
    }

    public function crop($top_x, $top_y, $bottom_x, $bottom_y) {
        $image_old = $this->image;
        $this->image = imagecreatetruecolor($bottom_x - $top_x, $bottom_y - $top_y);

        imagecopy($this->image, $image_old, 0, 0, $top_x, $top_y,
$this->info['width'], $this->info['height']);
        imagedestroy($image_old);

        $this->info['width'] = $bottom_x - $top_x;
        $this->info['height'] = $bottom_y - $top_y;
    }

    public function rotate($degree, $color = 'FFFFFF') {
        $rgb = $this->html2rgb($color);

        $this->image = imagerotate($this->image, $degree,
 imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));

        $this->info['width'] = imagesx($this->image);
        $this->info['height'] = imagesy($this->image);
    }

    private function filter($filter) {
        imagefilter($this->image, $filter);
    }

    private function text($text, $x = 0, $y = 0, $size = 5, $color = '000000') {
        $rgb = $this->html2rgb($color);

        imagestring($this->image, $size, $x, $y, $text,
imagecolorallocate($this->image, $rgb[0], $rgb[1], $rgb[2]));
    }

    private function merge($file, $x = 0, $y = 0, $opacity = 100) {
        $merge = $this->create($file);

        $merge_width = imagesx($image);
        $merge_height = imagesy($image);

        imagecopymerge($this->image, $merge, $x, $y, 0, 0, $merge_width,
$merge_height, $opacity);
    }

    private function html2rgb($color) {
        if ($color[0] == '#') {
            $color = substr($color, 1);
        }

        if (strlen($color) == 6) {
            list($r, $g, $b) = array($color[0] . $color[1], $color[2] . $color[3],
 $color[4] . $color[5]);
        } elseif (strlen($color) == 3) {
            list($r, $g, $b) = array($color[0] . $color[0], $color[1] . $color[1],
 $color[2] . $color[2]);
        } else {
            return false;
        }

        $r = hexdec($r);
        $g = hexdec($g);
        $b = hexdec($b);

        return array($r, $g, $b);
    }
}
?>

As you can see the quality is already set to 100 , so that doesn't help.
I have tried replacing resize with resample - but that produced no visible result.
However I have found this suggestion (code below) to sharpen images, unfortunately I am not sure how and where to use it. Especially since original code processed multiple image types. Please help to put this in the right place.
 {
$matrix = array(
  array(-1, -1, -1),
  array(-1, 16, -1),
  array(-1, -1, -1),
);

$divisor = array_sum(array_map('array_sum', $matrix));
$offset = 0;
imageconvolution($image, $matrix, $divisor, $offset);

return $image;
}

Also, if you have other suggestions to improve this code, help is greatly appreciated! I think that goes for the whole Opencart community, as this has been discussed many time but no working solution posted as of yet.

A: The quality parameter will only be applicable to .jpeg images.
To sharpen the images you could apply the imageconvolution() code within the resize() function.
public function resize($width = 0, $height = 0, $default = '') {
    if (!$this->info['width'] || !$this->info['height']) {
        return;
    }

    $xpos = 0;
    $ypos = 0;
    $scale = 1;

    $scale_w = $width / $this->info['width'];
    $scale_h = $height / $this->info['height'];

    if ($default == 'w') {
        $scale = $scale_w;
    } elseif ($default == 'h') {
        $scale = $scale_h;
    } else {
        $scale = min($scale_w, $scale_h);
    }

    if ($scale == 1 && $scale_h == $scale_w && $this->info['mime'] != 'image/png') {
        return;
    }

    $new_width = (int)($this->info['width'] * $scale);
    $new_height = (int)($this->info['height'] * $scale);
    $xpos = (int)(($width - $new_width) / 2);
    $ypos = (int)(($height - $new_height) / 2);

    $image_old = $this->image;
    $this->image = imagecreatetruecolor($width, $height);

    if (isset($this->info['mime']) && $this->info['mime'] == 'image/png') {
        imagealphablending($this->image, false);
        imagesavealpha($this->image, true);
        $background = imagecolorallocatealpha($this->image, 255, 255, 255, 127);
        imagecolortransparent($this->image, $background);
    } else {
        $background = imagecolorallocate($this->image, 255, 255, 255);
    }

    imagefilledrectangle($this->image, 0, 0, $width, $height, $background);

    imagecopyresampled($this->image, $image_old, $xpos, $ypos, 0, 0, $new_width, $new_height, $this->info['width'], $this->info['height']);

    //Image Sharpening Code

     $matrix = array(
        array(0.0, -1.0, 0.0),
        array(-1.0, 5.0, -1.0),
        array(0.0, -1.0, 0.0)
     );

     $divisor = array_sum(array_map('array_sum', $matrix));
     $offset = 0;
     imageconvolution($this->image, $matrix, $divisor, $offset);

    // End Image Sharpening Code

    imagedestroy($image_old);

    $this->info['width']  = $width;
    $this->info['height'] = $height;
}

References:

*

*sharpen image quality with PHP gd library

*http://adamhopkinson.co.uk/blog/2010/08/26/sharpen-an-image-using-php-and-gd/


text:
Q: How do I convert a string array to a LPCWSTR in .NET to pass to a Win32 API function? I have a piece of C# code that needs to convert a string array to a LPCWSTR to pass to a Win32 API function. I can't find nothing in the Marshal class that makes it straightforward. Does anybody knows how to do that?

A: You should declare the API function as taking a string array.  Since it's declared as constant, you should add an In attribute so that it's not marshalled back after the call.  If the function truly only has a unicode version as you've specified (i.e., it takes LPCWSTR and not LPCTSTR), then you should declare it with CharSet=Unicode.  Similar to:
[DllImport("kernel32.dll", CharSet=Unicode)]
static extern bool Foo([In] string[] stuff);

What API function are you trying to call?  If you post it, I can give you a good P/Invoke signature for it.  Or you can check pinvoke.net, which has a pretty good pre-compiled list (community-generated) of P/Invoke signatures.


text:
Q: Not able to see actual uploaded file(.pdf format) format on database and postman? i am trying to do create a user entity along with  a data/file  (pdf format).Uploaded and save to database  is fine but when i get the user into postman try to send get request method then in the data field show some terrible data and also i can not see my pdf file into my database.
pom.xml
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

Model Class
@Entity(name = "employee")

public class Employee {
@Id
@GeneratedValue
private Integer id;

@Column(nullable = false, length = 30)
private String name;

@Column(nullable = false, length = 30)
private String university;

@Column(nullable = false, length = 30)
private String department;

@Column(nullable = false, length = 2)
private Integer year_of_experience;

@Lob
private byte[] data;

2.  Contoller Class
@GetMapping
public List<Employee> getAllEmployee(){
    return employeeService.getAllEmployee();
}

@GetMapping("{id}")
public Employee getEmployeeById(@PathVariable Integer id){
    return employeeService.getEmployeeById(id);
}

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
             produces = MediaType.APPLICATION_JSON_VALUE)
public void addEmployee(@RequestParam("file") MultipartFile file, @RequestParam("emp") String emp ) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    Employee employee = objectMapper.readValue(emp,Employee.class);
    employeeService.addEmployee(employee,file);
}

ServiceImplemention Class
  @Override
public void addEmployee(Employee employee, MultipartFile file) throws IOException {

    for (int i = 0; i < employee.getExperienceList().size(); i++) {
        Experience experience = employee.getExperienceList().get(i);
        experienceService.addExperience(experience);
    }
  byte[]  temp = file.getBytes();
    InputStream inputStream = new ByteArrayInputStream(temp);
    employee.setData(temp);

    employeeRepostitory.save(employee);
}

Postman view to get employee.
post method set with "form-data" in header and select key as a file and next key is my user entiy key as a  text.i also try with content type (applicaiton/json) but not working.How can i convert to this unexpected data to a pdf file or  something stranded format to see.
"id": 62,
    "name": "raj",
    "university": "ewu",
    "department": "bba",
    "year_of_experience": 3,
    "data": "JVBERi0xLjcNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhlbi1VUykgL1N0cnVjdFRyZWVSb290IDkgMCBSL01hcmtJbmZvPDwvTWFya2VkIHRydWU+Pi9NZXRhZGF0YSAyNSAwIFIvVmlld2VyUHJlZmVyZW5jZXMgMjYgMCBSPj4NCmVuZG9iag0KMiAwIG9iag0KPDwvVHlwZS9QYWdlcy9Db3VudCAxL0tpZHNbIDMgMCBSXSA+Pg0KZW5kb2JqDQozIDAgb2JqDQo8PC9UeXBlL1BhZ2UvUGFyZW50IDIgMCBSL1Jlc291cmNlczw8L0ZvbnQ8PC9GMSA1IDAgUj4+L0V4dEdTdGF0ZTw8L0dTNyA3IDAgUi9HUzggOCAwIFI+Pi9Qcm9jU2V0Wy9QREYvVGV4dC9JbWFnZUIvSW1hZ2VDL0ltYWdlSV0gPj4vTWVkaWFCb3hbIDAgMCA2MTIgNzkyXSAvQ29udGVudHMgNCAwIFIvR3JvdXA8PC9UeXBlL0dyb3VwL1MvVHJhbnNwYXJlbmN5L0NTL0RldmljZVJHQj4+L1RhYnMvUy9TdHJ1Y3RQYXJlbnRzI

A: You should take a look at the community project Spring Content.  This project gives you a Spring Data-like approach to content.  It is for unstructured data (documents, images, videos, etc), what Spring Data is for structured data.
You could add it to your project with something like this:-

pom.xml

   <!-- Java API -->
   <dependency>
      <groupId>com.github.paulcwarren</groupId>
      <artifactId>spring-content-jpa-boot-starter</artifactId>
      <version>1.0.0.M9</version>
   </dependency>
   <!-- REST API -->
   <dependency>
      <groupId>com.github.paulcwarren</groupId>
      <artifactId>spring-content-rest-boot-starter</artifactId>
      <version>1.0.0.M9</version>
   </dependency>

Configuration

@Configuration
@EnableJpaStores
// enable REST API
@Import("org.springframework.content.rest.config.RestConfiguration.class")
public class ContentConfig {
}

NB: technically this configuration is not needed when using the Spring Boot starters, but included for clarity

To associate content, add Spring Content annotations to your account entity.

Enployee.java

@Entity
public class Employee {

   // replace @Lob field with:

   @ContentId
   private String contentId;

   @ContentLength
   private long contentLength = 0L;

   @MimeType
   private String mimeType = "application/pdf";

Create a "store":

EmployeeContentStore.java

@StoreRestResource
public interface EmployeeContentStore extends ContentStore<Employee, String> {
}

This is all you need to create REST endpoints for handling your employee's content under the URI /employees.  When your application starts, Spring Content will look at your dependencies (seeing Spring Content JPA and REST), look at your UserContentStore interface and inject an implementation of that interface for JPA.  It will also inject an @Controller that forwards http requests to that implementation.  This saves you having to implement any of this yourself.  So, very similar in programming model and operation to Spring Data.
Then...
curl -X POST /employees/{employeeId} -H "Content-Type: application/pdf" -F "file=@/path/to/local/file.pdf"
will store the content of /path/to/local/file.pdf in the database and associate it with the employee entity whose id is employeeId.
curl /employees/{employeeId} -H "Accept: application/pdf"
will fetch it again and so on...supports full CRUD.
Since you are associating the content with your employee entity, when you get your json responses back from the Spring Data endpoints, they will provide the content-related metadata, but NOT the "terrible data" that you are seeing with your current approach.
There are a couple of getting started guides and videos here.  The  reference guide is here.
HTH


text:
Q: How to call a function in another python file in my wsgi file? I am using mod_wsgi with pyramid and have different wsgi files per environment/server like the pyramid-test.wsgi and pyramid-prod.wsgi
These files contains code to set environment variables that are different per environment. Example:

os.environ['SQLALCHEMY_URL'] = 'TODO'

I try to move this code to a file called settings.py that will be called in the .wsgi file. These settings files will be hold next to the .wsgi file or preferable in a secure sub dir, such that others can't read the settings (like db password), but can however deploy a new version and overwrite the .wsgi file such that the app is automatically reloaded by Apache.
How can I call the python code in the settings.py file from the .wsgi file?
When I try to do that, it can't find it, as it's not part of the app module.

A: Presuming you are using recommended separate mod_wsgi daemon process group for each application instance, set the python-path option of the WSGIDaemonProcess directive for each to include the directory where your instance specific settings module is. A normal import should then work.


text:
Q: load bigquery JSON data dump into R tibble I have downloaded a JSON extract from Big Query which has nested and repeated fields (similar to the package bigrquery) and am attempting to further manipulate the resulting tibble.
I have the following code to load from JSON and convert to a tibble
library(tidyverse)
ga.list <- lapply(readLines("temp.json"), jsonlite::fromJSON, flatten = TRUE)
ga.df <- tibble(dat = ga.list) %>%
    unnest_wider(dat) %>%
    mutate(id = row_number()) %>%
         unnest_wider(b_nested) %>%
         unnest_wider(b3) %>%
         unnest_wider(b33)

So there were two list columns:

*

*b_nested, this column is a nested list (which I unnested recursively .. maybe there is a more automated way, if so, please advise!)

*rr1 and rr2, these columns will always have the same number of elements. So elements 1 of rr1 and rr2 should be read together.

I am still working out how to  extract id, rr1 and rr2 and make into a long table with repeated rows for each id row.
Note: this question has been edited a few times as I progress further along .. originally I had got stuck getting it from JSON to a tibble until I found unnest_wider()
temp.json:

{"a":"4000","b_nested":{"b1":"(not set)","b2":"some -
  text","b3":{"b31":"1591558980","b32":"60259425255","b33":{"b3311":"133997175"},"b4":false},"b5":true},"rr1":[],"rr2":[]}
  {"a":"4000","b_nested":{"b1":"asdfasdfa","b2":"some - text
  more","b3":{"b31":"11111","b32":"2222","b33":{"b3311":"3333333"},"b4":true},"b5":true},
  "rr1":["v1","v2","v3"],"rr2":["x1","x2","x3"]}
  {"a":"6000","b_nested":{"b1":"asdfasdfa","b2":"some - text
  more","b3":{"b31":"11111","b32":"2222","b33":{"b3311":"3333333"},"b4":true},"b5":true},"rr1":["v1","v2","v3","v4","v5"],"rr2":["aja1","aja2","aja3","aja14","aja5"]}

A: The final piece of the puzzle; in order to get the repeating rows for repeating record
  ga.df %>% select(id, rr1, rr2)  %>%
  unnest(cols = c(rr1, rr2))

FYI: Link to Big Query Specifying nested and repeated columns
Another solution (my preference) would be to create a tibble from rr1 and rr1 and keep as a column in ga.df so that purrr functions can be used
    ga.df %>%
  mutate(rr = map2(rr1, rr2, function(x,y) {
    tibble(rr1 = x, rr2 = y)
  })) %>%
  select(-rr1, -rr2) %>%
  mutate(rr_length = map_int(rr, ~nrow(.x)))


text:
Q: How can i filter my json data by the numbers selected in my select tags Let's say that i have this json file :
[
  {
    "restaurantName":"name1",
    "address":"restaurant1 address",
    "lat":lat1,
    "long":long1,
    "ratings":[
       {
          "stars":4,
          "comment":"good"
       },
       {
          "stars":5,
          "comment":"excellent"
       }
     ]
  },
  {
    "restaurantName":"name2",
    "address":"restaurant2 address",
    "lat":lat2,
    "long":long2,
    "ratings":[
       {
          "stars":4,
          "comment":"good"
       },
       {
          "stars":3,
          "comment":"ok"
       }
     ]
  }
]

And this html code:
<select id="s1">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

<select id="s2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<button type="button" id="btn">filter</button>

The problem is that i can't find a way to filter this data and get the restaurants list that have a star rating between the two numbers selected in the select tags.

A: You can use the function Array.reduce to sum the stars values, the function Array.filter to check for the from-to rating interval.

let data = [  {    "restaurantName":"name1",    "address":"restaurant1 address",    "lat":1,    "long":1,    "ratings":[       {          "stars":4,          "comment":"good"       },       {          "stars":5,          "comment":"excellent"       }     ]  },  {    "restaurantName":"name2",    "address":"restaurant2 address",    "lat":1,    "long":1,    "ratings":[       {          "stars":4,          "comment":"good"       },       {          "stars":3,          "comment":"ok"       }     ]  } ],
    ratingFrom = 3, // from s1 select
    ratingTo = 4, // from s2 select
    result = data.filter(d => {
      let avg = d.ratings.reduce((a, r) => a + r.stars, 0) / d.ratings.length;
      return avg >= ratingFrom && avg <= ratingTo;
    });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: First of all, I'd suggest to check the docs on Array.filter(...) and  Array.reduce(...).
In the example below you can see a possible solution to your problem.
You can calculate the average value of your ratings by summing up the values of stars using Array.reduce(...), afterwards you can compare the calculated value with the selected values in your <select>, that's where the Array.filter(...) is coming in, in short - this function will return you a new Array containing the elements which are meeting the pre-defined condition (in our case it is avgRating >= minRating && avgRating <= maxRating;).
The shortest solution has been already provided by @Ele, my example below introduces an additional Array.map(...), which is not obligatory here. Nevertheless, in case you were questioning what it does - that additional map function will return me a new Array containing only the ratings itself, in case of restaurant1 it would be [4, 5]

const data = [{
    "restaurantName": "name1",
    "address": "restaurant1 address",
    "lat": 51.43434,
    "long": 51.43434,
    "ratings": [{
        "stars": 4,
        "comment": "good"
      },
      {
        "stars": 5,
        "comment": "excellent"
      }
    ]
  },
  {
    "restaurantName": "name2",
    "address": "restaurant2 address",
    "lat": 51.43434,
    "long": 51.43434,
    "ratings": [{
        "stars": 4,
        "comment": "good"
      },
      {
        "stars": 3,
        "comment": "ok"
      }
    ]
  }
];

document.getElementById('btn').addEventListener('click', () => {
  const filteredRestaurants = data.filter(entry => {
    const ratings = entry.ratings;
    const avgRating = ratings
      .map(rating => rating.stars)
      .reduce((prev, next) => {
        return prev + next;
      }, 0) / ratings.length;
    const minRating = document.getElementById('s1').value;
    const maxRating = document.getElementById('s2').value;

    return avgRating >= minRating && avgRating <= maxRating;
  });
  console.log(filteredRestaurants);
});
<select id="s1">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
</select>

<select id="s2">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<button type="button" id="btn">filter</button>


text:
Q: How do you update pushed route when the widget that pushed it updates? So right now I have this structure:
StreamBuilder<List> -> WidgetA -> widgetPushedByWidgetA

I push the widget like this:
() => Navigator.of(context).push(
        MaterialPageRoute<Widget>(
            builder: (_) => WidgetPushedByA(list),
        ),
      ),

The problem is that when the stream updates the list within WidgetA, the Widget pushed by A isn't updated with the new list. Is there some way to do this? This is mostly irrelavent but the stream is coming from firebase.


text:
Q: Python support sorted dictionary -- similar to C++ map? I am using Python 2.7.x. I have a dictionary (I mean {}), key is int and value is string. I want to retrieve the key which has the minimal integer value. In C++, I think we can use map, which sort keys. And in Python, not sure if anything similar we can leverage? If my understanding is correct, Python dictionary (I mean {}) is not sorted by key.
thanks in advance,
Lin

A: In Python, dictionaries are represented internally by hash tables so you cannot natively get back the keys in sorted order. You can use sorted(d.keys()) to return a list of keys in sorted order. You can also use collections.OrderedDict if you pre-sort the keys. If you do not know the order of the keys ahead of time and you need to maintain the keys in sorted order as you insert values, you could take a look at this library for the SortedDict type.

A: There are binary tree implementations in Python:
https://pypi.python.org/pypi/bintrees/2.0.2
You can also use the blist.sorteddict.
You could also use the built-in bisect module to maintain a sorted list of tuples.
If all you care about is finding the minimum and you don't actually care about maintaining a sort, you can use the built-in heapq module to maintain a min-heap data structure which gives you constant time access to the minimal element.

A: Update
The OP has expressed a need for O(1) performance when finding the minimum key in a dictionary. Try the sortedcontainers module. It offers a SortedDict class:
>>> from sortedcontainers import SortedDict
>>> d = SortedDict({100: 'a', 27: 'b', 1234: 'c'})
>>> d.keys()
SortedSet([27, 100, 1234], key=None, load=1000)
>>> d.keys()[0]
27
>>> d[d.keys()[0]]
'b'

For a Python builtin dictionary you can use min(d) to find the lowest key:
>>> d = {100: 'a', 27: 'b', 1234: 'c'}
>>> print(d)
{1234: 'c', 27: 'b', 100: 'a'}
>>> print(min(d))
27
>>> print(d[min(d)])
b

A: Building off of @mhawke 's answer, you can simply do:
d = {1 : "a", 2 : "b", 3 : "c" }
print d[min(d.keys())] # => 'a'


text:
Q: ElasticSearch illegal_argument_exception for client.bulk() Node.js I try to send data to ES and I was using POST request to send data line by line and it worked fine with small files.
When I changed to use client.bulk(), I keep getting the following error message:
"status": 400,
"error":
{
    "type": "mapper_parsing_exception",
    "reason": "failed to parse [target_status_code]",
    "caused_by": {
        "type": "illegal_argument_exception",
        "reason": "For input string: \"-\""
    }
}

I noticed that after I use bulk, the type of target_status_code field has changed from string to number and many keyord fields are gone.
I only modified the sending request function so I don't understand why it doesn't work when using bulk.


text:
Q: Add span to the first letter of post Example post

Lorem ipsum dolor sit amet

Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.

What I have done :
function first_paragraph($content){
    return preg_replace('/
]+)?>/', '
', $content, 1);
}
add_filter('the_content', 'first_paragraph');

Which will have different class for first paragraph
Now I want add L and result should be like

Lorem ipsum dolor sit amet

Morbi elementum odio vel tortor adipiscing vel tempor risus ullamcorper.

Let me know

Update:
I got it worked but not a perfect solution.
function first_paragraph($content){
    $content = substr_replace($content, '', 4, 0);
    $content = substr_replace($content, '', 3, 0);
    $content = preg_replace('/
]+)?>/', '
', $content, 1);
return $content;
}
add_filter('the_content', 'first_paragraph');

A: This drop caps plugin does what you are looking for: http://wordpress.org/extend/plugins/drop-caps/
If you're trying to do drop caps this should be enough. If you want to do more you could look into the code and see how the plugin wraps the 1st char in a span. It probably uses preg replace too.  Id look myself but I'm answering this on my phone and have no way of looking at the code.


text:
Q: Smarty: unset an array index in template I would like to do {unset($array['index'])} into a Smarty 3 template.
Is such a syntax (or similar) supported ? After Googling and doc reading I can't find something satisfying.
Maybe I should ask for a feature request to Smarty dev team ? :)
Anyway, how would you do this given the currently available template functions ?

A: I don't think there's a direct support for this in smarty.  You can always do this with smarty's {php} tag, however I would strongly discourage you from doing so.  Logic doesn't belong in a presentation-level template.

A: There is a way though :-)
{$array=$array|array_diff_key:(['index']|array_flip)}

Even though it is not a good idea to do it in templates, sometimes it might save you time.

A: try this
{$array.index = null}

A: Two steps:
{$array.index = null}
{$array = $array|array_filter}

It work in Smarty3.
Example with a dynamic index:
{foreach $array as $item}
    {if $item.foo == 'bar'}

{$item.text nofilter}

        {* unset item from array *}
        {$array[$item@key] = null}
        {$array = $array|array_filter}
        {break}
    {/if}
{/foreach}

{if $array}

    {foreach $array as $item}

{$item.text nofilter}

    {/foreach}

{/if}

A: The main idea behind a template engine is that you can do all the loading, logic, unsetting etc. before you parse the view. With that being said you shouldn't be unsetting data in your template, and I'm pretty sure they will not implement that feature request.
I also don't get it why you'd want to unset a smarty variable: just don't use it and it won't get displayed.

A: I think, that you shouldn't want this, 'cause all logic must be in code not in templates.
But you can write your own modifier http://www.smarty.net/docs/en/plugins.modifiers.tpl

A: you don't you overwrite the value?
{assign var="array" value=array()}
{$array['index']='1'}
{$array['index2']='2'}
{$array['index']=''}
{$array|print_r}

this worked for me in smarty <3, don't know if still works as they really messed up smarty.

A: {$array=$links.lists|array_diff_key:(['10']|array_flip)}
{$array|print_r}

Here 10 is an array index.

A: try

{assign var=$array.index value=null)}


text: Q: how does the http to websocket communication works in wso2 esb how does the HTTP to web socket communication works in wso2 ESB. Is that a fire and forgot model or once it'll connect to backend(socket server) and it will keep receiving the data.


text:
Q: How to create Synchronized Data extension in Marketing cloud? I want to create a Synchronized Data extension of Lead Object of SalesForce, basically.

A: Synchronized Data extension Automatically creating once you sync the salesforce data in datasource marketing cloud


text:
Q: Is Adamantium common? In issue 5 of the recent Incredible Hulk ongoing (vol. 3), it is revealed that

 Dr. Doom

separated the Incredible Hulk and Bruce Banner. He does this using an adamantium chainsaw.

Image blurred to protect the innocent spoiler.
I was under the impression that adamantium was pretty much impossible to find and use outside of Ultron and the Weapon Blah program. Is it common enough that it's no big deal for the blurry fellow above to have gotten an adamantium chainsaw?

A: According to the Marvel wiki:

Extraordinarily expensive to produce, Adamantium is created through the mixing of certain chemical resins whose exact composition is a closely guarded government secret. For eight minutes after the resins are mixed, Adamantium can be molded if kept at a temperature of 1,500 degrees Fahrenheit. Its extremely stable molecular structure prevents it from being molded further, even if the temperature remains high enough to keep it in liquefied form. Hardened Adamantium can only be altered by rearrangement of its molecular structure. Given sufficient mass, Adamantium could survive a direct hit from a nuclear weapon or a blow from the most powerful superhuman. The only known substance able to pierce Adamantium is the compound known as Antarctic Vibranium, also called "anti-metal".
The U.S. government has shared the secret of Adamantium's composition with certain allies, through the information has fallen into unauthorized hands. Attempts by the former Solviet Union to reproduce the metal resulted in the creation of Carbonadium, a weaker yet far more malleable form that was used to create retractable coils wielded by the Russian super-soldier Omega Red. Due to the prohibitive cost of Adamantium's creation, many parties have resorted to the use of a somewhat weaker compound named Secondary Adamantium, which was once used to coat the sentient computer named F.A.U.S.T..

Given who the individual wielding the adamantium chainsaw is and his scientific ability and wealth he could have either stolen it, actually bought it, or stolen the formula for it.


text:
Q: Метод страно себя ведет если создавать его в другом класе и cделать cсылку на него В первом случае метод работает правильно, курсор после открытия формы перемещается на старт.
В этом коде изменяется только метод Start_Game()
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class LevelOneLevelOne : Form
    {
        public LevelOneLevelOne()
        {
            InitializeComponent();
        }
//Изменил только вот этот метод
        private void Start_Game()
        {
            Point point;
            point = Start111.Location;
            point.Offset(Start111.Width / 2, Start111.Height / 2);
            Cursor.Position = PointToScreen (point);
        }
        private void Finish_Game()
        {
            DialogResult DialogResult = MessageBox.Show("Котенок умер, восскресить его?", "Сообщение", MessageBoxButtons.YesNo);
            if (DialogResult == System.Windows.Forms.DialogResult.Yes)
            {
                Start_Game();
            }
            else if (DialogResult == System.Windows.Forms.DialogResult.No)
            {
                this.Close();
            }

        }
        private void LevelOneLevelOne_Shown(object sender, EventArgs e)
        {
            Start_Game();
        }

        private void finish_MouseEnter(object sender, EventArgs e)
        {

            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
        private void Wall3_MouseEnter(object sender, EventArgs e)
        {
            Finish_Game();
        }
    }
}

Курсор благополучно оказался на старте

А во втором случает когда я делаю ссылку на класс, он работает странно, я всего лишь этот метод написал в другом классе, что бы удобно было использовать.
Курсор после инициализации формы запускает метод, который перемещает курсор на старт, но он появляется не на старте, а где-то в левом верхнем углу, и после каждого вызова метода он чуть чуть съезжает по диагонале в правый нижний угол, а при десятом вызове метода он снова возвращается в левый верхний угол на исходное положение и все по кругу.
Код переместил в класс, а тут сделал ссылку на класс и вызвал метод
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    public partial class LevelOneLevelOne : Form
    {
        public LevelOneLevelOne()
        {
            InitializeComponent();
        }
//изменил только вот этот метод
        private void Start_Game()
        {

            StartClass SC = new StartClass();
            SC.StartM();
        }
        private void Finish_Game()
        {
            DialogResult DialogResult = MessageBox.Show("Котенок умер, восскресить его?", "Сообщение", MessageBoxButtons.YesNo);
            if (DialogResult == System.Windows.Forms.DialogResult.Yes)
            {
                Start_Game();
            }
            else if (DialogResult == System.Windows.Forms.DialogResult.No)
            {
                this.Close();
            }
        }
        private void LevelOneLevelOne_Shown(object sender, EventArgs e)
        {
            Start_Game();
        }

        private void finish_MouseEnter(object sender, EventArgs e)
        {

            DialogResult = System.Windows.Forms.DialogResult.OK;
        }
        private void Wall3_MouseEnter(object sender, EventArgs e)
        {
            Finish_Game();
        }

    }
}

В этом коде написан класс для перемещение курсора на старт
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApp3
{
    class StartClass : LevelOneLevelOne
    {
        public void StartM()
        {
            Point point;
            point = Start111.Location;
            point.Offset(Start111.Width / 2, Start111.Height / 2);
            Cursor.Position = PointToScreen(point);
        }
    }
}

Положение курсора при первом и 10 и 20 и т.д. вызове метода

Положение курсора при втором и 11 и 21 и т.д. вызове метода

Положение курсора при третьем и 12 и 22 и т.д. вызове метода

Объясните мне пожалуйста почему так происходит.


text:
Q: Does Another Universe Where Time Runs Backwards Revive the Idea of a Cyclical Universe? https://www.pbs.org/wgbh/nova/article/big-bang-may-created-mirror-universe-time-runs-backwards/
This article talks about a new theory where the big bang happened in one direction for us and the other direction where time is going backwards (mathematically). Would that revive the idea of a cyclical universe again?  I had this little vision in my head when I read this.  A universe chain with a big bang on essentially on either side of the start/end of time and in the next big bang our universe is the one going backward in time and the new one is going forward.

A: Not necessarily.
What I believe they are getting at is a theory that, before the Big Bang, there was a universe that was eternally contracting, and then it collapsed into a singularity and then exploded again to form our universe which now will be eternally expanding.
Hence, the "mirror" universe lies, not in some "parallel dimension" to use a kind of mathematically awkward pop-cult term, but in our past, so if you wanted to "go there", you'd have to go back in time. You'd need a time machine to get into it, since it's more than 13.8 billion years (437 Ps) ago. Unless and until someone invents a flux capacitor and gives it 1.21 jiggawatts (JW) [not to be confused with gigawatts (GW), by the way], or perhaps more even, given this is so far back, that ain't happening :)
Now, what was it like in this "mirror" universe? Well, it would likely have been just like ours but, if you view "ours" and its time as proceeding the same space-time axis, what you would see there would be that everything was running backwards: entropy would be ever-decreasing, not increasing. People would walk backwards, stars would be sucking up light, black holes would expand into stars (meaning they would actually be white holes, formed by collapsing Hawking radiation tuned with impeccable rightness to form a white hole for real and not just in sci-fi), rot gas would turn into corpses and dead people would come back to life and so forth as it all winds back to the Gnab Gib which then becomes the Big Bang - but likely not the same people, aliens and other such things as in our Universe and, for them, they would interpret this as a Big Bang and time going normally because their entropy arrow, which determines the direction of their conscious peception, goes the other way and so to them, "we" "already happened" and "our" Big Bang was their Gnab Gib, and someone there is talking goofily about some version of sroticapac xulf whose purpose is to go, from our perspective, forward in (our sense of, backwards in theirs) time to our world, etc. Two universes "joined at the hip", so to speak.
Or to imagine it more simply: Take a movie - any movie. Take a second movie. Reverse it so it plays backwards. Concatenate the first movie to the end of the reversed version of the second movie. Play this pair of movies connected together which will be joined at their beginnings as one single movie. That is what this is like, only on a universe-wide scale.

A: Perhaps it does. But I would also stipulate that the two-sided inversion is also overlaid, meaning that we cannot disconnect from the other side, meaning that we need a mirror side of reality to make sense of existence, and meaning that there are likely lesser mirrors (e.g., an actual mirror, the condition called situs inversus, or CP symmetry that appears disconnected from CPT symmetry that is more fundamental)that are somewhat removed from the must fundamental mirror.

A: The OP's link refers, first, to a paper by Carroll & Chen, whose complete version can be seen at https://arxiv.org/abs/hep-th/0410270 .   Vilenkin criticized it in a paper at  https://arxiv.org/abs/1305.3836, providing reasons ("under very mild assumptions", which he details) to explain why the (local) universe it attempted to describe would be literally "surrounded by singularities", which would prevent it from sharing its Big Bang / Big Crunch with another universe.
The link did not address these difficulties, but, instead, provided another (completely different) possibility based upon an extremely local experiment by Barbour, which, as stated, relied upon Newtonian gravity.  Newtonian gravity is entirely adequate for plotting orbits within the solar system, but the fact that it has never sufficed to explain the precession of Mercury's orbit (which is a very slow rotation of the orbit's axis around a point very far outside our system) shows that it will not suffice for any complete cosmology:  Actually, as described by Guth with simple algebra on p.296-297 in the 1997 edition of his book titled "The Inflationary Universe", "an infinite distribution of matter under the influence of Newtonian gravity would unquestionably collapse", and, in fact, would collapse as soon as its expansion might've otherwise begun.  I imagine Barbour (primarily a mathematician) may have accepted Newtonian gravity for the experiment only because of the current uncertainty about the interaction between gravity and subatomic particles.
It IS possible to hypothesize local universes that do not contain any matter at all, and it is possible that such universes comprise most of reality, but the illustration provided by the link showed the usual assortment of stars within the ones it was hypothesizing.
Concerning cosmologies describing local universes, containing matter during some part of an existence that might either continue indefinitely or recur more-or-less periodically, I've analyzed two (one of them similar to the Carroll & Chen model discussed in the OP's link, but a little older and simpler) at Is the Universe Past-Eternal? .

A: An interesting idea is that at the Big Bang positive matter went forwards, and negative matter went backwards, but time is circular, so we'll meet again.
Since most of space is pretty empty, a collision between the two universes would not wipe everything out instantly.  Galaxies would, for the most part, collide with nothing much.  But bits of our universe would go forward into their universe, and bits of their universe would go backwards into our universe.
I believe that makes the theory testable, because it should be possible to test whether bits of an antimatter universe are creeping into our universe.
There appears to be some evidence that this is happening, because recent research has shown that the universe is expanding at an increasing speed, when it should be expanding at a reducing speed, because of gravity.
That could be explained by saying that antimatter coming from the future is the fuel to provide the extra energy to keep the universe expanding faster.
That's probably not the true explanation, but it's worth investigating.

A: The problem with mirrors in this situation is the question of energy.
What one person might be doing in a situation might be the mirror image of what another is doing, but is the energy the same?  In the situation of a mirror universe colliding with our universe, in theory if you put a mirror in the middle, it should be the same on both sides, but once you cross the line, the rules of energy flows are different.  Okay, I've got a degree in philosophy, but one of my university mathematics teachers was the guy who figured out the Black Hole equations, and I remember him saying, "heat is a flow" which means it's dependent on time, so in a collision between universes following different rules of time, which way would the heat flow?
And the amount of energy resulting from a collision between just one star of positive matter and another of antimatter would be so huge that nobody really knows what would happen.
But I think it's an area that should be researched.


text:
Q: The start address cannot be crawled Getting the following on my WSS3 server. The server was renamed from GIMEL2 to GIMEL, and I ran stsadm -o renameserver. The search is running great, just want to remove this error
The start address sts3://gimel2:33055/contentdbid={f0bc201c-0341-4150-ba81-eac63b9affe4} cannot be crawled.

Context: Application 'Search index file on the search server', Catalog 'Search'
Details: The object was not found (0x80041201)

A: WSS does not have SSP or a Search Admin section which makes it really difficult to work with and troubleshoot.
I don't know how to actually change that reference, but an alias should make it work.
Open Central Admin > Operations > Alternate access mappings.
Select the appropriate "Alternate Access Mapping Collection" and click "Add Internal URLs"
Select the Default zone and enter http://gimel2
Run another index and verify that the error is gone.

A: In your SSP admin site, go to Search Administration. On the left, go to Content Sources. Change the name of any content sources including gimel2, to gimel.
Hopefully this will sort it.

A: The marked answer is valid, but not complete. There is another possiblity. This response is quoted from jktechnologies.com. The index crawl always starts at the root level site collection. If there isn't a root level site collection, the crawl will choke:

Example:
Your server name is "MYSERVER" and you have created a site http://MYSERVER:84/Sites/myportal or http://MYSERVER/Sites/myportal.
The site myportal isn't on the root. When you browse to http://myserver or http://myserver:84 you get a page cannot be displayed.
When you create a root site (Application Management / SharePoint Site Management / Create site collection) the search starts working again.
In my opinion it is a bit strange that this is needed but I am just a simple man….

This appears to have solved the problem and I am no longer experiencing the crawl problem. Seems like a ridiculous means of solving this problem, however this is using SP 2007... ugh.


text:
Q: Upgraded to 19.10 and now wireless networks aren't detected (Intel Corporation Wireless-AC 9260) Not totally sure where to look for clues to what's going on. In the GUI, it appears that the wifi is searching for a network, but nothing ever appears.
Output of lspci is
Network controller: Intel Corporation Wireless-AC 9260 (rev 29)

Last of dmesg | grep iwlwifi is
[  719.324454] iwlwifi 0000:02:00.0: Start IWL Error Log Dump:
[  719.324456] iwlwifi 0000:02:00.0: Status: 0x00000100, count: 7
[  719.324458] iwlwifi 0000:02:00.0: 0x20000034 | NMI_INTERRUPT_WDG
[  719.324460] iwlwifi 0000:02:00.0: 0x00000000 | umac branchlink1
[  719.324462] iwlwifi 0000:02:00.0: 0xC008888E | umac branchlink2
[  719.324464] iwlwifi 0000:02:00.0: 0xC0084C80 | umac interruptlink1
[  719.324466] iwlwifi 0000:02:00.0: 0xC0080708 | umac interruptlink2
[  719.324468] iwlwifi 0000:02:00.0: 0x00000400 | umac data1
[  719.324469] iwlwifi 0000:02:00.0: 0xC0080708 | umac data2
[  719.324471] iwlwifi 0000:02:00.0: 0xDEADBEEF | umac data3
[  719.324473] iwlwifi 0000:02:00.0: 0x0000002E | umac major
[  719.324475] iwlwifi 0000:02:00.0: 0x6BF1DF06 | umac minor
[  719.324477] iwlwifi 0000:02:00.0: 0x0003D177 | frame pointer
[  719.324479] iwlwifi 0000:02:00.0: 0xC0886C44 | stack pointer
[  719.324480] iwlwifi 0000:02:00.0: 0x00230405 | last host cmd
[  719.324482] iwlwifi 0000:02:00.0: 0x00004008 | isr status reg
[  719.324573] iwlwifi 0000:02:00.0: FW error in SYNC CMD GEO_TX_POWER_LIMIT
[  719.324617]  iwl_trans_pcie_send_hcmd+0x521/0x540 [iwlwifi]
[  719.324641]  iwl_trans_send_cmd+0x71/0xe0 [iwlwifi]
[  719.324678]  ? iwl_acpi_get_object+0xbc/0x130 [iwlwifi]
[  719.325072] iwlwifi 0000:02:00.0: Collecting data: trigger 2 fired.
[  719.325090] iwlwifi 0000:02:00.0: Firmware not running - cannot dump error

uname -r is 4.15.0-1059-oem
Everything was working fine before the upgrade.
Update: After restarting things have gotten worse! Now I get "No Wi-Fi Adapter Found" in the wi-fi settings and there's no output from dmesg | grep iwlwifi at all.


text:
Q: Node js, как удалить верхний уровень "пути" Например есть путь:
const examplePath = "test/realStuff/1.png";

Как удалить "test", чтобы получить:
realStuff/1.png

Вариант с replace не подходит.

A:

const examplePath = "test/realStuff/1.png";

console.log(examplePath.split`/`.slice(1).join`/`);


text:
Q: Dual of the fractional Sobolev space $W^{s,p}(\mathbb{R}^n)$ For $s\in\mathbb{R}$ and $1<p<\infty$, one can define the fractional Sobolev space $W^{s,p}(\mathbb{R}^n)$. Every element $f$ in $W^{s,p}(\mathbb{R}^d)$ is a tempered distribution such that the inverse Fourier transform of
$$\widehat{f_s}(\xi):=(1+|\xi|^2)^{\frac{s}{2}}\hat{f}(\xi)$$
is an element of $L^p(\mathbb{R}^d)$ and we define
$$\|f\|_{W^{s,p}}:=\|f_s\|_{L^p}.$$
Note that the function $(1+|\xi|^2)^{\frac{s}{2}}$ has at most polynomial order growth, thus $(1+|\xi|^2)^{\frac{s}{2}}\hat{f}(\xi)$ is in fact a well defined tempered distribution and so is its inverse Fourier transform. I'm looking for refrences which deal with the dual space of $W^{s,p}(\mathbb{R}^n)$. I have seen huge literatures on the case $p=2$, in which case the space $W^{s,2}(\mathbb{R}^n)$ is a Hilbert space with inner product
$$\langle f,g\rangle_{W^{s,2}}=\frac{1}{2\pi}\int_{\mathbb{R}^d}\hat{f}(\xi)\overline{\hat{g}(\xi)}(1+|\xi|^2)^sd\xi.$$
And the dual space of $W^{s,2}(\mathbb{R}^n)$ is precisely $W^{-s,2}(\mathbb{R}^d)$.
Unlike the case $p=2$, I didn't find any resources which discuss the duality when $p\neq 2$. I've seen some resources mentioned that the dual of $W^{s,p}(\mathbb{R}^n)$ is $W^{-s,q}(\mathbb{R}^n)$, where $\frac{1}{p}+\frac{1}{q}=1$. Intuitively this makes sense from the duality of $L^p$ spaces. But I didn't see any proof of this.
Could someone provide me some references related to this quesiton? Or maybe explain to me in details if applicable? Thanks in advance!
P.S. I saw some resources which define the Sobolev spaces of negative powers to be the dual of Soboleve spaces of positive powers, i.e., they define
$$W^{-s,q}(\mathbb{R}^n):=(W^{s,p}(\mathbb{R}^n))'$$
when $s>0$ and $\frac{1}{p}+\frac{1}{q}=1$. I would like to see whether this coincides with the definition I provided above.

A: So a good reference for that are the books Theory of function spaces I and II by H. Triebel.
In particular, the space that you define here is the space $F^s_{p,2}$ (see for example the last Theorem in section 1.5.1 in Theory of function spaces II) often denoted as $H^{s,p}$ and called the Bessel-Sobolev space which can be seen as complex interpolation of Sobolev spaces (see also Is $B^s_{p,p} = W^{s,p}$?), or also defined with a Littlewood-Paley decomposition. And you can find the fact that $(F^s_{p,q})' = F^{-s}_{p',q'}$ in Theory of function spaces II, section 2.11.2 (and it is also indicated in Theory of function spaces II, section 1.5.2)


text:
Q: How to map array in flatlist in React Native I have functionality which will return me days of the week. Then I am mapping that array into ScrollView. I am able to do this succesfully.
getting days of week functionality:
const [weekArray, changeWeekArrayState] = useState([]);
  useEffect(() => {
    var now = moment();
    let arrayDays = [];
    for (let i = 0; i < 7; i++) {
      var day = now.format('ddd');
      var date = now.format('DD/MM/YYYY');
      if (i == 0) {
        day = 'Today';
      } else if (i == 1) {
        day = 'Tommorow';
      }
      arrayDays.push({
        day: day,
        date: date,
      });
      now.add(1, 'days');
    }
    changeWeekArrayState(arrayDays);
    console.log(weekArray);
  }, []);

Below is my code:
<ScrollView
  horizontal={true}
  showsHorizontalScrollIndicator={false}>
  {weekArray.map((item, index) => (
    <TouchableOpacity
      index={index}
      onPress={() => setIndexSelect(index)}
      key={index}>
      <Text>
        {index === weekArray.length - 1 ? ` ${item.day} ` : ` ${item.day} | `}
      </Text>
    </TouchableOpacity>
  ))}
</ScrollView>;

This works, But I wanted to do this using FlatList, so tried below given code:
 <FlatList
  horizontal={true}
  contentContainerStyle={styles.horizontalView}
  data={weekArray}
  renderItem={_renderItem}
  keyExtractor={(item) => item.day}
/>;

const _renderItem = (item, index) => {
    <TouchableOpacity
      index={index}
      onPress={() => setIndexSelect(index)}
      key={index}
    >
      <Text>
        {index === weekArray.length - 1 ? ` ${item.day} ` : ` ${item.day} | `}
      </Text>
    </TouchableOpacity>
  }

I am getting just blank screen with this code.
I am very new to using FlatList , so I am not able to figure out how to do this.

A: To use Flatlist, simply you have to pass data which you want to map, and there's a renderItem prop which is used for rendering the data, there's another prop called keyExtractor which is for giving every element a unique
<Flatlist
   data={weekArray}
   renderItem={_renderItem}
   keyExtractor={(item) => item.day}
/>

const _renderItem = ({item, index}) => {
   return (
     //your jsx/code goes here
)}

for renderItem you have to add {}.

A: All you're missing is return statement in _renderItem and passing or accessing the value wrong. Use this (Just changed item to { item }). You can also use just item but you'll have to access your value as item.item.days in such case. Play around with this and you should see expected result.
<FlatList
  horizontal={true}
  contentContainerStyle={styles.horizontalView}
  data={weekArray}
  renderItem={_renderItem}
  //keyExtractor={(item) => item.day}
  keyExtractor={({ item, index }) => _renderItem(item, index)}
/>;

const _renderItem = (item, index) => {
    return (<TouchableOpacity
      index={index}
      onPress={() => setIndexSelect(index)}
      key={index}
    >
      <Text>
        {index === weekArray.length - 1 ? ` ${item.day} ` : ` ${item.day} | `}
      </Text>
    </TouchableOpacity>)
  }


text:
Q: Using PostgreSQL NOTIFY payload in QGIS I am using the NOTIFY signal of PostgreSQL intensively to update a PostGIS-layer in the map (see https://oslandia.com/en/2017/10/07/refresh-your-maps-from-postgresql/).
Additionally to the channel 'qgis', I am sending a payload with the latitude and longitude of the newly added point.
Now, additionally to the update of the layer, I would like to pan the map automatically to the location given in the payload of the NOTIFY signal.
Question:

*

*How can I reuse the NOTIFY payload of the qgis-channel of PostgreSQL in QGIS (e.g. within a Python-based layer-action).

Looking for any hints.

A: As per this PR (https://github.com/qgis/QGIS/commit/02e3916bf59a67abc81a8c90a3e246a5984f5c3), it should be simple as subscribing to notify signal at corresponding QgsDataProvider (https://qgis.org/api/classQgsDataProvider.html#abdb764c89cc99ccaa418178c26d84c32)


text:
Q: SFTP connection failed socket.timeout? I am attempting to connect to one of our SFTP servers in order to automate a report. We pull a file from this server once a week and I am not able to get this connections to work. I am not finding any useful references to the below traceback error. Anyone have an idea of what could be causing this problem?
I get a socket.timeout error after 2 or 3 seconds of executing the code.
import paramiko

cli = paramiko.SSHClient()

cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
cli.connect(hostname='AHOST', port=21, username="USER", password="PASS")

stdin_, stdout_, stderr_ = cli.exec_command("ls -l ~")
print(stdout_.readlines())

cli.close()

Traceback:
Exception: Error reading SSH protocol banner
Traceback (most recent call last):
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 2138, in _check_banner
    buf = self.packetizer.readline(timeout)
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\packet.py", line 367, in readline
    buf += self._read_timeout(timeout)
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\packet.py", line 576, in _read_timeout
    raise socket.timeout()
socket.timeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 1966, in run
    self._check_banner()
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 2143, in _check_banner
    "Error reading SSH protocol banner" + str(e)
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

Traceback (most recent call last):
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 2138, in _check_banner
    buf = self.packetizer.readline(timeout)
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\packet.py", line 367, in readline
    buf += self._read_timeout(timeout)
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\packet.py", line 576, in _read_timeout
    raise socket.timeout()
socket.timeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/user_name/PycharmProjects/PDD_Report/MAIN/MAIN.py", line 12, in <module>
    cli.connect(hostname='A40T', port=21, username="user_name", password="gate001")
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\client.py", line 397, in connect
    t.start_client(timeout=timeout)
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 587, in start_client
    raise e
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 1966, in run
    self._check_banner()
  File "C:\Users\user_name\Desktop\Python 3.6.2\lib\site-packages\paramiko\transport.py", line 2143, in _check_banner
    "Error reading SSH protocol banner" + str(e)
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

A: You are connecting to FTP port 21.
SSH/SFTP uses port 22 (what is the default value of the port parameter, which you override).

Side note 1: Your question is about SFTP. Yet, instead of using SFTPClient, you use SSHClient and execute shell commands – That has nothing to do with SFTP.

Side note 2: Do not use AutoAddPolicy like this. You
 lose security by doing so.
See Paramiko "Unknown Server".


text:
Q: Discrepancy in outputs of `size` and `objdump`? I have compiled the following C function (in sum.c) into object code:
int sum(int a, int b)
{
    return (a + b);
}

using
gcc -c sum.c

When I check the sizes of different sections using size:
size sum.o
   text    data     bss     dec     hex filename
    112       0       0     112      70 sum.o

it tells me that the text section is allocated 112 bytes. But when I disassemble it using objdump:
objdump -d sum.o

sum.o:     file format elf64-x86-64

Disassembly of section .text:

0000000000000000 <sum>:
   0:   f3 0f 1e fa             endbr64
   4:   55                      push   %rbp
   5:   48 89 e5                mov    %rsp,%rbp
   8:   89 7d fc                mov    %edi,-0x4(%rbp)
   b:   89 75 f8                mov    %esi,-0x8(%rbp)
   e:   8b 55 fc                mov    -0x4(%rbp),%edx
  11:   8b 45 f8                mov    -0x8(%rbp),%eax
  14:   01 d0                   add    %edx,%eax
  16:   5d                      pop    %rbp
  17:   c3                      retq

There are only 17 bytes worth of instructions in the .text section. Is there something that I am missing?

A: Use size -A and objdump -D to get all the information you want.
On my system size without -A adds the size of the .eh_frame section onto text (probably because it is read-only and will be loaded together with the text).


text:
Q: Обработка события клика мыши, при нажатой клавише на клавиатуре WPF Нужно обработать клик мыши с зажатой клавишей, к примеру CTRL, по элементу управления Кнопка.
Я так понимаю, обрабатываться всё же будем в обработчике клика и там проверять, нажата ли нужная клавиша на клавиатуре.
Только вот вопрос, как можно проверить, нажата ли клавиша?

A:      private void Button_Click(object sender, RoutedEventArgs e)
        {
           if(Keyboard.IsKeyDown(Key.LeftCtrl))
            {
                MessageBox.Show("function 1"); // ЛКМ при зажатой клавиши CTRL
            }
           else
            {
                MessageBox.Show("function 2"); // ЛКМ без зажатой клавиши CTRL
            }
        }


text:
Q: PHP GET - HTACCESS re-write / Reading a URL by ID? How to rewrite and get ID from a URL:
I am using a Ticket Script that gets the content from mysql database by ID. And i was wondering If we could get the ID from url by only typing the site.com/ID HERE.
Our Main URL looks like:  site.com/index.php?id=1A2VD4
But how to READ and GET the ID using URL: site.com/1A2VD4
The Htaccess I am using:

*

*RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?id=$1½
RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?id=$1
I tried a lot different GET methods and Regular Expression in my php code, but not luck at all / Centos / Apache 2.2! I will be appereciated if I could get some help!
Thanks in advance

A: You can use this code in root's .htaccess:
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\w-]+)/?$ /index.php?id=$1 [L,QSA]

Reference: Apache mod_rewrite Introduction
Inside index.php you can this id by using $_GET['id']


text:
Q: What does the .align directive do? I'm learning x86, and I'm trying to figure out what the .align directive does and how it can be useful.
The Oracle Reference Manual says:

The .align directive causes the next data generated to be aligned
  modulo integer bytes. Integer must be a positive integer expression
  and must be a power of 2. If specified, pad is an integer byte value
  used for padding. The default value of pad for the text section is
  0x90 (nop); for other sections, the default value of pad is zero (0).

But I'm not sure what it means. Would you refer to where I can read more about it or explain it briefly with an example?

A: The key to understanding what it does is to understand why it's there.
All computers have a natural boundary known as the wordsize.  This boundary is typically 4-bytes or 8-bytes.
The CPU can load and store from memory faster and without wasting cache space if 4 and 8 byte values are located on these boundaries. Some types of CPU's cannot fetch misaligned values at all.
So, there must be a mechanism in the assembler that skips to the next boundary so that a label and a storage allocation directive can begin on a more efficient address.
For instructions, odd boundaries work on most computers, but they still have performance implications and waste cache space.
   .string "ab\0"
; this next address is 3

vs
    .string "ab\0"
    .align 4 # sometimes interpreted as 2**n, so, .align 2
; this next address is 4, and would still be 4 if the string was just "a"


text:
Q: How can I concatenate the output of two commands? How can I concatenate the output of pwd and ls and add it to a file called f1? This is not working:
pwd, ls > f1

A: Use a compound command:
{ pwd; ls; } > f1

A: Saves a semi-colon and 2 spaces, costs a process vs @chepner  :-)
(pwd;ls) > f1

A: Maybe you looking for do something harder but file appending is a simple solution:
pwd >> f1
ls >> f1

If you prefer chepner's or Mark Setchell's answer, here's an explanation:

*

*You can use subshell with parenthesis:
( pwd; ls; ) > f1

*Or subcommand:
{ pwd; ls; } > f1

With subshell, parent shell won't have access to children environment. Variable aren't kept because a new orphan process is created.
And with subcommand initialized variable are kept and usable with parent.
Both have parent environment.
Reference:

*

*Advanced Bash-Scripting Guide - Subshells


text:
Q: How to parse XML in a Windows Phone 7 application Could someone tell me how to parse a XML-String that i receive from a wcf-rest service?
my webserive XML-String looks like
<WS>
    <Info>
        <Name>Beta</Name>
        <Description>Prototyps</Description>
    </Info>
    <Pages>
        <Page>
            <Name>Custom</Name>
            <Description>toDo</Description>
        </Page>
        ...many other pages...
    </Pages>
 </WS>

an my phone sourcecode:
public void DownloadCompleted(Object sender, DownloadStringCompletedEventArgs e)
{
    if (!e.Cancelled && e.Error == null)
    {
        var answer = XElement.Parse(e.Result).Descendants("WS"); // null
        ...
    }
}

if i try to parse it through XDocument.Load(e.Result) then i get the exception: File not Found.
i just want the "unique" information of the Info-Node and a list of all Page-Nodes with their values
Update
Even if i try to load the Root-Element via var item = xdoc.Root.Descendants(); item will be assigned to the whole xml-file.
Update 2 it seems the problem occurs with the namespaces in the root-element. with namespaces xdocument will parse the webservice output not correctly. if i delete the namespaces it works fine. could someone explain me this issue? and is there a handy solution for deleting all namespaces?
update 3 A Handy way for removing namespaces1

A: With really simple XML if you know the format wont change, you might be interested in using XPath:
var xdoc = XDocument.Parse(e.Result);
var name = xdoc.XPathSelectElement("/WS/Info/Name");

but for the multiple pages, maybe some linq to xml
var xdoc = XDocument.Parse(xml);
var pages = xdoc.Descendants("Pages").Single();
var PagesList = pages.Elements().Select(x => new Page((string)x.Element("Name"), (string)x.Element("Description"))).ToList();

Where Page is a simple class:
public class Page
{
    public string Name { get; set; }
    public string Descrip { get; set; }
    public Page(string name, string descrip)
    {
        Name = name;
        Descrip = descrip;
    }
}

Let me know if you need more explanation.
Also to select the Info without XPath:
var info = xdoc.Descendants("Info").Single();
var InfoName = info.Element("Name").Value;
var InfoDescrip = info.Element("Description").Value;

A: Viktor - XDocument.Load(string) attempts to load an XDocument by the supplied filename, not a string representation of an XML element.
You say var answer = XElement.Parse(e.Result).Descendants("WS"); // null, but which part is null?  The parsed XElement or the attempt to grab a descendant?  If <WS>...</WS> is your root element, would the .Descendents("WS") call return the root element?  Based on the documentation for XElement.DescendantsAndSelf(), I'm guessing not.  Have you instead tried calling:
var answer = XElement.Parse(e.Result).Descendants("Info");

A quick test on my end showed that, with WS as the root element, calling XElement.Parse(e.Result).Descendants("WS"); yielded no results, while XElement.Parse(e.Result).Descendants("Info"); yielded the <Info>...</Info> element.


text:
Q: "Update to" table values not loading during simple update query Started a new job with the most recent version of Access and can't find an answer to this -
When doing a basic Update query linking two tables I want to update a field in Table 1 to a field in Table 2 - every version I've had for the past 20 years gives you a drop down menu of the table fields available in the "Update to:" line but not this version?? I can type it out of course but I miss my drop down menu. Any ideas how to get this back?
Thanks in advance for any help.

A: In Access 2013, go to Design > Query Type in the ribbon and select Update. The grid will change to show your Update To: dropdown.


text:
Q: Transforming a string from an API call into Markdown syntax? Let's say I have a (graphQL) API call that returns the following:
node {
   "body": "* Hello\r\n\r\n_World_",
}

Which is
* Hello

_World_

in the original Markdown.
(To be more specific, I'm fetching github issues comments. I know there's an option for HTML in the github API, but I'm just curious.)
Is there any easy way to turn that back to Markdown in javascript? Without regex.


text:
Q: Get topN keywords with PySpark CountVectorizer I want to extract keywords using pyspark.ml.feature.CountVectorizer.
My input Spark dataframe looks as following:

id
text

1
sun, mars, solar system, solar system, mars, solar system, venus, solar system, mars

2
planet, moon, milky way, milky way, moon, milky way, sun, milky way, mars, star

I applied the following pipeline:
# Convert string to array
input_df = input_df.withColumn("text_array", split("text", ','))

cv_text = CountVectorizer() \
    .setInputCol("text_array") \
    .setOutputCol("cv_text")

cv_model = cv_text.fit(input_df)
cv_result = cv_model.transform(input_df)

cv_result.show()

Output:

id
text
text_array
cv_text

1
sun, mars, solar system, ..
[sun,  mars,  solar system, ..
(9,[1,2,4,7],[3.0,4.0,1.0,1.0])

2
planet, moon, milky way, ..
[planet,  moon,  milky way, ..
(9,[0,1,3,5,6,8],[4.0,1.0,2.0,1.0,1.0,1.0])

How can I now get for each id (for each row) top n keywords (top 2, for example)?
Expected output:

id
text
text_array
cv_text
keywords

1
sun, mars, solar system, ..
[sun,  mars,  solar system, ..
(9,[1,2,4,7],[3.0,4.0,1.0,1.0])
solar system, mars

2
planet, moon, milky way, ..
[planet,  moon,  milky way, ..
(9,[0,1,3,5,6,8],[4.0,1.0,2.0,1.0,1.0,1.0])
milky way, moon

I will be very grateful for any advice, docs, examples!

A: I haven't found a way to work with Sparse Vectors besides very few operations in the pyspark.ml.feature module so for something like taking the top n values I would say a UDF is the way to go.
The function below uses np.argpartition to find the top n values of vector values and return their indices which conveniently we can put in the vector indices to get the values.
import numpy as np
from pyspark.sql.functions import udf

@udf("array<integer>")
def get_top_n(v, n):
    top_n_indices = np.argpartition(v.values, -n)[-n:]
    return [int(x) for x in v.indices[top_n_indices]]

The values returned are the vocabulary index and not the actual word. If the vocabulary is not that big we can put it as an array column of its own and transform the idx to the actual word.
from pyspark.sql.functions import col, transform

voc = spark.createDataFrame([(cv_model.vocabulary,)], ["voc"])

cv_result \
.withColumn("top_2", get_top_n("cv_text", lit(2))) \
.crossJoin(voc) \
.withColumn("top_2_parsed", transform("top_2", lambda v: col("voc")[v])) \
.show()

+---+--------------------+--------------------+--------------------+------+--------------------+--------------------+
| id|                text|          text_array|             cv_text| top_2|                 voc|        top_2_parsed|
+---+--------------------+--------------------+--------------------+------+--------------------+--------------------+
|  1|sun, mars, solar ...|[sun,  mars,  sol...|(9,[1,2,4,7],[4.0...|[2, 1]|[ milky way,  sol...|[ mars,  solar sy...|
|  2|planet, moon, mil...|[planet,  moon,  ...|(9,[0,2,3,5,6,8],...|[3, 0]|[ milky way,  sol...| [ moon,  milky way]|
+---+--------------------+--------------------+--------------------+------+--------------------+--------------------+

I'm not sure I feel that good with the solution above, probably not scalable.
That being said, if you don't actually need the CountVectorizer , there is a combination of standard functions we can do on the input_df to simply get the top_n words of every sentence.
from pyspark.sql.functions import explode, row_number, desc, col
from pyspark.sql.window import Window

input_df \
.select("id", explode("text_array").alias("word")) \
.groupBy("id", "word") \
.count() \
.withColumn("rn", row_number().over(Window.partitionBy("id").orderBy(desc("count")))) \
.filter(col("rn") <= 2) \
.show()

+---+-------------+-----+---+
| id|         word|count| rn|
+---+-------------+-----+---+
|  1| solar system|    4|  1|
|  1|         mars|    3|  2|
|  2|    milky way|    4|  1|
|  2|         moon|    2|  2|
+---+-------------+-----+---+


text:
Q: How can a non-operator player run this command by clicking on a clickable tellraw text in 1.13+? My command is something simple:
/tellraw @a {"text":"Test","clickEvent":{"action":"run_command","value":"/scoreboard players add Jimmy test 1"}} The issue is that if a non-operator clicks on this text the command will not run. This question was asked for 1.12, but the /trigger command was removed, meaning those answers don't apply to the answer for this question. So, in 1.13+ Minecraft, how can I get around non-operators being unable to use the clickable text?


text:
Q: how to create a mind-map based tree-view windows based application in .NET I'm looking to create an intuitive tree-view structure (on the similar lines of a Mind-map) for my .NET Windows Application (WPF).
Something on the similar lines as this or this
I'm initially planning to develop a sample application, wherein my application just reads an underlying structured XML to create a mind-map like visualization and display it to the user. The user can select any of the displayed tree node. If the node has child nodes, it shall be displayed when the user clicks on the corresponding parent node.
To achieve this i need a heads up or help in the right direction to begin with. Any help is deeply appreciated

A: I've done a network map from scratch before in WPF but not a Mind Map.  It's not easy and would take a few pages to explain every step.  So I've given a quick startup below on how I accomplished my network map.  I don't think there would be much difference other than the layout and the visual representation of the nodes and node connectors.
The first place to start is your collection.  MSDN has a killer Directed Graph collection available here:  http://msdn.microsoft.com/en-us/library/ms379574(v=vs.80).aspx.
After your collection is established, you will need to extend the Panel class so it can perform your layout for you.  I don't know of any existing Mind Map layout panels, but here's a link to a Radial Panel layout:  http://msdn.microsoft.com/en-us/library/ms771363(v=vs.90).aspx.  It should show you the steps required to place things in a custom layout.
You will also need a way to visually represent your directed graph nodes.  The beautiful thing about WPF is you can create your own UserControls and if your panel is created to layout properly, it will perform all the layout work for your custom controls.  My network map was simply a UserControl with an ellipse as the background, thrown into a Radial Panel.
The final step is the ability to examine your graph collection and draw the connectors between connected nodes.  In my directed graph collection I added a property of type object called Tag and I stored the UserControl version of the node.  This way I know the coordinates of the connected UserControls and I can connect them with a PolyLine.  I think the difference for you is you would want your connector as Image.
That's the quick version.  I'd love to post source code here that shows more, but I wrote it for work and they would kill me.


text:
Q: asp.net cookie reading does not functioning (same page) I have a single page with a button and a textbox.
I was expecting that previous cookie should be read on page load.
just attempting read/write simple example. button should save to cookie the textbox value. and at next opening it should read it. but mycookie is always null. what is wrong with the codes ?
any clue?
(thanks)
    protected void Page_Load(object sender, EventArgs e)
    {

            HttpCookie mycookie = Request.Cookies["info"];

        if(mycookie!=null)
        TextBox1.Text=mycookie["mytext"];

    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        HttpCookie mycookie= new HttpCookie("info");
        mycookie.Expires = DateTime.Now.AddDays(3);

        mycookie["mytext"]=TextBox1.Text;

        Response.Cookies.Add(mycookie);
    }

A: You should probably use the Value property.  Try this:
    protected void Page_Load(object sender, EventArgs e)
{

        HttpCookie mycookie = Request.Cookies["info"];

    if(mycookie!=null)
    TextBox1.Text=mycookie.Value;

}

protected void LinkButton1_Click(object sender, EventArgs e)
{
    HttpCookie mycookie= new HttpCookie("info");
    mycookie.Expires = DateTime.Now.AddDays(3);

    mycookie.Value=TextBox1.Text;

    Response.Cookies.Add(mycookie);
}