text:
Q: Text not horizontally centre in nav bar / Too much space between nav bar text Here I have my website: http://gyazo.com/56e069ebf8b5bd61ee30523886180b88
There are a number of issues with the nav bar.
1.You can see that the text or nav bar is not horizontally centered, as indicated by the hover (which is equal on top and bottom)
2.There is to much space in between the text, (and this spacing is the only way I've found works without the text moving around when highlighting or hovering.
So for 1. is there a way I can make the text or the nav bar (not sure what is the cause) centre so the hover looks more equal (horizontally)
For 2. Is there a way I can close the gap between the text, while still keeping the same padding settings, and so it doesn't move the text around when I use the hover function.
I've also added a jsfiddle if that helps: http://jsfiddle.net/d1a5eshs/
HTML FOR NAV BAR

HOME

STATUS

INFO

GAMEMODES

SURVIVAL

PURE-PVP

GAMESWORLD

RULES

VOTE

CONTACT

                </ul

CSS FOR NAV BAR
/*TOP NAV BAR SECTION*/
#nav_bar {
    background-color: #a22b2f;
    padding:1px;
    box-shadow: 0px 2px
    height:45px;
    }
#nav_bar ul li {
    display: inline-block;
}
#nav_bar ul li a {
    color: white;
    text-decoration:none;
    font-weight:bold;
    font-size:15px;
    margin-left:10px;
    padding-bottom:13px;
    padding-top:17px;
    padding-left:10px;
    padding-right:10px;
    margin-bottom:30px;
}
#nav_bar ul li ul {
    display: none;
}
#nav_bar>ul>li>a:hover {
    background:#8c1b1f;
    padding-bottom:13px;
    padding-top:13px;
    padding-left:10px;
    padding-right:10px;
}
#nav_bar>ul>li>ul>li>a:hover {
    background:#c9c9c9;
    padding-bottom:5px;
    padding-top:5px;
    padding-left:5px;
    padding-right:5px;
}
#nav_bar ul li:hover ul {
    display: block;
    position: absolute;
    padding: 0px;
    background: #e2e2e2;
    padding-top:10px;
    padding-bottom:10px;
    padding-left:0px;
    padding-right:10px;
    border: 1px solid black;
    border-radius:5px;
}
#nav_bar ul li:hover ul li {
    display: block;

}
#nav_bar ul li:hover ul li a {
    color: black;
    font-size:12px;
    font-weight:bol;
    margin-left:-20px;
    padding-bottom:5px;
    padding-top:5px;
    padding-left:5px;
    padding-right:5px;
}

A: There were several spacing issues and also there were several duplicate styles and a few mistakes, but I think I fixed all your issues. http://jsfiddle.net/d1a5eshs/1/.

A: Here's my version of your navigation bar: http://jsfiddle.net/zo541am2/.  I trimmed and simplified both your HTML and CSS code.
HTML:

HOME

STATUS

INFO

GAMEMODES

SURVIVAL

PURE-PVP

GAMESWORLD

RULES

VOTE

CONTACT

CSS:
* {
    margin: 0;
    padding: 0;
}

body {
    padding: 10px;
}

nav {
    background-color: #a22b2f;
    box-shadow: 0px 2px 10px;
}

ul {
    list-style-type: none;
}

nav > ul {
    display: table;
    margin: 0 auto;
    min-width: 650px;
    text-align: center;
}

nav > ul > li {
    display: inline-block;
    position: relative;
}

nav > ul > li > a {
    display: block;
    color: #fff;
    text-decoration: none;
    font: bold 15px/3 Serif;
    padding: 0 15px;
}
nav ul ul {
    display: none;
    position: absolute;
    min-width: 100%;
    background: #e2e2e2;
    border: 1px solid gray;
    border-radius: 2px;
}

nav > ul > li:hover > a {
    background: #8c1b1f;
}

nav ul ul li a {
    display: block;
    color: black;
    font: bold 12px/3 Sans-Serif;
    text-decoration: none;
}

nav ul ul > li:hover > a {
    background: #c9c9c9;
}

nav > ul > li:hover > ul {
    display: block;
}


text:
Q: CSS animation z-index not working right on IOS I have a simple reactJS module with css animation where an envelope opens, a paper pops up, the paper goes back down, and the envelope closes.
On desktop (chrome, opera and firefox) it works great. On my Samsung (Chrome and Firefox) it works great. On iPadOS it gets wonky.
On Safari, Firefox, and Chrome, the envelope top spreads to the entire width of the screen, and to the top of the screen when it's closing and about to open. On Chrome on ipad, it also puts the envelope top in front of the 'letter' that slides up, when the letter is at the top. I have played with z-index changes, setting translateX values in the animation, and with opacity. I can't seem to figure out what is causing the problem, nor how to fix it.
I have been beating my head against the wall for this stupid little animation for 2 hours. Any ideas where I went wrong?
.js file
import React from "react";
import './EmailOpen.scss';

const contactEmail = 'email@email.com';

const EmailOpen = () => {
    return (
        <>

@

        </>
    );
}

export default EmailOpen;

.scss file

$envelopeWidth: 90px;
$envelopeHeight: calc($envelopeWidth * .6667);
$duration: 4s;
$borderRad: calc(0.0333 * $envelopeWidth);
$halfWidth: calc($envelopeWidth / 2);
$halfHeight: calc($envelopeHeight / 2);
$letterMove: calc(-0.67 * $envelopeHeight);

body {
    background-color: #000;
}

.wrapper {
    position: relative;
    top: calc(2vh);
    left: calc(50% - $halfWidth);
}

.mail {
    background: #aaa;
    position: relative;
    transform-style: preserve-3d;
    cursor: pointer;
    width: $envelopeWidth;
    height: $envelopeHeight;
    border-bottom-left-radius: $borderRad;
    border-bottom-right-radius: $borderRad;

    &:before {
        content:"";
        position: absolute;
        top: 0;
        right: 0;
        z-index: 5000;
        border-right: $halfWidth solid #fed;
        border-left: $halfWidth solid transparent;
        border-top: $halfHeight solid transparent;
        border-bottom: $halfHeight solid #fed;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }

    &:after {
        content:"";
        position: absolute;
        top: 0;
        left: 0;
        z-index: 4000;
        border-left: $halfWidth solid #cba;
        border-right: $halfWidth solid transparent;
        border-top: $halfHeight solid transparent;
        border-bottom: $halfHeight solid #cba;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }
}

.cover {
    &::before {
        content:"";
        position: absolute;
        top: 0;
        left: 0;
        z-index: 6000;
        transform-origin: top;
        transform: rotateX(0deg);
        animation: open $duration linear infinite;
        opacity: 1;
        border-left: $halfWidth solid transparent;
        border-right: $halfWidth solid transparent;
        border-bottom: $halfHeight solid transparent;
        border-top: $halfHeight solid #a98;
        border-bottom-left-radius: $borderRad;
        border-bottom-right-radius: $borderRad;
    }
}

@keyframes open {
    0%, 5% {
        transform: rotateX(0deg);
        z-index: 6000;
    }
    15%, 85% {
        transform: rotateX(180deg);
        z-index: 0;
    }
    95%, 100% {
        transform: rotateX(0deg);
        z-index: 6000;
    }
}

.letter {
    position: absolute;
    top: 0;
    background: #eee;
    left: calc($envelopeWidth * 0.05);
    width: calc($envelopeWidth * 0.9);
    height: calc($envelopeHeight * 0.95);
    border-radius: $borderRad;
    animation: letter $duration linear infinite;
    z-index: 2000;

    h1 {
        position: absolute;
        top: 10%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: green;
    }

    @keyframes letter {
        0%, 15% {
            transform: translateY(0);
        }
        25%, 75%  {
            transform: translateY($letterMove);
        }
        85%, 100% {
            transform: translateY(0);
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is this java code not opening text file? I am attempting to open a file (words.txt) and then count the number of vowels inside. Here is my code:
        Scanner input = new Scanner("words.txt");
    String fileContent = "";

    while (input.hasNext()) {

        fileContent += input.next() + " ";
    }
   input.close();

    char[] charArr = fileContent.toCharArray();
    int counter = 0;

    for(int i = 0; i < charArr.length; i++)

    {
          if(charArr[i] == 'a' || charArr[i] == 'e' || charArr[i] == 'i' || charArr[i] == 'o' || charArr[i] == 'u')

               counter++;
    }

  System.out.println(fileContent);

When I print the filecontent variable, it is telling me the string it is holding is 'words.txt'. Its not actually opening the file, just reading the name of it. Thoughts?

A: There is a Scanner constructor that takes a String, but it just reads from the String directly.

Constructs a new Scanner that produces values scanned from the specified string.

You should create a File from your filename and pass the File to another Scanner constructor that takes a File:

Constructs a new Scanner that produces values scanned from the specified file.

Scanner input = new Scanner(new File("words.txt"));

A: The Scanner class takes a string; you never give it contents of an actual file.

A: try this
File file = new File("word.txt");
then open the file in scnner

A: You might want to use regex for your pattern matching instead of your if solution:
int counter = 0;

try (final Scanner in = new Scanner(Paths.get("src/words.txt"))) {
    in.useDelimiter("[aeiouAEIOU]");

    while (in.hasNext()) {
        in.next()
        counter++;
    }
}

System.out.println("Number of vowels: " + (counter - 1));

Or for a little shorter version, use a for-loop:
...
for (counter = 0; in.hasNext(); in.next(), counter++) {
    //do additional stuff like counting for statistics eg.
}
...


text:
Q: npm install -g @angular/cli not working and hanging in windows 7 I am unable to install the angular cli from the npm and its getting stuck asking to loadAllDepsIntoIdealTree.
Steps taken:
C:\Windows\system32\node -v
v6.11.1
C:\Windows\system32\npm -v
3.10.10
C:\Windows\system32\npm install -g @angular/cli
Its gets stuck with the attached error

A: I also stucked in the same problem. Below solution works for me.
It would be better if you upgrade your node and npm versions to latest. After that please follow the below steps to install the angular/cli:
Open your command prompt with administrative privileges and uninstall angular/cli by using npm uninstall -g angular-cli command.
Remove node_modules directory and then clear the cache by using npm cache clear --force command.
Remove C:\Users\<username>\AppData\Roaming\npm\ and C:\Users\<username>\AppData\Roaming\npm-cache.
Try to install the angular/cli@latest by using npm install -g @angular/cli@latest command.
Hope the above trick resolve your issue.

A: I had the same problem for npm@5.3.0 on macOS. It was resolved by checking my package.json file with validator.
In my case the problem was the git package version notation: gulpjs/gulp.git#4.0 instead of https://github.com/gulpjs/gulp.git#4.0.
After changes I also regenerate package-lock.json.


text:
Q: Form submission will not stop for validation What I am trying to accomplish is a (very simple) email validation using jQuery, but no matter what I do, the form will just keep submitting.
<form id="rfq" name="rfq" action="rfq_form" method="post" enctype="multipart/form-data">
...
<input type="image" id="submit" name="submit" src="submit.png" border="0" />
JS email validation:
//$("#rfq").submit(function() { doesnt seem to work either

$('#submit').click(function() {
    var email = $('#email').val();
    if(email.indexOf("@") == -1){
        $("#email").addClass('invalid');
        return false; // cancel form submission if email invalid
    }
    return false; // return true if no errors once i get it working
});

A: Working Example
First, make sure all event handlers are attached once the DOM is "ready"
I'm using .submit() on the actual form.
$(document).ready(function() {
    // now that document is "ready"
    $('#formId').submit(function() {
        var email = $('#emailInput').val();
        alert(email);
        if(email.indexOf("@") == -1){
            alert("invalid!");
            return false; // cancel form submission if email invalid
        }
        alert("valid!");
        return true; // return true if no errors once i get it working
    });
});

A: Try wrapping your code in a ready block.
$(document).ready(function(){
    // your code here
});

You should also be using the submit event on the <form> element, I think.

A: This is going to work. If you don't understand why, feel free to ask :)
var validated = false;

$(document).ready(function(){
    $("#rfq").submit(function(event) {
        if (validated === true) {
            return true;
        }
        event.preventDefault(); // prevent submission
        var email = $('#email').val();
        if(email.indexOf("@") == -1){
            $("#email").addClass('invalid');
            return;
        }
        validated = true;
        return $(this).trigger('submit');
    });
});

A: You could try using this function to validate your address.
function validateEmail(elementValue){
   var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
   return emailPattern.test(elementValue);
 }

And then modify your code to submit the form.
$('#submit').click(function() {
    var email = $('#email').val();
    if(!validateEmail(email)){
        $("#email").addClass('invalid');
    }
    else {
       $("form").submit();
    }
});


text:
Q: What is the most micro-optimal and elegant "Insert in order" algorithm for IEnumerable? I am trying to create a generalized "insert in order" algorithm in C#, something that would implement the following
/// <summary>
/// Inserts a new element in its proper order into an ordered enumeration
/// </summary>
/// <typeparam name="T">The comparable type</typeparam>
/// <param name="source">The sorted enumeration</param>
/// <param name="insertion">The element to insert</param>
/// <returns>A new enumeration with <paramref name="insertion"/> in its proper order</returns>
public static IEnumerable<T> InsertInOrder<T>(this IEnumerable<T> source, T insertion) where T : IComparable<T>
{
      throw new NotImplementedException();
}

and be as optimized as possible in terms of the number of operations and the memory. The main problem I'm having is that when working with MoveNext() there's always these cases in my algorithm where I "accidentally" might have moved one too far and want to recover the previous element. That is making it hard for me to write something that is optimal and elegant.
For elegant-looking in O(n) time and not directly using the enumereator I came up with
IEnumerable<T> smallers = source.TakeWhile(x => x.CompareTo(insertion) < 0);
IEnumerable<T> greaters = source.SkipWhile(x => x.CompareTo(insertion) >= 0);

IEnumerable<T> reordered = smallers.Concat(new[] { insertion }).Concat(greaters);

foreach (T element in reordered)
{
    yield return element;
}

but this is not efficient due to multiple enumeration on source.
So I tried instead to convert to single enumeration and eventually (although it's embarrassing how long it took me) came up with
bool inserted = false;
IEnumerator<T> mover = source.GetEnumerator();
while (mover.MoveNext())
{
    if (mover.Current.CompareTo(insertion) < 0)
    {
        yield return mover.Current;
    }
    else
    {
        if (!inserted)
        {
            yield return insertion;
            inserted = true;
        }
        yield return mover.Current;
    }
}

but the problem there is that once we get to the point in the list where the insertion is less than or equal mover.Current, the if (mover.Current.CompareTo(insertion) < 0) becomes a useless check.
So, eventually I came up with
bool movedNext;
IEnumerator<T> mover = source.GetEnumerator();
while (movedNext = mover.MoveNext() && mover.Current.CompareTo(insertion) < 0)
{
    yield return mover.Current;
}
yield return insertion;
if (movedNext)
{
    do
    {
        yield return mover.Current;
    } while (mover.MoveNext());
}

but there is still the inefficiency of having an extra variable moveNext and having to keep reassigning it movedNext = mover.MoveNext() over and over.
Is it possible to write this insertion algorithm without an extra variable to deal with the "possible extra move"? :)

A: The last bit of code is about as good as it can get. Stop worrying about insignificant inefficiencies like the extra movedNext variable and the assignment inside the while loop.
Now, if your question is simple professional curiosity on if it can be avoided? Then the answer is: Yes, of course! But (there is always a but) at a cost: goto enters, readability exits:
public static IEnumerable<T> InsertInOrder<T>(
    this IEnumerable<T> source,
    T insertion) where T : IComparable<T>
{
    using (var e = source.GetEnumerator())
    {
        while (e.MoveNext())
        {
            if (e.Current.CompareTo(insertion) < 0)
            {
                yield return e.Current;
            }
            else
            {
                yield return insertion;
                yield return e.Current;
                goto continueEnumerating;
            }
        }

        yield return insertion;
        goto exit;

    continueEnumerating:
        while (e.MoveNext())
        {
            yield return e.Current;
        }

    exit:
        yield break;
    }

Methinks I'll pay the inefficiency thousandfold...


text:
Q: How to copy text to Clipboard from TextField in Android I want to copy text from TextField to Clipboard.
My TextField is named txtDetails and i have a button named btnCopyToClipBoard.I want to be able to copy the contents of my textfield to clipboard when i press the button.
Name Of InputBox Is "txtDetails"
Name Of Button Is "btnCopyToClipBoard"
String StrTemp  = txtDetails.getText();

So How We Can Set "OnClickListener" Of "btnCopyToClipBoard" To Copy Value In "StrTemp" To ClipBoard

A: Use ClipBoardManager's setText method:
String StrTemp  = txtDetails.getText();
btnCopyToClipBoard.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", StrTemp);
        clipboard.setPrimaryClip(clip);
    }
});

A: use global class extends Application for example:
public class G extends Application

And Call In manifiest
and use
public static Context               context;

// OnCreate
context = getApplicationContext();

And Then Change That Line As:
 ClipboardManager clipboard = (ClipboardManager) G.context.getSystemService(CLIPBOARD_SERVICE);

Or Use
ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);


text:
Q: How to add data frames to a list and name them from a user written function I think I can ask this question without explaining the details of why I am doing it, lets try:
I am writing a function, part of what it does is create a data frame called x. I have a list that I would like to store this data frame in called Subsets. I can get the function to place x within subsets using this code:
Subsets <- append(Subsets, list(x))#adds x to Subsets

This is great, but the purpose of having the list Subsets is to store multiple data frames (i.e., the function will be used for multiple xs, and this data frame for each x will be neatly stored in the list object Subsets). Naturally, I want to name this data frame something unique every time I use it for a different x. The naming convention I want to use can be extracted from information within the data frame x. I want to paste the values in x[1,1] and x[1,6] (which are columns that denote the unique location and id of each x) and use this to name the data frame stored within the list Subsets.
I can (externally, outside the function) give make a new data frame from x with the name I want using assign(paste0(x[1,1],x[1,6]),x)
but when I try to combine these to make that the name of the data frame within a list, I cant get it to work:
#the word in x[1,1] is NY and the word in x[1,6] is 1
#so the name of the object within the list is supposed to become NY1
Subsets <- append(Subsets, list(assign(paste0(x[1,1],x[1,6]),x),)

what am I doing wrong?

A: You need to create a list with an element named according to paste0(x[1,1],x[1,6]).  What assign does is create an object with that name.
This code should do what you want:
newlist <- list(x)
names(newlist) <- paste0(x[1,1],x[1,6])
Subsets <- c(Subsets, newlist)


text:
Q: What do the third and fourth arguments of the mat-palette function do (not the first/second) and how do I use those for my own components I know what this does:
$my-accent: mat.define-palette(mat.$pink-palette, A200);

Now the primary color will be A200.
However, what happens if there is more than two arguments?
Like such:
Example:
$my-accent: mat.define-palette(mat.$pink-palette, A200, A100, A400);

Example taken from here:
https://material.angular.io/guide/theming
What do A100 & A400 do in this case?
It would really nice to get a link to the corresponding documentation about those parameters where you drew your knowledge from.
I tried searching for docs, found nothing.
I tried playing around with it in my app, nothing changed.
EDIT:
If those are special color variations, then how do I use those in my own elements manually, e.g. color="primary-1", primary-2.
I want to apply those colors if my element is in a special state, such that it stands out from other elements which have the color primary.

A: You already have that documentation

These four hues represent, in order: the "default" hue, a "lighter" hue, a "darker" hue, and a "text" hue


text:
Q: Laravel last method Something strange is happening when I call my controller method:
public function placeOrder()
{
    $user = JWTAuth::toUser();
    if ($user->orders->isEmpty()) {
        Order::create(['user_id' => $user->id, 'status_id' => '1', 'draft' => false]);
    }
    //Order::create(['user_id' => $user->id, 'status_id' => '1', 'draft' => false]);

    $input = Input::except('token', 'condiments');
    $input['order_id'] = $user->orders->last()->id;
    return $user->orders->last();
}

So if user doesn't have an order, create it.
For the sake of the argument, my user has 5 orders, and I want to return the last one. It works, I get order no. 5 returned. However, if I uncomment the order creation line (after the if clause), it should create an order every time the method is called...which it does. However, I always get the order before last returned. So I create 6th, but get 5th back...create 35th, get 34th back?
Does anyone know why that might be?
EDIT:
If it means something...the method gets triggered from Ionic mobile app with POST method on route
EDIT2:
JWTAuth is causing the issue...when I return user as User::find(1) it gets updated accordingly

A: You must insert the data as related model (see Laravel Docs).
$order = new Order(['user_id' => $user->id, 'status_id' => '1', 'draft' => false]);

$order = $user->orders()->save($order);

Now you can return the new order with return $order;
or you will need to refresh your model $user->load('orders');


text:
Q: Extract root hive from Registry key path Is there a registry equivalent of [System.IO.path]::GetPathRoot($path)? I want to recursively delete empty parent keys after deleting a specified key or property, so I want to walk back up the tree until I reach the root hive. And I would prefer not to just continue until an exception is thrown.

A: I don't know of a specific function for this.
If you use the registry provider, you can also use the PSDrive property on the child items, which will give you information about the registry root:
(Get-Item "HKLM:\Software\Windows").PSDrive.Name

or
(Get-Item "HKLM:\Software\Windows").PSDrive.Root

Although for "regular" registry paths, it would still be as simple as
$root = $path.Split("\")[0]

As for your specific scenario, you could create a function like this:
function Remove-KeyIfEmpty {
<#
.SYNOPSIS
Removes empty registry keys and optionally empty parent keys recursively.
#>
    [CmdletBinding(SupportsShouldProcess)]
    param (
        [Parameter(
            Mandatory,
            Position = 0,
            ValueFromPipeline,
            ValueFromPipelineByPropertyName
        )]
        [Alias("PSPath")]
        [string]$Path,
        [switch]$Recurse
    )
    $key = Get-Item $Path
    if ($key.Property.Count -eq 0 -and $key.SubKeyCount -eq 0) {
        if ($PSCmdlet.ShouldProcess($key, "Remove-Item")) {
            Remove-Item $Path
            if ($Recurse -and $key.PSParentPath) {
                Remove-KeyIfEmpty $key.PSParentPath -Recurse
            }
        }
    }
}

Example:
Remove-KeyIfEmpty "HKCU:\Software\Example\SubKey" -Recurse

It even supports common parameters, like the -WhatIf, -Confirm, -Verbose and -ErrorAction switches.


text:
Q: Sending text to label printer not working at all On beginning i would like to highligth that i've tried a lot of things to make it done but without success and i am really stack and hoping i find some help here. My client has some 'sato' label printer which is placed on some ip address and on port 9100 some specific text data in predefined format has to be sent to print it. I was trying couple of diffrent code without success (below) - from what i know it should be fine. I am not getting any errors or whatever it looks like data is sending correctly but printer doesn't want to print. I check using some external tools like hyper terminal to check if at all printer working or not - it does and was able to send the file on this ip/port and printer starts to print. What could be wrong with what i am doing? Below find my diffrent code tries.
    Public Sub WriteData(ByVal data As String, ByRef IP As String)
try
        Console.WriteLine("Sending message """ & data & """ to " & IP)
        Dim client As TcpClient = New TcpClient()
        client.Connect(New IPEndPoint(IPAddress.Parse(IP), My.Settings.CommPort))
        Dim stream As NetworkStream = client.GetStream()
        Dim sendBytes As Byte() = Encoding.ASCII.GetBytes(data)
        stream.Write(sendBytes, 0, sendBytes.Length)
   Catch ex As Exception
MsgBox(ex.toString)
        End Try

    End Sub

also tried this:
     ' Printer IP Address and communication port
        Dim ipAddress As String = "192.168.1.21"
        Dim port As Integer = 9100

        ' ZPL Command(s)
        Dim ZPLString As String = ""

        Try
            ' Open connection
            Using client As New System.Net.Sockets.TcpClient()
                client.Connect(ipAddress, port)

                ' Write ZPL String to connection
                Using writer As New System.IO.StreamWriter(client.GetStream())
                    writer.Write(ZPLString)
                    writer.Flush()
                End Using
            End Using
                ' Catch Exception
        Catch ex As Exception
MsgBox(ex.toString)
        End Try

and also this:
Try
     Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        clientSocket.NoDelay = true;

        IPAddress ip = IPAddress.Parse("192.168.1.21");
        IPEndPoint ipep = new IPEndPoint(ip, 9100);
        clientSocket.Connect(ipep);

        byte[] fileBytes = File.ReadAllBytes("test.txt");

        clientSocket.Send(fileBytes);
        clientSocket.Close();
   Catch ex As Exception
MsgBox(ex.toString)
        End Try

and this:
Try
     Dim clientSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
        clientSocket.NoDelay = True

        Dim ip As IPAddress = IPAddress.Parse("192.168.1.21")
        Dim ipep As New IPEndPoint(ip, 9100)
        clientSocket.Connect(ipep)

        Dim fileBytes As Byte() = File.ReadAllBytes("test.txt")

        clientSocket.Send(fileBytes)
        clientSocket.Close()
   Catch ex As Exception
MsgBox(ex.toString)
        End Try

A: EDIT: I've included code to disconnect/close, and dispose the stream and TcpClient.
With a little modification to your initial code, this sends an entire file (which should work if that's the only thing your label printer requires):
Public Sub WriteFile(ByVal FilePath As String, ByRef IP As String)
    Try
        Console.WriteLine("Sending file """ & FilePath & """ to " & IP)
        Dim client As New TcpClient()
        client.Connect(IP, 9100)

        Dim stream As NetworkStream = client.GetStream()
        Dim sendBytes As Byte() = IO.File.ReadAllBytes(FilePath)

        stream.Write(sendBytes, 0, sendBytes.Length)

        stream.Close(5000) 'Wait 5 seconds to ensure that the data is sent.
        client.Close()
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
End Sub

Example call:
WriteFile("C:\Users\Vincent\Desktop\Print me.txt", "192.168.1.21")

A: I had a similar problem. I had to take the file info, save it as a .CLP file (my client's printer is a Zebra thermal label printer) and then my client could print the file that way.
I don't know what format a 'sato' printer uses, but if you can create your text file and save it with that extension, that could work.


text:
Q: CSS hover, transition effect in the same direction I am doing some basic CSS fill transitions on hover. I have used this codepen as an example: https://codepen.io/brandon4117/pen/ihIgE. Now on hover the background position raises to fill the div, and on hover off, the background goes back down. I wanted to know how can I modify this pen, to work such as when hover off the transition should go upwards, rather than down.
Most hover transitions: Hover on new fill top->bottom. Hover off new fill removes bottom->top. I would like to do on hover fill top->bottom, on hover off fill removes top->bottom again.
A look at the CSS being used:
div {border-style: solid;
border-color: black;
color: black;
padding: 50px;
background-size: 200% 200%;
background-image:
linear-gradient(to top, #A72424 50%, transparent 50%);
background-position:0 100%;
-webkit-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
-moz-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
-ms-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
-o-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
transition: background-position 300ms, color 300ms ease, border-color 300ms ease;

}

div:hover {color: white;
border-color: #A72424;
background-image:
linear-gradient(to top, #A72424 50%, transparent 50%);
background-position: 0 0%;
-webkit-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
-moz-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
-ms-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
-o-transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
transition: background-position 300ms, color 300ms ease, border-color 300ms ease;
}

a {color: black; text-decoration: none;
transition: all 100ms linear;
-webkit-transition: all 100ms linear;
-moz-transition: all 100ms linear;
-ms-transition: all 100ms linear;
-o-transition: all 100ms linear;}

a:hover {color: white;
transition: all 100ms linear;
-webkit-transition: all 100ms linear;
-moz-transition: all 100ms linear;
-ms-transition: all 100ms linear;
-o-transition: all 100ms linear;
}

a:active {color: white;}

Thanks

A: Ok I got the answer: For top down do this:
.divclass::after {
    position: absolute;
    transition: 0.3s;
    content: '';
    height: 0;
    top: 50%;
    right: 0;
    width: 3px;
    background: #fff;
    bottom: 0;
    top: auto;
    z-index: -1;
    width: 120%;
}

.divclass:hover::after {
    height: 100%;
    top: 0;
}

Thanks for pointing me in the direction of pseudos Frderico


text:
Q: Почему при парсинге канала на ютубе на python неправильно сохраняется html файл? Мне нужно было всего лишь кол-во подписчиков, но при парсинге, как я в дальнейшем понял сохраняется вообще не то. В дев тулс есть нормальный html, а при скачивании выходит 99% js, вобщем какая-то фигня.
Как решить проблему и почему она возникает?


text:
Q: Ruby XML Parsing I have a sample XML document like
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <SearchSecretsResponse xmlns="urn:thesecretserver.com">
      <SearchSecretsResult>
        <Errors/>
        <SecretSummaries>
          <SecretSummary>
            <SecretId>86</SecretId>
            <SecretName>hostName\root</SecretName>
            <SecretTypeName>Unix Root Account (SSH)</SecretTypeName>
          </SecretSummary>
        </SecretSummaries>
      </SearchSecretsResult>
    </SearchSecretsResponse>
  </soap:Body>
</soap:Envelope>

I am trying to parse it using Nokogiri. My code is
doc = Nokogiri::XML.parse(xml)
puts doc.xpath('//SecretSummary')

But this doesn't print anything. What am I doing wrong ?

A: You'll need to alias the namespace.
Nokogiri::XML(xml).xpath('//foo:SecretSummary', 'foo' =>  'urn:thesecretserver.com')

A: You could also remove the namespaces
doc.remove_namespaces!


text:
Q: Name of my app not showing on top of activity. Showing "com.example.(appname).(file name) When first starting a simple app, usually the title of the app is on the top of the activity. However, for me, it says com.example.inventory.MainActivity and then when I switch activities to another one, it'll say com.example.inventory.AddProduct
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.example.inventory">
  <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".ProductList"></activity>
    <activity android:name=".AddProduct" />
    <activity android:name=".MainActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>
</manifest>

I'm a beginner so sorry if I forgot to include any other important file.

A: You need to add a label for your activity like this:
   <activity android:name=".ProductList"
   android:label = "Product Screen"></activity>

Replace Product Screen with the Title of your choice.
Do the same for all the other activities in the Manifest.xml


text:
Q: Get state of toggled element I am building an application with angularui. I have a a span that contains an image that I need to toggle on and off and save the state on when user hits save. How do I get the toggle state of this element?
Here's my code:

    <form role="form" ng-submit='updateProspect()'>
        <fieldset>

        </fieldset>

        <button class="btn btn-primary btn-block">
            Save
        </button>
    </form>

Controller:
angular.module('Main', [
      'mobile-angular-ui.core.sharedState'])
    .controller('UpdateProspectCtrl', function($scope){
      // set the state here on click of the toggelable span.
      $scope.setPinned = function() {
        $scope.updateProspectPinned = !$scope.updateProspectPinned;
        console.log("setting pinned to", $scope.updateProspectPinned);
      };

      // Using the above function I am able to guage the state. However, next time when I load this page I want to set the last state. If the user had selected it, I want to show it as selected. How do I achieve this behavior?
    })

Also, even though I have given it an ng-model I am unable to access it in my controller. I can access all the remaining elements of the page except for this span and its container p tags. What could be the issue?

A: You shouldnt bind ng-model directive to anything else but inputs and textareas, it is not meant for a span, if you want to display  the model use -
 {{updateProspectPin}}
The ng-click directive should be the one responsible for toggling the value.
If you want to save the state you should open an angular service which is a singleton, and store the saved state there.
New service -
function pinnedStateService (localStorageService) {
    var service = this;

    service.pinState = { value: getPinStateFromLocalStorage()};

    service.toggleState = function () {
      service.pinState.value = !service.pinState.value;
      localStorageService.set("pinItem", this.pinState.value);// i am not sure this is the correct syntax
    }

    function getPinStateFromLocalStorage() {
        return localStorageService.get("pinItem"); // i am not sure this is the correct syntax
    }
}

function controller(pinnedStateService){
  $scope.pinState = pinnedStateService.pinState;
  $scope.toggleState = pinnedStateService.toggleState; // binding function to scope so you can use it on the view
}

in the view -
 <element ui-class="{'active': pinState}" />

Good luck


text:
Q: Change bullet type for each level of Outline Environment I love using the outline environment (outlines package) for taking notes in class. \1 uses a standard bullet, \2 uses a dash. I wanted to make \3 a bullet and \4 a dash as well. How would I go about doing this as I'm fairly new to LaTeX.

A: The outline environment (in its default form) behaves as itemize, so you can modify \labelitemiii and \labelitemiv:
\renewcommand{\labelitemiii}{\textbullet}
\renewcommand{\labelitemiv}{\textendash}

MWE:
\documentclass{article}
\usepackage{outlines}

\renewcommand{\labelitemiii}{\textbullet}
\renewcommand{\labelitemiv}{\textendash}

\begin{document}
\begin{outline}
   \1 Level 1
      \2 Level 2
         \3 Level 3
            \4 Level 4
\end{outline}
\end{document}

Output:


text:
Q: How to send the result data to file text? I am trying  to send the resulted data from a python script to a file text.
import string
import serial
import time
from array import array
import struct
import binascii
ser = serial.Serial(
                    port='COM4',\
                    baudrate=230400,\
                    parity=serial.PARITY_NONE,\
                    stopbits=serial.STOPBITS_ONE,\
                    bytesize=serial.EIGHTBITS,\
                    timeout=0)
text_file = open('C:\\Users\\user\\Ciphertxt.txt', 'w')
f = open(r'C:\\Users\\user\\Plaintxt.txt', 'r')
for a in f:
   plaintxt_16b=a[0:32]
   plaintext=binascii.unhexlify(plaintxt_16b)
   clear_msg=b'\x24'+b'\x73'+b'\x10'+plaintext
   ser.write(clear_msg)
   time.sleep(0.5)
   print(ser.read(156))
   text_file.write(ser.read(156))
ser.close()                # close ports

This line print(ser.read(156)) already displayed for me the good data, so  I am sure about results which is:
*************************
e0370734 313198a2 885a308d 3243f6a8
Go encrypt..
Encrypt done..
196a0b32 dc118597  2dc09fb 3925841d
***********************
*************************
ccddeeff 8899aabb 44556677   112233
Go encrypt..
Encrypt done..
d6e4d64b 27d8d055 c5c7573a 8df4e9aa
***********************
*************************
54776f20 4f6e6520 4e696e65 2054776f
Go encrypt..
Encrypt done..
155d4a8c 17d78b93 409745dd e73be537
***********************

But the Ciphertxt.txt file just gives me those three lines.
**

**

**

I don't understand where the problem is.

A: Once you read the data from ser.read(156), that data is removed from ser and it won't be available to you again.
So, reading that data twice can either give you garbage data or not give any data at all.
You should store it in a variable. The following code would work just fine.
data = ser.read(156)
print data
text_file.write(data)

A: Probably, the issues lies in reading from your serial port two times by executing two ser.read, thus you should do:
ser.write(clear_msg)
time.sleep(0.5)
recv_msg = ser.read(156)
print(recv_msg) #for debugging
text_file.write(recv_msg)


text:
Q: Cannot figure out output of SQL query There are 2 tables:

And a query:
SELECT DISTINCT A FROM R1 AS a
WHERE NOT EXISTS (
    SELECT * FROM R2 AS b
    WHERE NOT EXISTS (
        SELECT * FROM R1 AS c
        WHERE c.A = a.A AND c.C = a.C AND c.B = b.B
    )
);

The answer is 1, 3 but I cannot figure out why. Can someone explain to me why the answer is this?

A: I do not understand the question 100% but I will do my best:
I believe this is the part that confuses you:
WHERE c.A = a.A AND c.C = a.C AND c.B = b.B

If you change it to
WHERE c.A = a.A AND c.C = a.C AND c.B = a.B

You will get the result you are talking about and you are expecting to get.
Here is the demo.
Ok if it is not clear to you why, then maybe this will help:
1
insert into R1 values(1, 'b', 'w')
insert into R1 values(1, 'a', 'w')
insert into R1 values(1, 'c', 'w')

3
insert into R1 values(3, 'a', 'p')
insert into R1 values(3, 'c', 'p')
insert into R1 values(3, 'b', 'p')

This above are the data responsable for the result of 1,3.
They are the ones that have c.A = a.A AND c.C = a.C AND c.B = b.B


text:
Q: Twitter Bootstrap DropDown Menu Issue I'm new to Bootstrap and am learning how to use it. I'm having some trouble getting a simple Dropdown menu to "drop down" when clicked on this beta site.
I would really appreciate if someone could look at my page source and let me know what's wrong. Below is the html of the dropdown menu.

      Restavec Freedom Alliance

Home

About

Blog

            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

A:

The reason why your menu is not working properly is because you're initiating the same script three times. The bootstrap.js and .min.js variation have all the plugins packaged within them, one is the full dev version and the other is meant for production, the minified version. The third script is a loose plugin script which is not needed if you are already including the packed version. So remove the second and third scripts loaded in your header and your menu should work.
Edit
Just noticed something else, the .collapse class was also preventing the menu from showing since it is only used upon mobile nav collapse, so it does not need to be included.


text:
Q: Simple expect once with arguments I'm trying to get this simple test to work.
let querySpy = sinon.spy(db.query);

querySpy.expects().once().withArgs(`USE myDatabase`);

I'm trying to put a spy on a method, expect it to be called once with specific arguments. Easier said than done.
I cannot put the spy on db, results in TypeError: Attempted to wrap undefined property undefined as function (it's an object).
I'm looking at: https://gist.github.com/yoavniran/1e3b0162e1545055429e#sinon-chai
I can't find a calledOnceWith method. Does it exist?

A: You can use args to verify the arguments that are sent to the function.
 sinon.spy(db, "query");  //spy on existing method
 expect(db.query.calledOnce).to.be.true; //verify is called once
 const args = db.query.getCalls()[0].args; //get the arguments
 expect(args[0]).to.equal(`USE myDatabase`); //verify the arguments.

This is one way to verify args.


text:
Q: Kinematic equations using Universal Gravitation This has been asked on here before, but the question was never fully answered. After reading through the math, I get stuck at what seems like a dead end.
This is what I have so far:
The gravitational force is given by
$$F = \dfrac{Gm_1m_2}{r^2}$$
and if you divide force by mass to get acceleration you have
$$a = \dfrac{Gm}{r^2}$$
to find velocity, you have to integrate acceleration with respect to time. Unfortunately, the equation is a function of position, which is itself a function of time. In order to integrate, you have to multiply both sides of the equation by velocity to cancel out ${\mathrm{d}t}$.
$$V^2 = Gm\int \dfrac{1}{r^2} \,\mathrm{d}t \dfrac{\mathrm{d}r}{\mathrm{d}t}$$
I solved this equation and got
$$V = \pm \sqrt{c-\frac{Gm}{r}}$$
From here I tried to integrate again to get position, multiplying both sides to get ${\mathrm{d}r}$ by itself.
$$RV = \int \sqrt{c-\frac{Gm}{r}}\, \mathrm{d}t \dfrac{\mathrm{d}r}{\mathrm{d}t}$$
After that, I was planning to divide the equation I got by velocity, in order to get the equation for R. But before I could do that I realized that I had a couple of problems. For starters, if I integrated my equation for velocity with respect to position, I would have a function for position which takes itself as an input. And besides that, When I tried to integrate I got a very convoluted function with imaginary numbers, which doesn't really make sense in the context of kinematics.
So I was hoping that somebody here would be able to tell me where I went wrong solving this.

A: you can do it like this:
velocity v(r)
$$a=\frac{dv}{dt}=-\frac{G\,m}{r^2}\\
\frac{v\,dv}{dt}=-\frac{G\,m}{r^2}\frac{dr}{dt}\quad\Rightarrow\\
\int v\,dv=-\int \frac{G\,m}{r^2}\,dr\\
\frac{v^2}{2}=\frac{G\,m}{r}\\
v(r)=\sqrt{2}\,\sqrt{\frac{G\,m}{r}}$$
position r(t)
$$\frac{dr}{dt}=v(r)=\sqrt{2}\,\sqrt{\frac{G\,m}{r}}\quad \Rightarrow\\
dr\,\sqrt{r}=\sqrt{2\,G\,m}\,\,dt\\
\int dr\,\sqrt{r}=\int \sqrt{2\,G\,m}\,\,dt\\
\frac{2}{3}\,r^{3/2}=\sqrt{2\,G\,m}\,t\\
r(t)=\left(\frac{3}{2}\,\sqrt{2\,G\,m}\,t\right)^{2/3}+r_0$$
$$v(t)=v(r(t))$$

A: Actually, we can write $a=v\frac{dv}{dx}$, which will make things easier:
$$vdv=-\frac{Gm}{x^2}dx$$
$$\int_0^{\Delta v}vdv=-\int_\infty^x \frac{Gm}{x^2}dx$$
$$\Delta v(x)=\sqrt\frac{2Gm}{x}$$
$$\sqrt x\,dx=\sqrt {2Gm}\,dt$$
$$\int_\infty^x\sqrt x\,dx=\int_0^t \sqrt {2Gm}\,dt$$
$$\frac{9}{8}x^3(t)=Gmt^2$$
Note that last equation is actually Kepler's third law!
Hope it helps!


text:
Q: Wordpress post visualization on homepage i am not able to display the custom fields in a wordpress home page.
This is the code (fully working except for the part that show the custom field)
<?php
  $thumbnails = get_posts('numberposts=3&cat=3');
  foreach ($thumbnails as $thumbnail) {
    if ( has_post_thumbnail($thumbnail->ID)) {
        echo '
ID ) . '" title="' . esc_attr( $thumbnail->post_title ) . '">';
        echo get_the_post_thumbnail($thumbnail->ID, 'medium',  array('class'=> "blur") );
        echo '';
    echo '
' . esc_attr( $thumbnail->post_title ) . '
';
    echo get_post_meta($post->ID, "RiassuntoHome", true);
    echo '
Giorni restanti: 30 giorni';
    echo '
Premio: 10.000 euro';
    echo '
ID ) . '">Invia la Tua Idea
';
    }
  }
?>
<?php echo '

' ?>

A: The object is $thumbnail, not $post:
echo get_post_meta($thumbnail->ID, "RiassuntoHome", true);


text:
Q: Apache Kafka: Replay messages in a topic I'm considering using Apache Kafka as an event store for storing events within a microservice.
One thing that I read through various blogs is that Kafka can be considered to be a single source of truth, where Kafka log will store all the events for a given topic.
I was wondering if Kafka has the ability to replay messages since the beginning of time (in case there is a hard drive/network crash that occurs for example)?
(note that i see that there are some logs stored in the /tmp folder under a topic directory). Does anyone know of any command (if any) that can be invoked to replay the messages in the topic?

A: Yes, You can replay message. As Consumer have a control over resetting the offset. You can start reading messages from the beginning or if you know any existing offset value you can read it from there as well.
Once the message is committed it will be in there in topic until its retention period is over. Default retention period is 7 days, however you can change it any time.

A: Yes, you can seek to a specific offset, but

beginning of time

depends on the topic or broker configuration. IIRC, the default retention is 7 days.
Refer to the the Kafka documentation.


text:
Q: Scrapy, showing description image alt I tried to scrape instagram, for the example i tried to scrape nike instagram. But, ijust want get the discription of image. The description image inside tag . I tried to show it but doesn't work.
This is my code :
import scrapy
class Nike(scrapy.Spider):
    name = 'nike'
    urls = 'http://www.instagram.com/nike/'
    start_urls = [urls]
    allowed_domains = ['http://instagram.com']

    def parse(self, response):
        for N in response.css('div._jjzlb'):
            yield{
                'name':N.css('alt::text').extract()
            }

A: As requested by OP in the comments, here's an example of parsing JavaScript data from the HTML source directly, using js2xml (disclaimer: I'm the author of js2xml):
$ scrapy version -v
Scrapy    : 1.4.0
lxml      : 3.7.3.0
libxml2   : 2.9.3
cssselect : 1.0.1
parsel    : 1.2.0
w3lib     : 1.17.0
Twisted   : 17.1.0
Python    : 2.7.12+ (default, Sep 17 2016, 12:08:02) - [GCC 6.2.0 20160914]
pyOpenSSL : 17.0.0 (OpenSSL 1.0.2g  1 Mar 2016)
Platform  : Linux-4.8.0-53-generic-x86_64-with-Ubuntu-16.10-yakkety

$ scrapy shell http://www.instagram.com/nike/
2017-05-30 10:06:39 [scrapy.utils.log] INFO: Scrapy 1.4.0 started (bot: scrapybot)
(...)
2017-05-30 10:06:40 [scrapy.downloadermiddlewares.redirect] DEBUG: Redirecting (301) to <GET https://www.instagram.com/nike/> from <GET http://www.instagram.com/nike/>
2017-05-30 10:06:41 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.instagram.com/nike/> (referer: None)

>>> response.xpath('//script[contains(., "sharedData")]')
[<Selector xpath='//script[contains(., "sharedData")]' data=u'<script type="text/javascript">window._s'>]

>>> response.xpath('string(//script[contains(., "sharedData")])').get()
u'window._sharedData = {"activity_counts": null, "config": (...redacted...) "show_app_install": true};'

>>> import js2xml

>>> # get the JavaScript statements
>>> js = response.xpath('string(//script[contains(., "sharedData")])').get()

>>> # parse them with js2xml
>>> jstree = js2xml.parse(js)

>>> # locate the object we're interested in:
>>> # here it's the right-part of the following assignement:
>>> #                      |--- this bit
>>> # window._sharedData = {"activity_counts":...
>>>
>>> obj = jstree.xpath('//assign[left//identifier[@name="_sharedData"]]/right/*')[0]

>>> # convert this object to a Python dict
>>> sharedData = js2xml.jsonlike.make_dict(obj)
>>>
>>> from pprint import pprint

>>> # quite a lot of data...
>>> pprint(sharedData)
{'activity_counts': None,
 'config': {'csrf_token': 'JzQ8ja9YlG1cKqwAbvwacTKhOc4FuBDT', 'viewer': None},
 'country_code': 'FR',
 'display_properties_server_guess': {'pixel_ratio': 1.5,
                                     'viewport_width': 360},
 'entry_data': {'ProfilePage': [{'logging_page_id': 'profilePage_13460080',
                                 'user': {'biography': 'Just Do It.',
                                          'blocked_by_viewer': False,
                                          'connected_fb_page': None,
                                          'country_block': False,
                                          'external_url': 'http://nike.com/justdoit',
                                          'external_url_linkshimmed': 'http://l.instagram.com/?u=http%3A%2F%2Fnike.com%2Fjustdoit&e=ATOPqaPHEBPK4ylZ6YZRynSTQdp28oGedfFWw3gLtqoII1ZhtlDhLI0vu9Udbjg',
                                          'followed_by': {'count': 72447697},
                                          'followed_by_viewer': False,
                                          'follows': {'count': 136},
                                          'follows_viewer': False,
                                          'full_name': 'nike',
                                          'has_blocked_viewer': False,
                                          'has_requested_viewer': False,
                                          'id': '13460080',
                                          'is_private': False,
                                          'is_verified': True,
                                          'media': {'count': 897,
                                                    'nodes': [{'__typename': 'GraphVideo',
                                                               'caption': 'Eliud Kipchoge - 2:00:25\nThe barrier just got that much closer.\n#Breaking2 #JustDoIt',
                                                               'code': 'BTvxgGEAn-p',
                                                               'comments': {'count': 2274},
                                                               'comments_disabled': False,
                                                               'date': 1494064175,
                                                               'dimensions': {'height': 640,
                                                                              'width': 640},
                                                               'display_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/e15/18380674_1840678496198968_334757937257906176_n.jpg',
                                                               'id': '1508642110004428713',
                                                               'is_video': True,
                                                               'likes': {'count': 296763},
                                                               'owner': {'id': '13460080'},
                                                               'thumbnail_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/e15/18380674_1840678496198968_334757937257906176_n.jpg',
                                                               'video_views': 1193309},

                                                              (...redacted...)

                                                              {'__typename': 'GraphVideo',
                                                               'caption': u'We step onto the court as equals. Judged only by our performance. New Orleans sets the stage for All Star Weekend @nikebasketball.\xa0#EQUALITY #nike',
                                                               'code': 'BQlZFdugTIG',
                                                               'comments': {'count': 1172},
                                                               'comments_disabled': False,
                                                               'date': 1487273379,
                                                               'dimensions': {'height': 360,
                                                                              'width': 640},
                                                               'display_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/e15/16789854_771546756335957_8222167172487577600_n.jpg',
                                                               'id': '1451676781575746054',
                                                               'is_video': True,
                                                               'likes': {'count': 184595},
                                                               'owner': {'id': '13460080'},
                                                               'thumbnail_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/e15/c157.0.406.406/16789854_771546756335957_8222167172487577600_n.jpg',
                                                               'video_views': 627647}],
                                                    'page_info': {'end_cursor': 'AQCseCeUI_vJ_XzpTTIf7AhmwqbkBSf959347Wl03MM_ErpUQqP6RGjuJRdEcH1qJBCWvPGxUhpm6rPv5esAW5GvXHGodwmYA0eT51wnk8_-KA',
                                                                  'has_next_page': True}},
                                          'profile_pic_url': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-19/s150x150/17126848_1779368432381854_3589478532054515712_a.jpg',
                                          'profile_pic_url_hd': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-19/s320x320/17126848_1779368432381854_3589478532054515712_a.jpg',
                                          'requested_by_viewer': False,
                                          'username': 'nike'}}]},
 'environment_switcher_visible_server_guess': True,
 'gatekeepers': {'bn': True, 'ld': True, 'pl': True},
 'hostname': 'www.instagram.com',
 'language_code': 'en',
 'platform': 'web',
 'probably_has_app': False,
 'qe': {'bc3l': {'g': '', 'p': {}},
        'create': {'g': '', 'p': {}},
        'deact': {'g': '', 'p': {}},
        'disc': {'g': '', 'p': {}},
        'ebd': {'g': 'holdout', 'p': {'use_new_styles': 'false'}},
        'feed': {'g': '', 'p': {}},
        'gql': {'g': '', 'p': {}},
        'nav': {'g': '', 'p': {}},
        'nav_lo': {'g': '', 'p': {}},
        'pm': {'g': '', 'p': {}},
        'poe': {'g': '', 'p': {}},
        'profile': {'g': '', 'p': {}},
        'sidecar': {'g': '', 'p': {}},
        'su_universe': {'g': '', 'p': {}},
        'ufi': {'g': '', 'p': {}},
        'ufi_loggedout': {'g': '', 'p': {}},
        'us': {'g': '', 'p': {}},
        'us_li': {'g': '', 'p': {}},
        'video': {'g': '', 'p': {}}},
 'show_app_install': True}

>>> # nodes have a 'caption' key that looks like the "alt" attributes
>>> pprint(sharedData['entry_data']['ProfilePage'][0]['user']['media']['nodes'])
[{'__typename': 'GraphVideo',
  'caption': 'Eliud Kipchoge - 2:00:25\nThe barrier just got that much closer.\n#Breaking2 #JustDoIt',
  'code': 'BTvxgGEAn-p',
  'comments': {'count': 2274},
  'comments_disabled': False,
  'date': 1494064175,
  'dimensions': {'height': 640, 'width': 640},
  'display_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/e15/18380674_1840678496198968_334757937257906176_n.jpg',
  'id': '1508642110004428713',
  'is_video': True,
  'likes': {'count': 296763},
  'owner': {'id': '13460080'},
  'thumbnail_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/e15/18380674_1840678496198968_334757937257906176_n.jpg',
  'video_views': 1193309},
 {'__typename': 'GraphImage',
  'caption': 'Eliud Kipchoge - 2:00:25\nThe barrier just got that much closer.\n#Breaking2 #JustDoIt',
  'code': 'BTvj_-gg6B6',
  'comments': {'count': 2269},
  'comments_disabled': False,
  'date': 1494057096,
  'dimensions': {'height': 1080, 'width': 1080},
  'display_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/e35/18299402_128309274385168_1749644873230712832_n.jpg',
  'id': '1508582728264818810',
  'is_video': False,
  'likes': {'count': 484745},
  'owner': {'id': '13460080'},
  'thumbnail_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/18299402_128309274385168_1749644873230712832_n.jpg'},

(...redacted...)

 {'__typename': 'GraphVideo',
  'caption': u'We step onto the court as equals. Judged only by our performance. New Orleans sets the stage for All Star Weekend @nikebasketball.\xa0#EQUALITY #nike',
  'code': 'BQlZFdugTIG',
  'comments': {'count': 1172},
  'comments_disabled': False,
  'date': 1487273379,
  'dimensions': {'height': 360, 'width': 640},
  'display_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/s640x640/e15/16789854_771546756335957_8222167172487577600_n.jpg',
  'id': '1451676781575746054',
  'is_video': True,
  'likes': {'count': 184595},
  'owner': {'id': '13460080'},
  'thumbnail_src': 'https://scontent-cdg2-1.cdninstagram.com/t51.2885-15/e15/c157.0.406.406/16789854_771546756335957_8222167172487577600_n.jpg',
  'video_views': 627647}]
>>>


text:
Q: $wpdb SQL syntax for specific multiple database table entries I've just started delving into $wpdb SQL queries and am struggling with understanding what syntax I should be using.
The WordPress site that I am working on is a product comparison site. It has a review system as part of its theme. However the review system has not got a comparison element to it so I am trying to auto generate a series of HTML tables on the site front page which contains the review criteria.
So far I have been able to locate the correct database table (wp_6_postmeta). The table consists of four main columns:
meta_id
post_id
meta_key
meta_value
The meta_key column has hundreds of different fields, and I am trying to target four specific criteria at the moment:
_synopsis
_features
_specifications
_length
Ideally what I want is a series of tables that are added to every time a new review product is created that contains:
Synopsis
Features
Specifications
Length
... all grouped per product.
So I've been able to use the code below to pull in all the _synopsis meta_key fields but am struggling with also bringing in _features etc to work in a logical PHP loop.
What I need to know is should I be using a different syntax to the initial get_results("SELECT... line before the foreach loop starts, or should I be trying to add further get_results code at the point where I need the _features, _specifications, and _length to show. I have tried this but including the foreach loop again causes either jumbling up of results issues or the page not to show in the front end.
<?php
global $wpdb;
$result = $wpdb->get_results("SELECT * FROM wp_6_postmeta WHERE meta_key = '_synopsis'");
foreach ( $result as $print )   {
?>

            Meta ID
            <?php echo $print->meta_id;?>

            Post ID
            <?php echo $print->post_id;?>

            Meta Value (Synopsis)
            <?php echo $print->meta_value;?>

            Meta Value (Features)
            <?php echo $print->meta_value;?>

            Meta Value (Specifications)
            <?php echo $print->meta_value;?>

            Meta Value (Length)
            <?php echo $print->meta_value;?>

      <?php
        }
       ?>

A: In SQL, I'd be tempted to do this as a straightforward pivot, so something like:
SELECT entity
     , MAX(CASE WHEN attribute = 'a' THEN value END) a
     , MAX(CASE WHEN attribute  = 'b' THEN value END) b
     , etc.
 GROUP
    BY entity


text:
Q: Is there a "best" tokenization for NER training in OpenNLP? Is there a "best" tokenization for NER training in OpenNLP? I noticed that OpenNLP provides a max-entropy tokenizer that allows you to tokenize based on a trained model. I also noticed that OpenNLP provides a simple tokenizer. If I use the same tokenizer during runtime that I used to train my model, does it matter which tokenizer I use?
I would rather use the simple tokenizer for my application.

A: For most applications the quality of your tokenizer isn't very important and as long as you use the same one in training and after you should be fine.
However, the only way to be sure is to try the different tokenizers and compare the results - for some applications the difference between a good tokenizer and a great one may matter.


text:
Q: Append columns from excel file to csv file based on if statement I have two files:

*

*One with 'filename' and value_count columns (ValueCounts.csv)

*Another with 'filename' and 'latitude' and 'longitude' columns (GeoData.xlsx)

I have started by creating dataframes for each file and the specific columns within that I intend on using. My code for this is as follows:
Xeno_values = pd.read_csv(r'C:\file_path\ValueCounts.csv')
img_coords = pd.read_excel(r'C:\file_path\GeoData.xlsx')

df_values = pd.DataFrame(Xeno_values, columns = ['A','B'])
df_coords = pd.DataFrame(img_coords, columns = ['L','M','W'])

However when I print() each dataframe all the column values are returned as 'NaN'.
How do I correct this? And then write and if statement that iterates over the data and says:

if 'filename' (col 'A') in df_values == 'filename' (col 'W') in df_coords, append 'latitude' (col 'L') and 'longitude' (col 'M') to df_values

If any clarification is needed please do ask.
Thanks,
R

A: Check out the documentation for pandas read_csv and read_excel (https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html). These functions already return the data in a dataframe. Your code is trying to create a dataframe using a dataframe, which is fine if you don't specify columns, but will return all NaN values if you do.
So if you want to load the dataframes:
df_values = pd.read_csv(r'C:\file_path\ValueCounts.csv')
df_coords = pd.read_excel(r'C:\file_path\GeoData.xlsx')

Will do the trick. And if you just want specific columns:
df_values = pd.read_csv(r'C:\file_path\ValueCounts.csv', usecols=['A','B'])
df_coords = pd.read_excel(r'C:\file_path\GeoData.xlsx', usecols=['L','M','W'])

Make sure that those column names do actually exist in your csv files
If you want to rename columns (make sure you're doing all columns here):
df_values.columns = ['Filename', 'Date']

For adding lat/long to df_values you could try:
df = pd.merge(df_values, df_coords[['filename', 'LAT', 'LONG']], on='filename', how='inner')

Which assumes that there are columns 'filename' in both the values and coords dataframes, and that the coords dataframes has columns 'LAT' and 'LONG' in it.
Lastly, do out a tutorial on pandas (https://www.tutorialspoint.com/python_pandas/index.htm). Becoming more familiar with it will help you wrangle data better.


text:
Q: Wait while file load in Unity How I can load and return file from another method(use WWW)?
I want to do next:

*

*Method GetSettings(). Download file text, parse json and
return result.

*Call method from Start() and wait while GetSettings() return result.

How I can do this?

A: Looks like you want to downloaded data then wait then wait for the download to finish then download another data. If this is true the you can the code below will download data 2 times. You can increase the number of times by increasing the REQ_AMOUNT value.
It uses yield return StartCoroutine to wait for the current coroutine function to return before running again.
IEnumerator Start()
{

    int REQ_AMOUNT = 2;

    for (int i = 0; i < REQ_AMOUNT; i++)
    {
        yield return StartCoroutine(GetSettings());
    }
}

IEnumerator GetSettings()
{
    string url = RoomSettings.AbsoluteFilenamePath;

    if (Application.isEditor)
    {
        url = "file:///" + url;
    }

    var www = new WWW(url);
    yield return www;
    // Do some code, when file loaded
}


text:
Q: JMS between Enterprise applications We have a project where we want to link 2 enterprise systems together using JMS.
In a nutshell, system 1 sends a message to the queue.
Systems2 picks up that message, does a whole load of processing in the background for about 30mintues and then sends a message back to the queue for System1 to pick up.
Can we get away with 1 queue or do we need 2?
If we have 2 queues then, System1 writes to queue1, System2 picks up.
When system2 is ready, it writes to queue2 and System1 picks it up.
Which approach would be the best?
If anyone knows of any limitations to these approaches, or any better solutions, then please do share
Thanks
Damien

A: You can employ selectors on a queue, but I would advise keeping it simple and using 2 queues as you described.  I prefer to domain message types into separate queues and I think you'll find that the easiest to manage too.
A queue is largely just a logical name for a bucket of messages and little if any further overhead than all messages in a single queue.

A: If this is a dedicated peer-to-peer interface and neither of these applications acts like a server, then you could get away with a single queue.  However this model does not support the client-server pattern.  On the other hand, the client-server pattern supports a peer-to-peer interface as well as client-server interface and it is no harder to implement so why not use it?
Specifically, a server listens on a well-known queue.  Any app wanting to drive that service sends a message to the well-known queue.  The message contains the address of a Reply-To destination and the server sends the reply to that destination.  In this way a server application can process requests from many relatively anonymous (or authenticated if so desired) clients anywhere on the network.
This approach also supports the client and server queue not being on the same message engine.  It supports accessing the queues in FIFO mode which should be more performant.  It handles the classic asynch messaging case of fast producer, slow consumer better than a single queue.  It supports dynamic reply-to destinations.  It allows the applications to be relocated independent of each other.  And if what you have is truly a peer-to-peer with no elements of the client-server pattern then this architecture supports that too.


text:
Q: Can I tell with preprocessor code is in an mbed library or program The mbed forums are broken, so I'm posting here for some help.
mbed supports libraries and programs as separate entities.  In the spirit of module testing, I want to incorporate a test routine with my libary code.  If the library is imported as a program and compiled, then the main() would get built and linked, and generates some test output.  If the library is used normally, the main() is not built into the code, preventing linker errors.
are there any predefined preprocessor directives that I could look at to make this determination?   If not, does anyone have a suggestion on how I might implement a test routine into my library?
For clarity, here is a simple example:
Here is a link to the library/program in mbed if you want to experiment/pull request suggestions
example code that wants to know if it is a program or a library
#include "mbed.h"

class LED_TEST:public DigitalOut{
   public:
   LED_TEST(PinName pin):DigitalOut(pin) {};

   void TurnOn() {write(1);}
   void TurnOff() {write(0);}
};

#ifdef __IN_A_PROGRAM   //if I'm compiling as a program then I want to create this main for testing.
                        //if I'm compiling as a library I do not want the main to prevent linker problems
int main(void)
{
LED_TEST lt(LED1);
    while (1)
    {
        lt.TurnOn();
        wait(1);
        lt.TurnOff();
        wait(1);
    }
}
#endif


text:
Q: repaint() Method in java not calling the paint() method? Here is my code
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import javax.swing.JFrame;
import javax.swing.JPanel;

import com.leappainter.model.GetXYCoordinatesPOJO;

public class DrawXY extends JPanel {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private int x;
    private int y;
    private int d;

    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }
    public int getD() {
        return d;
    }
    public void setD(int d) {
        this.d = d;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.RED);
        g2d.drawOval(getX(), getY(), 30, 30);
        System.out.println("painting");
    }
    public void draw() {
        JFrame frame = new JFrame("Leap Draw");
        frame.add(new DrawXY());
        frame.setSize(600, 600);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void update(GetXYCoordinatesPOJO getxy) {
        // TODO Auto-generated method stub
        setX((int) getxy.getX());
        setY((int) getxy.getY());
        setD((int) getxy.getD());

        //System.out.println(getX());

        DrawXY draw = new DrawXY();
        draw.repaint();
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Update method is getting called by function which updates the value but the paint method is not getting called after 2 times.

A: You are calling repaint on a different instance!
Change ...
public void update(GetXYCoordinatesPOJO getxy) {
    // TODO Auto-generated method stub
    setX((int) getxy.getX());
    setY((int) getxy.getY());
    setD((int) getxy.getD());

    //System.out.println(getX());

    DrawXY draw = new DrawXY(); // < -- YOU CREATE NEW INSTANCE HERE
    draw.repaint();
    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

to
public void update(GetXYCoordinatesPOJO getxy) {
    // TODO Auto-generated method stub
    setX((int) getxy.getX());
    setY((int) getxy.getY());
    setD((int) getxy.getD());

    //System.out.println(getX());

    repaint();
    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And see VGR's comment ... +1 for him.


text:
Q: AbstractTable.update() - more complex condition? From the docs:

int SqlUtil::AbstractTable::update (
hash  set,
hash  cond,
reference< string >   sql,
hash  opt
)

updates rows in the table matching an optional condition and returns
  the count of rows updated; no transaction management is performed with
  this method
  Example:
int ucnt = table.update(("id": id), ("name": name));

where ("name": name) is a condition hash. Can the condition be more complex though? What if I had a list or a hash names and wanted to update all rows with a name that is in it? Is it possible to do it with one update statement or do I need to iterate through names?

A: Yes, the where condition can be complex with update statements generated by SqlUtil.
The where condition is represented by the cond parameter in the method docs in your question.
To update rows based on a match from a list of values, use op_in() as follows:
int rows = table.update(("col1": val1, "col2": val2), ("col3": op_in(my_list)));

This will generate SQL like:
update table set col1 = %v, col2 = %v where col3 in (%v)

(NOTE: the exact SQL generated will differ depending on the underlying database, and the %v characters are placeholder specifications for bind by value operations in the generated SQL where the actual values are sent separately to the SQL server for reasons described in the previous link)
To update values based on a match of a another column value, use op_like() as in:
int rows = table.update(("col1": val1, "col2": val2), ("col3": op_like("%some value%")));

Which will generate SQL like:
update table set col1 = %v, col2 = %v where col3 like %v

In general you can use any SQL operator function in the where clause of the update method.


text:
Q: Kotlin - chaining of safe call operator. unnecessary operator calls Take the following example which uses safe call operator (?.):
class Sample {
    class A(
            val sampleB: B? = B()
    )

    class B(
            val sampleC: C = C()
    )

    class C(
            val sampleInt: Int = 1
    )

    fun test() {
        val intInC: Int? = A().sampleB?.sampleC?.sampleInt
    }
}

I understand that we need a safe call operator on sampleB. But why do we need the safe call operator on sampleC.
If I remove that operator, it does not compile.
Based on my understanding of the operator, if sampleB were null, the line returns null. And if sampleB is not null, we can be sure that sampleC is not null, based on its type. But why does Kotlin force safe call operator on sampleC ?

A: A().sampleB?.sampleC?.sampleInt

parses as
((A().sampleB)?.sampleC)?.sampleInt

The types are
A(): A
A().sampleB: B?
(A().sampleB)?.sampleC: C?
((A().sampleB)?.sampleC)?.sampleInt: Int?

Because the type before sampleC is a B?, the ?. is required.

A: First of all, the safe call operator ?. will not break the chain of safe calls. When you write A().sampleB?.sampleC?.sampleInt, if A().sampleB is null, the chain will not stop at ?.sampleC but it will execute null?.sampleC. The type of A().sampleB?.sampleC will be C? but not C since it depends on the whole expression but not the type of the property. That's why ?. is needed if the previous expression is nullable.
If sampleB is the only nullable expression in the chain, you may consider using .run:
val intInC: Int? = A().sampleB?.run { sampleC.sampleInt }

A: I am guessing you are not convinced because, as you said, if it reaches the point in the chain where .sampleC is called it's because sampleB was not null, and if it was null it would not have reached this point.
The point here is that you are thinking in terms of implementation and, in that sense, you may be right. But you need to interpret it semantically: even though, for optimization reasons let's say, it doesn't need to go to the end of line when it finds a null before, still, the whole line needs to have a coherent meaning even when there is a null. And for that to be true you need the ? symbol.


text:
Q: String manipulation, optional character With grep, you can use a question mark ? to signify an optional character, that is a character that is to be matches 0 or 1 times.
$ foo=qwerasdf

$ grep -Eo fx? <<< $foo
f

The question is does Bash String Manipulation have a similar feature? Something like
$ echo ${foo%fx?}

A: You're probably talking about parameter expansion. It uses shell patterns, not regular expression, so the answer is no.
Upon further reading, I noticed that if you
shopt -s extglob

you can use extended pattern matching which can achieve something similar to regex, albeit with slightly different syntax.
Check this out:
word="mre"
# this returns true
if [[ $word == m?(o)re ]]; then echo true; else echo false; fi

word="more"
# this also returns true
if [[ $word == m?(o)re ]]; then echo true; else echo false; fi

word="mooooooooooore"
# again, true
if [[ $word == m+(o)re ]]; then echo true; else echo false; fi

Works with parameter expansion too,
word="noooooooooooo"
# outputs 'nay'
echo ${word/+(o)/ay}
# outputs 'nayooooooooooo'
echo ${word/o/ay}


text:
Q: DynamoHttpServletRequest.getRemotePort() is return 0 How to get client Remort Port I need client remote port for some validation. I tried to get Remote Port in request but result come only Zero 0. I seen that OOTB class DynamoHttpServletRequest its default return the zero any way to get the client remote port.
In OOTB class DynamoHttpServletRequest returns
public int getRemotePort() {
    return 0;
}

Is there any possibility to get remote port?
Any alternative ways to get Client Remote port?

A: I got the remote port help of implemented class HttpServletRequest.
public int getClientPort(DynamoHttpServletRequest req){
    int remortPortVal = req.getRequest().getRemotePort();
    return remortPortVal;
}


text:
Q: How to increment the empid with python in text file I have one text file in that there is two columns are available which names  'empid' and 'name'. Here  I want to increment the empid with 1(one) incremental value eachtime  means 10 times and name column will be repeatedly same. Here is the text file and python file
demo.txt file
empid   name

10      bhuvi

read_file.py file
fil = open('c:/users/$$$$$$/desktop/demo.txt','r')
fil2 = fil.read()
for  i in fil2:
     print(fil2[i],end='')
fil.close()

A: I don't understand the question, are you trying to append new rows to demo.txt like this?
demo.txt
empid, name
10, bhuvi
11, bhuvi
.., .....
20, bhuvi

If yes, then
with open('1.txt', 'r+') as f:
lines = f.readlines()
empid, name = lines[1].rsplit(',')
for i in range(1, 11):
    f.write(f'{int(empid) + i},{name}')


text:
Q: Command Query Separation: commands must return void? If CQS prevents commands from returning status variables, how does one code for commands that may not succeed?  Let's say you can't rely on exceptions.
It seems like anything that is request/response is a violation of CQS.
So it would seem like you would have a set of "mother may I" methods giving the statuses that would have been returned by the command.  What happens in a multithreaded / multi computer application?
If I have three clients looking to request that a server's object increase by one (and the object has limits 0-100).  All check to see if they can but one gets it - and the other two can't because it just hit a limit.  It would seem like a returned status would solve the problem here.

A:
It seems like anything that is request/response is a violation of CQS.

Pretty much yes, hence Command-Query-Separation. As Martin Fowler nicely puts it:

The fundamental idea is that we should divide an object's methods into two sharply separated categories:
Queries: Return a result and do not change the observable state of the system (are free of side effects).
Commands: Change the state of a system but do not return a value [my emphasis].

Requesting that a server's object increase by one is a Command, so it should not return a value - processing a response to that request means that you are doing a Command and Query action at the same time which breaks the fundamental tenet of CQS.
So if you want to know what the server's value is, you issue a separate Query.
If you really need a request-response pattern, you either need to have something like a convoluted callback event process to issue queries for the status of a specific request, or pure CQS isn't appropriate for this part of your system - note the word pure.

Multithreading is a main drawback of CQS and can make it can hard to do. Wikipedia has a basic example and discussion of this and also links to the same Martin Fowler article where he suggests it is OK to break the pattern to get something done without driving yourself crazy:

[Bertrand] Meyer [the inventor of CQS] likes to use command-query separation absolutely, but there are
exceptions. Popping a stack is a good example of a query that modifies
state. Meyer correctly says that you can avoid having this method, but
it is a useful idiom. So I prefer to follow this principle when I can,
but I'm prepared to break it to get my pop.

TL;DR - I would probably just look at returning a response, even tho it isn't correct CQS.

A: Article "Race Conditions Don't Exist" may help you to look at the problem with CQS/CQRS mindset.
You may want to step back and ask why counter value is absolutely necessary to know before sending a command? Apparently, you want to make decision on the client side whether you can increase counter more or not.
The approach is to let the server make such decision. Let all the clients send commands (some will succeed and some will fail). Eventually clients will get consistent view of the server object state (where limit has reached) and may finally stop sending such commands.
This time window of inconsistency leads to wrong decisions by the clients, but it never breaks consistency of the object (or domain model) on the server side as long as commands are handled adequately.


text:
Q: separate columns of a text file Hii experts i have a big text file that contain many columns.Now i want to extract each column in separate text file serially with adding two strings on the top.
suppose i have a input file like this
2 3 4 5 6
3 4 5 6 7
2 3 4 5 6
1 2 2 2 2

then i need to extract each column in separate text file with  two strings on the top
file1.txt      file2.txt     .... filen.txt

s=5            s=5
r=9            r=9
2              3
3              4
2              3
1              2

i tried script as below:but it doesnot work properly.need help from experts.Thanks in advance.
#!/bin/sh
for i in $(seq 1 1 5)

do
echo $i
awk '{print $i}' inp_file  > file_$i
done

A: Could you please try following, written and tested with shown samples in GNU awk. Following doesn't have close file function used because your sample shows you have only 5 columns in Input_file. Also created 2 awk variables which will be printed before actual column values are getting printed to output file(named var1 and var2).
awk -v var1="s=5" -v var2="r=9" '
{
  count++
  for(i=1;i<=NF;i++){
    outputFile="file"i".txt"
    if(count==1){
      print (var1 ORS var2) > (outputFile)
    }
    print $i > (outputFile)
  }
}
' Input_file

In case you can have more than 5 or more columns then better close output files kin backend using close option, use this then(to avoid error too many files opened).
awk -v var1="s=5" -v var2="r=9" '
{
  count++
  for(i=1;i<=NF;i++){
    outputFile="file"i".txt"
    if(count==1){
      print (var1 ORS var2) > (outputFile)
    }
    print $i >> (outputFile)
  }
  close(outputFile)
}
'  Input_file

A: Pretty simple to do in one pass through the file with awk using its output redirection:
awk 'NR==1 { for (n = 1; n <= NF; n++) print "s=5\nr=9" > ("file_" n) }
     { for (n = 1; n <= NF; n++) print $n > ("file_" n) }' inp_file

A: With GNU awk to internally handle more than a dozen or so simultaneously open files:
NR == 1 {
    for (i=1; i<=NF; i++) {
        out[i] = "file" i ".txt"
        print "s=5" ORS "r=9" > out[i]
    }
}
{
    for (i=1; i<=NF; i++) {
        print $i > out[i]
    }
}

or with any awk just close them as you go:
NR == 1 {
    for (i=1; i<=NF; i++) {
        out[i] = "file" i ".txt"
        print "s=5" ORS "r=9" > out[i]
        close(out[i])
    }
}
{
    for (i=1; i<=NF; i++) {
        print $i >> out[i]
        close(out[i])
    }
}

A: split -nr/$(wc -w <(head -1 input) | cut -d' ' -f1) -t' ' --additional-suffix=".txt" -a4 --numeric-suffix=1  --filter "cat <(echo -e 's=5 r=9') - | tr ' ' '\n' >\$FILE" <(tr -s '\n' ' ' <input) file
This uses the nifty split command in a unique way to rearrange the columns. Hopefully it's faster than awk, although after spending a considerable amount of time coding it, testing it, and writing it up, I find that it may not be scalable enough for you since it requires a process per column, and many systems are  limited in user processes (check ulimit -u). I submit it though because it may have some limited learning usefulness, to you or to a reader down the line.
Decoding:
split -- Divide a file up into subfiles. Normally this is by lines or by size but we're tweaking it to use columns.
-nr/$(...) -- Use round-robin output: Sort records (in our case, matrix cells) into the appropriate number of bins in a round-robin fashion. This is the key to making this work. The part in parens means, count (wc) the number of words (-w) in the first line (<(head -1 input)) of the input and discard the filename (cut -d' ' -f1), and insert the output into the command line.
-t' ' -- Use a single space as a record delimiter. This breaks the matrix cells into records for split to split on.
--additional-suffix=".txt" -- Append .txt to output files.
-a4 -- Use four-digit numbers; you probably won't get 1,000 files out of it but just in case ...
--numeric-suffix=1 -- Add a numeric suffix (normally it's a letter combination) and start at 1. This is pretty pedantic but it matches the example. If you have more than 100 columns, you will need to add a -a4 option or whatever length you need.
--filter ... -- Pipe each file through a shell command.
Shell command:
cat -- Concatenate the next two arguments.
<(echo -e 's=5 r=9') -- This means execute the echo command and use its output as the input to cat. We use a space instead of a newline to separate because we're converting spaces to newlines eventually and it is shorter and clearer to read.
- -- Read standard input as an argument to cat -- this is the binned data.
| tr ' ' '\n' -- Convert spaces between records to newlines, per the desired output example.
>\$FILE -- Write to the output file, which is stored in $FILE (but we have to quote it so the shell doesn't interpret it in the initial command).
Shell command over -- rest of split arguments:
<(tr -s '\n' ' ' < input) -- Use, as input to split, the example input file but convert newlines to spaces because we don't need them and we need a consistent record separator. The -s means only output one space between each record (just in case we got multiple ones on input).
file -- This is the prefix to the output filenames. The output in my example would be file0001.txt, file0002.txt, ..., file0005.txt.


text:
Q: Not able to Create a new confluence page as a child of another page Not able to Create a new confluence page as a child of another page with below curl req:
curl -u admin:admin -X POST -H 'Content-Type:application/json' -d '{"type":"page","title":"new page",
"ancestors":[{"id":456}], "space":{"key":"TST"},"body":{"storage":{"value":
"
This is a new page
","representation":"storage"}}}'
https://wiki/rest/api/content/

OS: Windows
Error on using -o with curl:
curl: (7) Failed to connect to  port 80: Connection refused


text:
Q: In IntelliJ, how to automatically change getter/setter from static to non-static In IntelliJ, when changing a variable declaration from static to non-static, is there a way to automatically change its getter and setter's declaration from static to non-static?

A: I don't think it can be done automatically. When you call a non-static member of a class, you need a reference to the object.
something = MyClass.getSomething():

Should be changed to
something = instanceOfMyClass.getSomething();

It's hard to guess which variable must be put in place of instanceOfMyClass.


text:
Q: How to SELECT * WHERE JSON keys contain ANY/IN (array of values) I am dealing with a Symfony "workflow" "Marker" and Postgres. (and Doctrine)
in the db, the column "status" contains JSON data like this
{"needs_address":1,"needs_contacts":1,"needs_education":1,"needs_health_and_social":1,"has_profile_photo":1,"has_letter":1}

I figured out how to query like this
SELECT id, profile_status, beneficiary_code
FROM public.beneficiary_profile
WHERE profile_status->>'needs_address' = '1'

How can I query for a list of status' like
('needs_education','needs_contacts','needs_address')
without writing it all out like
WHERE profile_status->>'needs_address' = '1'
    OR profile_status->>'needs_contacts' = '1'
    OR profile_status->>'needs_education' = '1'

I figure there must be a way with JSON functions and maybe IN() or ANY()

A: You will need to unnest the elements in order to be able to use an IN clause, something like:
select *
from public.beneficiary_profile p
where exists (select *
              from jsonb_each_text(p.status) as x(ky,val)
              where x.ky in ('needs_address', 'needs_contact', 'needs_education')
                and x.val = '1');


text:
Q: Remove dynamic elements that were created after the dom was loaded I have a series of fieldset elements that are hidden when all of the list items inside them are not visible. The problem is I want to actually remove the field sets after they slide up and are hidden but I'm having trouble getting that to work.

$(document).ready(function () {
    $('body').on("click", ".readBtn", function (e) {
        var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');

        $('#chapter_'+chapterid).slideUp(function () {
          if (!$(this).is(":visible")
             && !$(this).siblings("li").is(":visible")) {
            // Hide `fieldset`
            var parent = $(this).closest("fieldset");
            parent.slideUp();
            parent.remove();
          }
        });
    });
});
button.readBtn {
    margin-left: 1em;
}

<fieldset class="story">
    <legend>

            Title 1

    </legend>

                Chapter Title

            <button class="readBtn" id="readBtn_9">
                Mark as Read
            </button>

</fieldset>
<fieldset class="story">
    <legend>

            Title 2

    </legend>

                Chapter Title

            <button class="readBtn" id="readBtn_10">
                Mark as Read
            </button>

                Chapter Title

            <button class="readBtn" id="readBtn_12">
                Mark as Read
            </button>

</fieldset>

I've read that you can't use the jquery.click call in order to remove an element that was created after page load, so that's why I went with using the on call. But I'm having trouble getting it to work.

A: Try
$(document).ready(function () {
    $('.readBtn').click(function () {
        var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');

        $('#chapter_'+chapterID).slideUp(function() {
          if (!$(this).is(":visible")
             && !$(this).siblings("li").is(":visible")) {
            // hide `fieldset`
            // remove `fieldset` if all `li` siblings _not_ visible ,
            // at `.hide()` `complete` callback
            $(this).closest("fieldset").hide(function() {
              $(this).remove()
            })
          }
        });

    });
});

$(document).ready(function () {
$('.readBtn').click(function () {
    var chapterID = $(this).attr('id').replace(/[A-Za-z_]+/g, '');

    $('#chapter_'+chapterID).slideUp(function() {
      if (!$(this).is(":visible")
         && !$(this).siblings("li").is(":visible")) {
        // hide `fieldset`
        $(this).closest("fieldset").hide(function() {
          $(this).remove()
        })
      }
    });

});
})
button.readBtn {
    margin-left: 1em;
}

<fieldset class="story">
    <legend>

            Title 1

    </legend>

                Chapter Title

            <button class="readBtn" id="readBtn_9">
                Mark as Read
            </button>

</fieldset>
<fieldset class="story">
    <legend>

            Title 2

    </legend>

                Chapter Title

            <button class="readBtn" id="readBtn_10">
                Mark as Read
            </button>

                Chapter Title

            <button class="readBtn" id="readBtn_12">
                Mark as Read
            </button>

</fieldset>

A: This is what I would do:
$(document).ready(function () {
    $('body').on("click", ".readBtn", function (e) {
        liEl = $(e.currentTarget).parent();
        var chapterID = $(e.currentTarget).attr('id').split('_').pop();

        $('#chapter_'+chapterID).slideUp(function () {
          if (!liEl.is(":visible")
             && !liEl.siblings(":visible").length > 0) {
            // Hide `fieldset`
            var parent = liEl.closest("fieldset");
            parent.slideUp();
            parent.remove();
          }
        });
    });
});

http://jsfiddle.net/jplato/zp91wzc0/1/


text:
Q: Is there a way to tell if a composite number is the product of a (1x9) or a (3x3) factors The $(1\times 9)$ and $(3 \times3)$ here refer only to the last digit of the factors. For example can we tell if $1159=19 \times 61$ is a $(1 \times 9)$ product without factoring it.
We want to be able to distinguish between composite integers having the same last digit (like $1159=19 \times 61$ and $1339=13 \times 103$) without factoring them.
Is there a simple test to determine the last digit of the factors given a composite integer?


text:
Q: $on don't catch $broadcast I have a Angular Project and I want create Authentication mechanism so i have the following controller:
angular.module('authModule')
.controller('LoginCtrl', function($rootScope, $location, loginRESTService, UserService){
    var login = this;

    function signIn(user) {
        loginRESTService.login(user)
            .then(function(response) {
                console.log(response);
                user.access_token = response.user_id;
                UserService.setCurrentUser(user);
                $rootScope.$broadcast('authorized');
                $location.path("/formList");
            });
    }
})

additional I have a main controller with the following methods
angular.module('authModule')
.controller('MainCtrl', function ($rootScope, $state, LoginService, UserService) {
    var main = this;

    $rootScope.$on('authorized', function() {
        console.log("ENTRE CON PERMISO");
        main.currentUser = UserService.getCurrentUser();
    });

    $rootScope.$on('unauthorized', function() {
        console.log("ENTRE SIN PERMISO");
        main.currentUser = UserService.setCurrentUser(null);
        $state.go('login');
    });
})

the problem it's that 'authorized' and 'unauthorized' never was invoked and don't have idea why
my app.js file
angular
  .module('pysFormWebApp', [
    ...
    'translateModule',
    'formModule',
    'authModule'
  ])
  .config(function ($routeProvider,  $httpProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl',
        controllerAs: 'main'
      })
      .when('/login', {
        templateUrl: 'views/auth/login.html',
        controller: 'LoginCtrl',
        controllerAs: 'login'
      })
      .otherwise({
        redirectTo: '/'
      });

my index.html  (only a part because is so long and is the index that generate yo angular)

        <button ng-if="main.currentUser" class="btn btn-default navbar-btn" ng-click="main.logout()">Logout {{main.currentUser.name}}
        </button>

A: First, you are not broadcasting the 'unauthorized' event. because of that the $rootScope.on('unauthorized') is not working.
Second. Maybe are running the main controller before the login controller, and because of that your controller doesn't catch the event.
let me know if it solves your problem.