text:
Q: Why does Typescript infer 'never' instead of intersection type? Given the following example:
interface Data {
    name: string;
    value: number;
}

const data :Data = {
    name: 'name',
    value: 1,
}

const updateValue = (key: keyof Data, value: string | number): void => {
    data[key] = value;
};

link to ts-playgound
Typescript shows the following error:
Type 'string | number' is not assignable to type 'string & number'.
  Type 'string' is not assignable to type 'string & number'.
    Type 'string' is not assignable to type 'number'.

Which is clear and understandable. However if I add a union type to the interface like so:
type MultiType = 'x' | 'y';

interface Data {
    name: string;
    value: number;
    multiType: MultiType | null;
}

const data :Data = {
    name: 'name',
    value: 1,
    multiType: null,
}

const updateValue = (key: keyof Data, value: string | number): void => {
    data[key] = value;
};

link to ts-playgound
I get the following error:
Type 'string | number' is not assignable to type 'never'.
  Type 'string' is not assignable to type 'never'.

Typescript accepts it if I use the intersection type string & number & MultiType but it also accepts never.
This seems inconsistent to me. Is this maybe a bug?

A: string & number is equivalent to never, and so is string & number & (MultiType | null).   There are no values which are both a string and a number, so no values satisfy string & number or string & number & AnythingElse.
Right now the latter explicitly reduces to never because it contains unions of these equivalent-to-never types, which is really ugly to leave like that.  Specifically, the compiler distributes intersections over unions, so
string & number & ('x' | 'y' | null)

becomes
(string & number & 'x') | (string & number & 'y') | (string & number & null)

That type isn't particularly enlightening to people, so the compiler checks that each of those union constituents is equivalent to never and reduces the type to
never | never | never

which is just
never

as you saw.

So why doesn't string & number by itself get immediately reduced to never?  Well originally the idea was that it would help people understand where the bug in their code came from, since string is not assignable to number is more enlightening that string is not assignable to never.
Unfortunately while string & number is equivalent to never in terms of what values are assignable to and from it, in TS3.5 and below the compiler doesn't always treat them the same, which is confusing.
Therefore it looks like, starting in TS3.6, empty intersections like string & number will be reduced to never explicitly.  Once TS3.6 is released, your above code will act the same in both cases, and you'll get the string | number is not assignable to never error.

Okay, hope that helps; good luck!

A: Two things :

*

*It's only logical that TypeScript doesn't accept string | number as type for your value parameter, because all of the following :

*

*string | number is not assignable to string because number is not assignable to string in case the key is 'name'

*string | number is not assignable to number because string is not assignable to number in case the key is 'value' (both of there were already true in your first example)

*string | number is not assignable to MultiType | null because both number and string are not assignable to 'x' | 'y' | null in case the key is 'multiType'
For some reason however, in your first example TypeScript simply stops on the first "wrong" case and gives you this error (Even though there are really two things wrong already).
In the second case, you could have seen the same error message because the incompatibility of types is still there, it seems like the inference goes a little deeper and tells you that the problem is deeper than this. As to why is the error message formatted like this, I don't really know and I guess it would require going deeper into how are things inferred by the compiler here. In the end, the compiler is right, but the error message could be clearer.

For your second question, the never type documentation says :

The never type is a subtype of, and assignable to, every type

So that's why you can specify your value to be of type never, and assign it to your data. Because it will never happen.


text:
Q: Searching an Array VBA Excel I wish vba to search a given cell for "ANY" of these phrases and if it should find any of these phrases change the colour of text in another cell Green other wise turn it red.
So far i can get it to search the cell however its marking everything as red even though I know they should be green. I assume it is not searching the entire content of the array.
Here is what i have so far:
Sub Test()

    Dim celltxt1 As String, mvarr1, a

    celltxt = ActiveSheet.Range("G21:G128").Select
    mvarr1 = Array("Tom", "Alison1", "Paul", "Deb2", "Pr123", "21", "18", "Pie-1", "Run", "Swim")

   For Each a In mvarr1
       If (InStr(1, celltxt1, CStr(a), vbTextCompare) > 0) Then
            ActiveSheet.Range("I21:I128").Font.Color = vbGreen
      Else
            ActiveSheet.Range("I21:I128").Font.Color = vbRed
      End If
   Next a
End Sub

Any advice or suggestion would be appreciated

A: Try to use this code:
Sub Test()

   Dim celltxt1 As String, mvarr1, a

   celltxt = ActiveSheet.Range("G21:G128").Select
   mvarr1 = Array("Tom", "Alison1", "Paul", "Deb2", "Pr123", "21", "18", "Pie-1", "Run", "Swim")

   Dim isFound As Boolean
   isFound = False

   For Each a In mvarr1
     If (InStr(1, celltxt1, CStr(a), vbTextCompare) > 0) Then
          isFound = True
          Exit For
     End If
   Next a

   If isFound = True Then
       ActiveSheet.Range("I21:I128").Font.Color = vbGreen
   Else
       ActiveSheet.Range("I21:I128").Font.Color = vbRed
   End If

End Sub

A: Because you set the colour for each item in the array, it'll end up red if the last item in the array isn't found, no matter what happened before.
The simplest change would just be to set to red as a default, then set green if any are found.
You can also use Exit For to stop looping once the first match is found.
Dim clrCell
clrCell = vbRed

For Each a In mvarr1
   If (InStr(1, celltxt1, CStr(a), vbTextCompare) > 0) Then
       clrCell = vbGreen
       Exit For
   End If
Next a

ActiveSheet.Range("I21:I128").Font.Color = clrCell

A: If you are just trying to make each corresponding cell in column "I" a color based on the cell in column "G" then you will want to use the OFFSET function.
Sub Test()
    Dim celltxt1 As String, mvarr1, a
    Set celltxt = ActiveSheet.Range("G21:G128")
    mvarr1 = Array("Tom", "Alison1", "Paul", "Deb2", "Pr123", "21", "18", "Pie-1", "Run", "Swim")
    For Each b In celltxt
       b.Select
           For Each a In mvarr1
               If (InStr(1, b, CStr(a), vbTextCompare) > 0) Then
                   ActiveCell.Offset(0, 2).Font.Color = vbGreen
                   Exit For
               Else
                   ActiveCell.Offset(0, 2).Font.Color = vbRed
               End If
           Next a
    Next b
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error: 'webView' undeclared I'm trying to display the webpage
http://johnbridge180.com/Boarders.html
I can't quite get this to work I only have one error: "'webView' undeclared". Here is the code for the app:
WebViewController.h:
    //
    //  WebViewController.h
    //  Boarders
    //
    //  Created by John Bridge on 5/2/11.
    //  Copyright 2011 Bridge and co. All rights reserved.
    //

    #import <UIKit/UIKit.h>
    @interface WebViewController : UIViewController {

IBOutlet UIWebView *displayWeb;
    }
    @end

WebViewcontroller.m:
   //
   //  WebViewController.m
   //  Boarders
   //
   //  Created by John Bridge on 5/2/11.
   //  Copyright 2011 Bridge and co. All rights reserved.
   //

   #import "WebViewController.h"

   @implementation WebViewController
   - (void)viewDidLoad {
       displayWeb.userInteractionEnabled = true;
       [displayWeb loadRequest:[[NSURLRequest alloc] initWithURL:[[NSURL alloc]            initWithString:@"http://www.johnbridge180.com/Boarders.html"]]];
[super viewDidLoad];
   }
   @end

Hope you guys can help Thank You!!

A: The code that you presented here is fine. However from the error I assume that you are trying to call the 'displayWeb' variable with the 'webView' name. Searching thought your .m file for 'webView' and you'll find it.
Also try do clean your project if that doesn't work.
Your code is also leaking (a lot). Please review the cocoa memory management basics!

A: there are a few problems here...
You are not creating your url and request correctly, they would not be cleaned up correctly the way you were doing it.
- (void)viewDidLoad {
       displayWeb.userInteractionEnabled = true;
       [displayWeb loadRequest:[NSURLRequest requestWithUrl:[NSURL urlWithString:@"http://www.johnbridge180.com/Boarders.html"]]];
       [super viewDidLoad];
   }

That way you are creating an autoreleased url, and request.
Please give a little more information where it says webView is not declared.


text:
Q: Below code is not woking with Chrome browser I have created a reusable function which clicks the check box of a particular row and returns the text of that row.

CheckBoxXpath-> private static final String XPATH_JOBRATECATEGORIES_CHECKBOX_LIST = "//kendo-grid-list//table/tbody/tr/td[1]/label";

RowXpath -> private static final String XPATH_JOBRATECATEGORIES_LIST = "//kendo-grid-list//table/tbody/tr/td[2]//div//div";

count-> 0 (I want to click only first row check box)

public String Select_CheckBox_Return_SelectedText(String CheckBoxXpath,String RowXpath, int Count) {

  List<WebElementFacade> listOfCheckBox = findAll(By.xpath(CheckBoxXpath));
  List<WebElementFacade> listOfrow = findAll(By.xpath(RowXpath));
  if(listOfCheckBox.size()>Count) {
  for (int i = 0; i <= Count; i++) {
   listOfCheckBox.get(i).click();
   String Actual=listOfrow.get(i).getText();

  }
  }else {
   Assert.fail("Need to have more rows to fullfill the requirement");
   return null;
  }

  return Actual;

 }

This is working fine with Firefox browser, but not working with Chrome browser.
On debugging code is throwing exception on -> "listOfCheckBox.get(i).click();"
I am not able to understand why it is behaving so weired.
Need help. Thanks in advance.

A: You need to target the checkboxes, not the labels in your xpath:
//kendo-grid-list//table/tbody/tr/td[1]/input[@type='checkbox']


text:
Q: Lock Screen - Some of these settings are hidden or managed by your organization I have this message on the lock screen screen. I've tried many way to fix it:

*

*I do not have the NoLockScreen key

*Allow Telemetry is at full

*Disabled my antivirus

*tried O&O ShutUp10 software

*I only have 2 settings Enabled under gpedit\Computer Configuration\Administrative Templates\All Settings. These are Allow Telemetry and Require use of specific security layer for remote (RDP) connection

I'm running Windows 10 Education version 1903


text:
Q: Showing that $x_i(k+1)=\frac{1}{a_{ii}}\left(b_i-\displaystyle\sum_{j=1,j \neq i}^{n}a_{ij}x_j(k)\right)$ does converge Consider $n$ agents that collectively solve the linear system $Ax = b$, where matrix $A \in \mathbb{R}^{n \times n}$ is invertible with non-zero diagonal elements, $a_{ii}$, and $b \in \mathbb{R}^{n \times n}$. Each agent stores a variable $x_i(k)$ as the discrete-time variable $k$ changes. At time step $k \in \mathbb{N}$, each agent performs the following:
$$x_i(k+1)=\frac{1}{a_{ii}}\left(b_i-\sum_{j=1,j \neq i}^{n}a_{ij}x_j(k)\right), \qquad i \in \{1,\dots,n\}$$
Each agent $i \in \{1,\dots,n\}$ then sends its value $x_i(k+1)$ to all other agents $j \in \{1,\dots,n\}$ with $a_{ij} \neq 0$, and they iteratively repeat the computation above. The initial values of the agents are arbitrary.
How can the following be shown?

*

*The necessary condition for convergence, i.e., $\lim\limits_{k \to \infty}x(k)=x^*$.

*Assuming the process indeed converges, how can we show that $Ax^*=b$?
For the first part, do I simply need to show that the modulus of $A$'s eigenvalues must be less than $1$?

A: For part $1$, yes.
For part $2$, take limit as $k \to \infty$ on both sides of the equation so that under the limit, $x_{k+1} = x_k = x^*$
That would mean that for $x^*$, we have:
$a_{ii}x^*_i=b_i-\displaystyle\sum_{j=1,j \neq i}^{n}a_{ij}x_j^* $
which when re-arranged is same as $(Ax^*)_i=b_i$ for all $i$


text:
Q: Opayo (Sagepay) Direct VB.net code to handle 3dAuth I have been tasked with updating a VB.net website to handle 3dauth. There used to be a vb.net toolkit apparently with sample code but Opayo support cannot supply it anymore. They suggested 'finding it on the internet' I think it was used to build the site originally.
The code has been working fine up until now without 3dauth but obviously it is now compulsory.
If I turn on 3dauth on the account, after the user enters their card info, it does come back to
 If strStatus = "3DAUTH" Then

                            '** This is a 3D-Secure transaction, so we need to redirect the customer to their bank **
                            '** for authentication.  First get the pertinent information from the response **
                            strVPSTxId = findField("VPSTxId", strResponse)

                            strACSURL = findField("ACSURL", strResponse)
                            strCReq = findField("CReq", strResponse)
                            strPAReq = findField("PAReq", strResponse)
                            strMD = findField("MD", strResponse)

But does nohing with the info. I know I need to update these fields to 3dauthv2 but I'm not sure how to send to bank then get response and send back to opayo.
If Opayo would provide sample code for this it would be a lot easier!
Any help would be appreciated as would a copy of the old VB.net toolkit.
thanks very much
Bob


text:
Q: Shell script to check for the presence of one or more files with a specific extension? I want to write a script to find a file with specific extension.this much i have done:
#!/bin/bash
file="/home/Savio/Dsktop/check/*.csv"
file1="/home/Savio/check/*.txt"
if [[ -f "$file" && -f "$file1" ]];
then
    echo " found."
else
    echo "not found."
fi

Where the check folder contains sub-folders. Please correct me if anything wrong is there

A: If you don't want recursion, you can do
export DIR=/home/Savio/Dsktop/check
if ls ${DIR}/*.txt &>/dev/null && ls ${DIR}/*.csv &>/dev/null
then
    echo "Found."
else
    echo "Not found."
fi

Or, in perl:
perl -e '
    $DIR="/home/Savio/Dsktop/check";
    @a= glob "${DIR}/*.txt";
    @b= glob "${DIR}/*.csv";
    print  @a && @b ? "Found.\n" : "Not found.\n"
'

If you do want recursion, the solution proposed in the other answers will work. You can make it go faster by making find stop after the first match it finds:
export DIR=/home/Savio/Dsktop/check
CSV=$(find "$DIR" -name *.csv|head -n1)
TXT=$(find "$DIR" -name *.txt|head -n1)
[ ! -z "$CSV" ] && [ ! -z "$TXT" ] && echo Found || echo Not found

References

*

*Stephane Chazelas' great answer to How to stop the find command after first match?

A: The wildcard in file1 is never expanded because it's always in quotes.
In bash, one way is to set the nullglob option so that a wildcard that matches no file expands to an empty list.
#!/bin/bash
shopt -s nullglob
csv_files=(/home/Savio/Dsktop/check/*.csv)
txt_files=(/home/Savio/check/*.txt)
if ((${#csv_files[@]} && ${#txt_files[@]}))
then
  echo " found."
else
  echo "not found."
fi

If you want to match dot files as well, set the dotglob option.
With only a POSIX shell, you need to cope with the pattern remaining unchanged if there is no match.
matches_exist () {
  [ $# -gt 1 ] || [ -e "$1" ]
}
if matches_exist /home/Savio/Dsktop/check/*.csv &&
   matches_exist /home/Savio/check/*.txt; then
  echo " found."
else
  echo "not found."
fi

Note that it looks for files regardless of their type (regular, directory, symlink, device, pipe...) while your [[ -f file ]] checks whether the file exists and is a regular file or symlink to regular file only (would exclude directories, devices...).

A: bash script to check whether csv files exists and for loop all of them of exists
#!/bin/bash
# count variable to check if csv files exists in current directory
count_file=`ls -1 *.flac 2>/dev/null | wc -l`
if [ $count_file != 0 ]
then
  for file in *.csv; do
    echo ${file##*/}
  done
fi

A: find would probably work better here.
csv=$(find /home/Savio/Dsktop/check -type f -name "*.csv")
txt=$(find /home/Savio/check/ -type f -name "*.txt")

What you have will not recurse into sub-directories.

A: Be aware that if [[ -f "$file" ]] will fail if $file contains more than one filename -- which is likely to happen when you are selecting the file using a wildcard.
You should either check for a specific filename (without any wildcards) or use Petey T's approach and check if the number of files found by find is greater than 0:
csv=$(find /home/Savio/Dsktop/check -type f -name "*.csv")
txt=$(find /home/Savio/check/ -type f -name "*.txt")
if [[ ( -n $csv ) -a ( -n $txt ) ]]
then
    echo "found"
else
    echo "not found"
fi


text:
Q: Understanding assumptions about machine word size in analyzing computer algorithms I am reading the book Introduction to Algorithms by  Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein.. In the second chapter under "Analyzing Algorithms" it is mentioned that :

We also assume a limit on the size of each word of data. For example , when working with inputs of size n , we typically assume that integers are represented by c lg n bits for some constant c>=1 . We require c>=1 so that each word can hold the value of n , enabling us to index the individual input elements , and we restrict c to be a constant so that the word size doesn't grow arbitrarily .( If the word size could grow arbitrarily , we could store huge amounts of data in one word and operate on it all in constant time - clearly an unrealistic scenario.)

My questions are why this assumption that each integer should be represented by c lg n bits and also how c>=1 being the case allows us to index the individual input elements ?

A: first, by lg they apparently mean log base 2, so lg n is the number of bits in n.
then what they are saying is that if they have an algorithm that takes a list of numbers (i am being more specific in my example to help make it easier to understand) like 1,2,3,...n then they assume that:

*

*a "word" in memory is big enough to hold any of those numbers.

*a "word" in memory is not big enough to hold all the numbers (in one single word, packed in somehow).

*when calculating the number of "steps" in an algorithm, an operation on one "word" takes one step.
the reason they are doing this is to keep the analysis realistic (you can only store numbers up to some size in "native" types; after that you need to switch to arbitrary precision libraries) without choosing a particular example (like 32 bit integers) that might be inappropriate in some cases, or become outdated.

A: You need at least lg n bits to represent integers of size n, so that's a lower bound on the number of bits needed to store inputs of size n.  Setting the constant c >= 1 makes it a lower bound.  If the constant multiplier were less than 1, you wouldn't have enough bits to store n.
This is a simplifying step in the RAM model.  It allows you to treat each individual input value as though it were accessible in a single slot (or "word") of memory, instead of worrying about complications that might arise otherwise.  (Loading, storing, and copying values of different word sizes would take differing amounts of time if we used a model that allowed varying word lengths.)  This is what's meant by "enabling us to index the individual input elements."  Each input element of the problem is assumed to be accessible at a single address, or index (meaning it fits in one word of memory), simplifying the model.

A: This question was asked very long ago and the explanations really helped me, but I feel like there could still be a little more clarification about how the lg n came about. For me talking through things really helps:
Lets choose a random number in base 10, like 27, we need 5 bits to store this. Why? Well because 27 is 11011 in binary. Notice 11011 has 5 digits each 'digit' is what we call a bit hence 5 bits.
Think of each bit as being a slot. For binary, each of those slots can hold a 0 or 1. What's the largest number I can store with 5 bits? Well, the largest number would fill each slot: 11111
11111 = 31 = 2^5 so to store 31 we need 5 bits and 31 is 2^5
Generally (and I will use very explicit names for clarity):
numToStore = 2 ^ numBitsNeeded
Since log is the mathematical inverse of exponent we get:
log(numToStore) = numBitsNeeded
Since this is likely to not result in an integer, we use ceil to round our answer up. So applying our example to find how many bits are needed to store the number 31:
log(31) = 4.954196310386876 = 5 bits


text:
Q: how to disable Cache in a REST Tree in DOJO with a complete code to reproduce it The following code shows a tree in Dojo using dojox.data.JsonRestStore with one node named Changing0 with children to be lazy loaded. the problem is in updating the tree by renaming the one node (Changing1, Changing2,...) without changing its reference number or id.
The question is the following: if it is a caching problem, how to disable caching.
Please note that on the log file we can see that the REST is functioning well but the name is unchanged on the tree. Even if we use refresh2() instead of refresh1() by deleting the whole tree and its data and recreating it. Maybe it is the $ref that is kept in javascript referencing since we do not change the id.
the code is the following:
reproducing_problem.php:
<?php
if(!isset($_SESSION))
    {
        session_start();
    }
$_SESSION['keyA']=0;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<title>Reproducing Cache Problem</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

       Change name and refresh

notes

reproducing-REST.php:
<?php
if(!isset($_SESSION))
{
    session_start();
}
$keyA=$_SESSION['keyA'];
$_SESSION['keyA']=$keyA+1;
if (array_key_exists('PATH_INFO', $_SERVER)) {
    $arr = null;
    $resource = $_SERVER['PATH_INFO'];
    $method = $_SERVER['REQUEST_METHOD'];
    error_log("  resource: ".$resource." \n",3,"mylogfile.txt");
    if ($method == 'GET') {
        if ($resource=='/'){
            $arr=array();
            $sameref='1234';
            $name="Changing".$keyA;
            error_log("  name: ".$name." \n",3,"mylogfile.txt");
            array_push($arr,array('$ref' => $sameref, 'name' => $name, 'children' => true));
        }
        else{
            $aProduct = ltrim($resource, '/');
            $arr=array();
            $name="exploding";
            $child='2345';
            array_push($arr,array('name' => $name,'idq' => $child));
            $arr=array('idp' => $aProduct, 'name' => $name, 'children' => $arr);
        }
        $status = 'HTTP/1.1 200 OK';
    }
    header($status);
    echo json_encode($arr);
}
?>

thank you


text:
Q: Any free Tools to display more than 5000 geography objects in SQL Server? SQL Server 2008 and up allow you to create a spatial index. If you select records that include a geography or geometry object, a spatial data tab appears that can display up to 5000 points or lines or other shapes. You can select a label column, pan, and zoom. I am trying to debug a road network dataset that has disconnected islands of roads and need to be able to display all the line segments for a given state and label the disconnected ones so I can see where the missing roads are. That means I need to display more than 5000 objects.
Are there any free tools that can do this, including the labeling (color labels would be ok if text labels are not supported)? I have about 250,000 line segments, but anything that can display 50,000 would be okay for my work. A plugin for SSMS would be best, but an external tool would work, too. If there is a C# .NET library, I could use that, too.

A: You might try SharpGIS SqlSpatial Query Tool.

A: QGIS will read SQL Server spatial data - you should be able to connect to your database, see your tables, and add them to the map canvas and zoom down however you like.
Your database interaction will be limited to what you can do in the layer properties dialogue box.


text:
Q: NoneType() > NoneType() error while dealing with Binary tree When i try to compile it gives me this error, i think its because of the max function i used, can someone help me to resolve this?
                                                                                class BinaryTree:
    def init(self):
        self.root = None
        self.size = 0
# Return True if the element is in the tree
def search(self, e):
    current = self.root # Start from the root

    while current != None:
        if e < current.element:
            current = current.left
        elif e > current.element:
            current = current.right
        else: # element matches current.element
            return True # Element is found

    return False

# Insert element e into the binary search tree
# Return True if the element is inserted successfully
def insert(self, e):
    if self.root == None:
      self.root = self.createNewNode(e) # Create a new root
    else:
      # Locate the parent node
      parent = None
      current = self.root
      while current != None:
        if e < current.element:
          parent = current
          current = current.left
        elif e > current.element:
          parent = current
          current = current.right
        else:
          return False # Duplicate node not inserted

      # Create the new node and attach it to the parent node
      if e < parent.element:
        parent.left = self.createNewNode(e)
      else:
        parent.right = self.createNewNode(e)

    self.size += 1 # Increase tree size
    return True # Element inserted

# Create a new TreeNode for element e
def createNewNode(self, e):
  return TreeNode(e)

def leaf(self):
    self.leafHelper(self.root)

def leafHelper(self,r):
    if r == None:
        return r
    else:
        self.leafHelper(r.left)
        if(r.left == None and r.right == None):
            print(r.element, end = " ")
        self.leafHelper(r.right)

def nonleaf(self):
    self.nonleafHelper(self.root)

def nonleafHelper(self,r):
    if r == None:
        return r
    else:
        self.nonleafHelper(r.left)
        if(r.left != None or r.right != None):
            print(r.element, end = " ")
        self.nonleafHelper(r.right)

def getHeight(self):
    self.height(self.root)

def height(self,r):
    if r == None:
        return r
    else:
        return 1 + max(self.height(r.left),self.height(r.right))

"""
# Return the size of the tree
def getSize(self):
  return self.size"""

# Inorder traversal from the root
def inorder(self):
  self.inorderHelper(self.root)

# Inorder traversal from a subtree
def inorderHelper(self, r):
  if r != None:
    self.inorderHelper(r.left)
    print(r.element, end = " ")
    self.inorderHelper(r.right)

# Postorder traversal from the root
def postorder(self):
  self.postorderHelper(self.root)

# Postorder traversal from a subtree
def postorderHelper(self, root):
  if root != None:
    self.postorderHelper(root.left)
    self.postorderHelper(root.right)
    print(root.element, end = " ")

# Preorder traversal from the root
def preorder(self):
  self.preorderHelper(self.root)

# Preorder traversal from a subtree
def preorderHelper(self, root):
  if root != None:
    print(root.element, end = " ")
    self.preorderHelper(root.left)
    self.preorderHelper(root.right)

# Return true if the tree is empty
def isEmpty(self):
  return self.size == 0

# Remove all elements from the tree
def clear(self):
  self.root == None
  self.size == 0

# Return the root of the tree
def getRoot(self):
  return self.root

class TreeNode:
def __init__(self, e):
  self.element = e
  self.left = None # Point to the left node, default None
  self.right = None # Point to the right node, default None

####################### Main test binary tree

def main(size = 7):
tree = BinaryTree()
tree.insert("George")
tree.insert("Michael")
tree.insert("Tom")
tree.insert("Adam")
tree.insert("Jones")
tree.insert("Peter")
tree.insert("Daniel")

# Traverse tree
print("Inorder (sorted): ", end = "")
tree.inorder()
print("\nPostorder: ", end = "")
tree.postorder()
print("\nPreorder: ", end = "")
tree.preorder()
print("\nLeaf: ", end = "")
tree.leaf()
print("\nNonleaf: ", end = "")
tree.nonleaf()
tree.getHeight()

numbers =[49, 76, 67, 29, 75, 18, 4, 83, 87, 40]
print ("\n\nInserting the following values:")
for i in numbers:
    print(i, end=" ")
print()
intTree = BinaryTree()
for e in numbers:
  intTree.insert(e)
print("\nPreorder traversal:")
intTree.preorder()
print("\n\nInorder traversal:")
intTree.inorder()
print("\n\nPostorder traversal:")
intTree.postorder()
print("\nLeaf: ", end = "")
intTree.leaf()
print("\nNonleaf: ", end = "")
intTree.nonleaf()

if name == "main":
    main()

A: Change your height() function as follows -
def height(self,r):
    if not r:
        return 0
    else:
        return 1 + max(self.height(r.left),self.height(r.right))

You can not add a NoneType to an Integer.


text:
Q: Removing an dynamically and previously added event listener on button click In C#  I have executed JavaScript by ExecuteScript() function. In JavaScript I have added an EventListener to webpage by clicking an button say 'Attach'. Now I want to remove that EventListener on another button click say 'Detach'.
Now under 'Attach' button Form.
I have written following:
document.addEventListener('click', hilightElement, false);

where highlightElement is my function.
Under 'Detach' button Form.
I have written following
document.removeEventListener('click', hilightElement);

here document.removeEventListener does not work i.e the EventListener which i added still exist.
Is  there any way that I can remove the event listener so that 'click' event does not do anything after 'Detach' button click.

A: Try Rayons example, since I realized I was writing the same code.

A: I tried your code as below, and it works as expected:

var attach = document.getElementById('attach');
var detach = document.getElementById('detach');
var hilightElement = function() {
  alert("Here");
};
attach.addEventListener('click', function(e) {
  e.stopPropagation();
  document.addEventListener('click', hilightElement, false);
});
detach.addEventListener('click', function() {
  document.removeEventListener('click', hilightElement);
});
<button type="button" id="attach">Attach</button>
<button type="button" id="detach">Detach</button>


text:
Q: How to make ansible interpolate the variables or facts in the return section of the ternary filter? How to make use of variables or  facts in the return section of ternary filter?
eg: set_facts:
var1="{{ (true) | ternary('ansible_os_family','ansible_os_family'|upper) }}"

A: kindly discard this. Return section seem to consider any variales when passw


text:
Q: register a swift thread as pj_thread I'm currently working on an iOS app using pjSIP and swift.
I got a method on in a .c-file for making a call, let it be
void makeCall(const char *destUri){
    ...
    status = pjsua_call_make_call(...
}

and I got a swift method that is called from the main thread which is calling the makeCall-function from the C-file.
If I do so, the app crashes and by saying that I need to register the thread to pjSIP before calling anymore pjLib functions.
To register a thread to pjSIP I need to call the function pj_thread_register
I tried to add the thread as UnsafeMutablePointer.
my calls look like this right now:
void makeCall(const char *destUri, long threadDesc, pj_thread_t **thread){
    ...
    pj_thread_register(NULL, &threadDesc, thread);
    status = pjsua_call_make_call(...
}

internal static func makeSIPCall(numberToCall: String){
    ...
    let destination = ... //my call destination
    let thread : NSThread = NSThread.currentThread()
    let observer = UnsafeMutablePointer<CopaquePointer>(Unmanaged.passUnretained(thread.self).toOpue())

    makeCall(destination, Int(thread.description)! as Clong, observer)

}

Thread 1: EXC_Breakpoint and the fatal error "found nil while unwrapping an Optional value"
So how can I pass the needed properties of the thread from swift to C?

A: Try not to send an reference from swift but use this directly within your
.c-file:
void makeCall(const char *destUri, long threadDesc, pj_thread_t **thread){
    ...
    pj_thread_desc a_thread_desc;
    pj_thread_t *a_thread;

    if (!pj_thread_is_registered()) {
        pj_thread_register(NULL, a_thread_desc, &a_thread);
    }
    status = pjsua_call_make_call(...
}

Source: ipjsua (demo project you get after building pjSIP)

A: It seems to be possible to write the same function as mentioned in the accepted answer in Swift.
func registerThread() {
   if pj_thread_is_registered() == 0 {
     var thread: OpaquePointer?
     var threadDesc = Array(repeating: 0, count: Int(PJ_THREAD_DESC_SIZE))
     pj_thread_register(nil, &codecInfos[0], &thread)
   }
}

threadDesc and thread  will be filled after pj_thread_register returns.
This behaviour was not obvious to me as no information about the thread is explicitly passed to pj_thread_register. Yet I can call this function from any GCD dispatch queue and this conditionally registers the threads used.


text:
Q: PHP Good search engine for checkout items I am making a checkout/cashier software as hobby project, at the moment I am trying to come up with some way to search items in the database.
I got a database from my part-time job which contains about 50,000 items of computer related parts and I want to be able to search through them using keywords or EAN code.
If I enter this it shows the item

If I enter this it doesn't show the item

Am I doing something wrong in my MySQL Query?
This is how I come up with these results:
SELECT *
FROM items
WHERE EAN LIKE '%" . addslashes($_GET['sTerm']) . "%'
OR itemName LIKE '%" . addslashes($_GET['sTerm']) . "%'
OR factoryId LIKE '%" . addslashes($_GET['sTerm']) . "%'
OR itemId LIKE '%" . addslashes($_GET['sTerm']) . "%';

Where addslashes($_GET['sTerm']) stands for the search bar contents so in this case AAA or from the second image AAA Varta


text:
Q: Type error: Cannot read property 'configure' of undefined I have the following error:
Cannot read property 'configure' of undefined.
How can I make my unit test work.
this is my unit test so far :
import React from 'react';
import { Enzyme, mount } from 'enzyme'
import layout from './layout';
import Adapter from 'enzyme-adapter-react-15';

//Unit Test  V
Enzyme.configure({ adapter: new Adapter() });

describe ('layout />', () => {
it( 'should be defined ', () => {
  expect(layout).toBeDefined()
 })

it( 'should render ', () => {
    const wrapper = mount(<layout />)
    expect(wrapper).toMatchSnapshot()
})

it( 'should render class name', () => {
    const wrapper = mount
    (<div className = "empty-layout"/>)
    expect(wrapper).toMatchSnapshot()
})

});
I expect the test to pass. Any ideas/hints or improvements that I could implement on my unit test.

A: The configure step is always done globally in a file called setupTests.js which is usually at the root of your project:
setupTests.js:
import {configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({adapter: new Adapter()});

see here: https://facebook.github.io/create-react-app/docs/running-tests#src-setuptestsjs
So create a file setupTests.js in the root folder of your project with the provided content above and remove the line Enzyme.configure({ adapter: new Adapter() }); from your test and see if it works.


text:
Q: How to fix 'Cannot set property 'props' of undefined' error When I'm pressing button '&#60' or '&#62' (increase or decrease difficulty level) I get error "Uncaught TypeError: Cannot set property 'props' of undefined" at PureComponent (react.development.js:444)
How can I fix it?
The code above is much less then actual code, however even in this size it not works well.
Even 'blah-blah' do not appears in console.
StartMenu.js
import React from 'react';
import { connect } from 'react-redux';

import increaseDifficultyLevelfunction from './increaseDifficulyLevel';
import decreaseDifficultyLevelfunction from './decreaseDifficulyLevel';

function StartMenu(props) {
  return (

      <button
        type="button"
        id="leveldown"
        onClick={decreaseDifficultyLevelfunction}
      >
      <
      </button>

{props.difficultyLevel}

      <button
        type="button"
        id="levelup"
        onClick={increaseDifficultyLevelfunction}
      >
        >
      </button>

      <button
        type="button"
        id="startButton"
        onClick={props.restartGame}
      >
        start the game
      </button>

  );
}

const mapStateToProps = state => ({
  difficultyLevel: state.difficultyLevel,
});

const mapDispatchToProps = dispatch => ({
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(StartMenu);

decreaseDifficultyLevel.js
import { connect } from 'react-redux';
import { decreaseDifficultyLevel } from '../../actions/actionCeator';

function decreaseDifficultyLevelfunction(props) {
  console.log('blah-blah');
  props.decreaseDifficultyLevel();
}

const mapStateToProps = state => ({
  difficultyLevel: state.difficultyLevel,
});

const mapDispatchToProps = dispatch => ({
  decreaseDifficultyLevel: () => { dispatch(decreaseDifficultyLevel()); },
});

export default connect(
  mapStateToProps,
  mapDispatchToProps,
)(decreaseDifficultyLevelfunction);

A: I was digging into the details here and decided to try it in a codesandbox.
The common React component (till hooks) cases, is made of a class component. In these cases, functions/actions are bind at the top level and retain their context in sub components (so we can use them). In function components, things are bit different. In order to get the actions to work you need to do the following:

*

*link your actions to redux, using mapDispatchToProps as usual.

   Import * as actions from './actions';

   const mapDispatchToProps = dispatch => {
      return {
        actions: bindActionCreators(levelActions, dispatch)
      };
   };

*bind your actions so they can retain their context.

In order to make step 2, you need to declare the functions within the functional component (usually known as class variables) and then use them in the buttons onClick attribute. Like so:
   const {
     increaseDifficultyLevelFunction,
     decreaseDifficultyLevelFunction
   } = props.actions;

   const increaseLevel = () => increaseDifficultyLevelFunction();
   const decreaseLevel = () => decreaseDifficultyLevelFunction();

Check this reference, it covered your case with examples.


text:
Q: Does $(\sqrt{p}+\sqrt{q})^{11}+(\sqrt{p}-\sqrt{q})^{11}= (\sqrt{r}+\sqrt{s})^{11}+(\sqrt{r}-\sqrt{s})^{11}$ have non-trivial rational solutions? It has been conjectured by Euler, Ekl, etc, that
$$x_1^k+x_2^k=x_3^k+x_4^k$$
has no solution for $k>4$ if the $x_i$ are algebraic numbers of deg $1$.
However, if these are deg $2$, then there are solutions when $k>4$. A parametrization by Desboves is if $a^2+b^2=c^2$, then,
$$(a\sqrt2+b)^5+(-b+c\sqrt{-2})^5=(a\sqrt2-b)^5+(b+c\sqrt{-2})^5$$
Update: There is even for $k=11$,
$$(1+\sqrt{-7})^{11}+(1-\sqrt{-7})^{11}=(1+\sqrt{-11})^{11}+(1-\sqrt{-11})^{11}$$ which answers the title of the post, but leaves the question of how high $k$ can get.

Q: But if we now consider the $x_i$ to be algebraic numbers of deg $4$ of form,
  $$(\sqrt{p}+\sqrt{q})^k+(\sqrt{p}-\sqrt{q})^k= (\sqrt{r}+\sqrt{s})^k+(\sqrt{r}-\sqrt{s})^k\tag1$$
  where $p,q,r,s$ are integers, does it have non-trivial solutions for $\color{blue}{k>11}$?

It has parametric ones for $k\leq10$. (See this answer for $k\leq6$.) Also,

For $k=7,9:$
$$ (\sqrt{a+c}+\sqrt{a+2b-c})^k+(\sqrt{a+c}-\sqrt{a+2b-c})^k = \\(\sqrt{a+c}+\sqrt{a-2b-c})^k+(\sqrt{a+c}-\sqrt{a-2b-c})^k$$
$$\begin{aligned}
&\text{If}\;k=7,\; \text{then}\; 4a^2+b^2=c^2.\\
&\text{If}\;k=9,\; \text{then}\; 6 a(a^2 + 5 b^2) + 2 b^2 c - 3 a c^2 = 0.
\end{aligned}$$

For $k=8,10:$
$$ (\sqrt{2a+c}+\sqrt{-2a+c})^k + (\sqrt{2a+c}-\sqrt{-2a+c})^k = \\(\sqrt{2b+c}+\sqrt{-2b+c})^k + (\sqrt{2b+c}-\sqrt{-2b+c})^k$$
$$\begin{aligned}
&\text{If}\;k=8,\; \text{then}\; a^2+b^2=2c^2.\\
&\text{If}\;k=10,\; \text{then}\; a^2+b^2=c^2.
\end{aligned}$$
which are just quadratics in $c$ and easily solvable. But extending these for $k=11,12$, respectively, yield quartics in $c$ and are harder. (And these special cases seem to always involve a negative integer under the square root.)
P.S. A different parameterization for $k=8$ involves, of all things, the minpoly of the golden ratio $\phi$ and the plastic constant $P$.

Q: In summary, does $(1)$ have non-trivial solutions for $k>11$ as well?

(I have done a computer search, but my search radius may have been too small.)


text:
Q: Change Settings of a PDF document with PDFSharp What I want to do is to send a PDF Document to a user and restrict him to do anything other than to scroll and zoom within the document. Especially the print option should be disabled. I tried it with the following VB.NET Code, creating a new PDF file:
Imports PdfSharp.Drawing
Dim document As New PdfSharp.Pdf.PdfDocument

    document.Info.Title = "Built with PDFSharp"
    document.Info.CreationDate = Now
    document.Info.Subject = "PDFSharp Test"

    Dim page As PdfSharp.Pdf.PdfPage = document.AddPage

    Dim gfx As XGraphics = XGraphics.FromPdfPage(page)
    Dim font As PdfSharp.Drawing.XFont = New PdfSharp.Drawing.XFont("Verdana", 20, PdfSharp.Drawing.XFontStyle.Bold)
    gfx.DrawString("Hello, World!", font, XBrushes.Black, New XRect(0, 0, page.Width, page.Height), XStringFormats.Center)

    document.SecuritySettings.PermitFullQualityPrint = False
    document.SecuritySettings.PermitPrint = False
    document.SecuritySettings.PermitAccessibilityExtractContent = False
    document.SecuritySettings.PermitAnnotations = False
    document.SecuritySettings.PermitAssembleDocument = False
    document.SecuritySettings.PermitExtractContent = False
    document.SecuritySettings.PermitFormsFill = False
    document.SecuritySettings.PermitModifyDocument = False

    ' Save the file
    Dim filename As String = "HelloWorld.pdf"
    document.Save(filename)

But when the PDF document is opened, there still is the possibility to print and to do other things, like it is in normal PDF documents. Am I missunderstanding the securitySettings? I view the PDF document with adobe acrobot. Any help is appreciated.

A: You don't set an owner password, therefore anybody can do anything without password.
Set an owner password and Adobe Reader should prevent printing etc.
See also:
http://pdfsharp.net/wiki/ProtectDocument-sample.ashx
Do not set a user password if you want people to be able to view the document without entering a password.

A: I know this is a little bit late, but this helped me regarding this problem:
If you set an owner password, but no user password, then everybody can open the document using Adobe Reader without entering a password.
But a password is needed to make changes in Adobe Acrobat.
Watch it, but don't modify it.
ref. http://forum.pdfsharp.de/viewtopic.php?f=2&t=1777


text:
Q: Filter a list of strings using math I have a directory with files listed like so:
abc201303130110.txt
abc201303140511.txt
abc201303150112.txt

As you can see, the filename contains a datetime stamp. I want to return all files with the value 201303140000 or higher in the filename.
I can get use grep to grab the datetime portion of the filename, but I don't know how to pipe through a filter that can do something like X > 201303140000.

A: If your awk is the GNU awk, you can simply use:
find . -type f | awk '{ match($0, /2013[0-9]+/,arr)}  arr[0] >= 201303140000 '

A: Perl to the rescue! Perl's -n switch works a bit like sed -n and perl is more powerful in its matching and arithmetic.
dennis@lightning:/tmp/foo$ ls -1
abc201303130110.txt
abc201303140511.txt
abc201303150112.txt
dennis@lightning:/tmp/foo$ ls | perl -ne '$d=$_; $d =~ s/.*?(\d+).*/\1/s; print if $d >= 201303140000'
abc201303140511.txt
abc201303150112.txt

A: With zsh:
print -rl abc<201303140000->.txt


text:
Q: From Windows Phone 7.1 to Windows Phone 8.0 I just copied .cs code to new Windows Phone 8.0 app. There is no error code or something.
All the images on the application I did set in .cs  not in .xaml.
When I debugg the profject there are no images.  Whole images are in construcor. And all are in Canvas. E.G
       Image bankImage = new Image()
                {
                    Source = new BitmapImage(new Uri("/PhoneApp2;component/images/Menu/cash.png", UriKind.Relative)),
                    Height = 80,
                    Width = 250
                };
 Canvas.SetTop(bankImage, 140);
            Canvas.SetLeft(bankImage, 170);
MyCanvas.Children.Add(bankImage);

What is the reason that my app has no images on WP8 and on WP7 there is?

A: Solved
Image property Build Action has to be "Content". If there is contect I had to get source like
ImageSource = (ImageSource)new BitmapImage(new Uri("/images/AmericanPoker/Bottom.png", UriKind.Relative))

No need to use App;component

A: Don't copy .cs files to new WP8 project.
Just open old WP7 project in newer version of Visual Studio (2012 or 2013) - and it will become WP8 project.


text:
Q: Strange chopping / stretching of text in Chrome when animating `left` with CSS I'm seeing a very strange effect in Google Chrome when I animate the position of an element that contains text.
Without animation, part of the text is hidden by the boundaries of it's parent element. When I animate the left property using @keyframes, part of it gets duplicated repeatedly or stretched. This doesn't seem to happen with Firefox and it doesn't seem to happen with different content such as a CSS pattern.
I can't imagine that I'm the first person to discover this. Is this a known issue? Is there a bug report somewhere that I can read?
Example:

Demo:

html, body {
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.container {
  width: 10em;
  overflow: hidden;
  margin: 1em;
}

.text {
  white-space: nowrap;
  position: relative;
  animation-name: marquee;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes marquee {
  from { left: 0; }
  to   { left: -100%; }
}

Now is the time for all good men to come to the aid of their party.

A: A similar issue had occurred to me too. The problem is webkit related.
To resolve this include
body{
       -webkit-backface-visibility: hidden;
     }

Use this same code if you run into abnormal animation issues that persist on Chrome.


text:
Q: Comparing two columns and extracting the entire row data in excel The names from a column in sheet1 has to be compared with names from a column in sheet2, and the if a name matches, the entire row data of that particular name from sheet2 has to be displayed in sheet1 without overriding the existing data in sheet1.

A: I would use the Power Query Add-In for this.  A Query can start from an existing Excel table.
I would start one Query based on sheet2.  I would Merge the data from sheet1 on the name column, and select the Only include matching rows check box.
Then I would start a 2nd Query based on sheet1, and Append the results of the 1st Query. I would deliver the results to a new Excel Table.
http://office.microsoft.com/en-au/excel-help/combine-multiple-queries-HA103993872.aspx


text:
Q: Measure Java execution time (Real, User, System) like linux command I have a massive parallel Java-Application and want to measure its execution time the very same way that linux' time command does it (Real, User, System).
I'm especially interested in the time the application spends in kernel-tasks, i.e. shows suboptimal behavior (the higher the ratio of system/(system+user), the worse the performance).
In bash, there is time, for C++ there are boost/std chrono .. Is there anything for Java?
I found OperatingSystemMXBean, but it seems this is a dead end for measuring time in kernel-tasks.


text:
Q: Where is the virtual function table for C++ class stored? I tried to find where exactly virtual function table gets stored for c++ class.
i found some answers like its a "static array of function pointers"
so will it get stored in data segment read only memory? (initialised one)

A: Most probably yes. However, it's not mandated. It's not even mandated that polymorphism is implemented via virtual function table, but on most platforms it is. These are implementation details, as long as a compiler obeys the behavior set by the standard, it can do whatever it wants.
A vftable is one per class and stored in only one place in memory.

A: When you make any function virtual, the compiler will insert a vptr inside your class. As a result, the size of the class will grow by 4 bytes (on Win32).This pointer holds the address of the virtual table (vtable). vtable is constructed by the compiler at compile time and is basically nothing but an array of function pointers. The function pointers are actually pointers to the virtual functions of that particular class. To be more exact, the virtual table is a static array of function pointers, so that different instances of the same class can share that vtable. Since, static members are stored in the data section (.data), the vtable is also stored in the data section of the executable.

A: It's implementation dependent, yes.
And for g++ (4.9.0), virtual table (not the pointer) is stored in the section .rodata of ELF file and its corresponding segment LOAD in memory.


text:
Q: simple prediction using Pearson correlation and linear regression with python i have a data set like this
    Value   Month       Year

    103.4   April       2006
    270.6   August      2006
    51.9    December    2006
    156.9   February    2006
    126.9   January     2006
    96.8    July        2006
    183.1   June        2006
    266.6   March       2006
    193.1   May         2006
    524.7   November    2006
    619.9   October     2006
    129     September   2006
    374.1   April       2007
    260.5   August      2007
    119.6   December    2007
    9.9     February    2007
    91.1    January     2007
    106.6   July        2007
    79.9    June        2007
    60.5    March       2007
    432.4   May         2007
    128.8   November    2007
    292.1   October     2007
    129.3   September   2007

value is the annual rainfall for one district. lets call it districtA. i have the data set from 2006 to 2014 and i need to predict rainfall for next 2 years for districtA. i choose pearson correlation and linear regression from sklearn libary to predict the data. I'm very confused and I don't know how to set X and Y. 'm new to Python so every help is valuable.Thank you
ps..
i found a code like this
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model

# Load the diabetes dataset
diabetes = datasets.load_diabetes()

# Use only one feature
diabetes_X = diabetes.data[:, np.newaxis, 2]

# Split the data into training/testing sets
diabetes_X_train = diabetes_X[:-20]
diabetes_X_test = diabetes_X[-20:]

# Split the targets into training/testing sets
diabetes_y_train = diabetes.target[:-20]
diabetes_y_test = diabetes.target[-20:]

# Create linear regression object
regr = linear_model.LinearRegression()

# Train the model using the training sets
regr.fit(diabetes_X_train, diabetes_y_train)

# The coefficients
print('Coefficients: \n', regr.coef_)
# The mean square error
print("Residual sum of squares: %.2f"
      % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2))
# Explained variance score: 1 is perfect prediction
print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test))

# Plot outputs
plt.scatter(diabetes_X_test, diabetes_y_test,  color='black')
plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue',
         linewidth=3)

plt.xticks(())
plt.yticks(())

plt.show()

when i print the diabetes_X_train it gives me this
[[ 0.07786339]
 [-0.03961813]
 [ 0.01103904]
 [-0.04069594]
 [-0.03422907]...]

i assuming this is the r value getting from correlation and coefficient.
when i print the diabetes_Y_train it gives me something like this
[ 233.   91.  111.  152.  120.  .....]

my problem is how can i get r value from the rainfall and assign it to x axis

A: There is not the best solution, but it works.
Little explanation: I have substituted month on their indexes in the list, it is necessary for algorithm.
Also I have substituted spaces delimeters on ';' delimeters, because in different rows was different number of spaces and it was not convinient. Now your data is:
Value;Month;Year
103.4;April;2006
270.6;August;2006
51.9;December;2006

And file with initial data is 'data.csv'.
import pandas as pd
import sklearn.linear_model as ll

data = pd.read_csv('data.csv', sep=';')
X = data.ix[:,1:3]
y = data.ix[:,0]

month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

for i, m in enumerate(data.ix[:,1]):
    data.ix[i,1] = month.index(m)

X = data.ix[:,1:3]
lr = ll.LinearRegression()
lr.fit(X, y)

######### TEST DATA ##########
X_test = [[1, 2008], [2, 2008]]
X_test = pd.DataFrame(X_test, columns=['Month', 'Year'])

y_test = lr.predict(X_test)
print(y_test)

As a result of test I got this values
[69.23079837  80.63691725]


text:
Q: Spreading elements with no duplicates in Javascript I am looking for the way to remove duplicates. I found a common way is to create a Set and then spread into a new Array.
How could I Set to acomplish this purpose? For instance, I have the following code:
const tmp1=[];
const tmp2=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp = [...new Set([...tmp1],[...tmp2])]; //This should remove duplicates, but gets empty array
const x = [...tmp1, ...tmp2]; // This would keep duplicates

The issue is that because tmp1 is an empty array, then I am getting empty result. However, if I do the following, then getting correct result:
const tmp = [...new Set(...tmp1,[...tmp2])];

I think something is missing in here.
This is an example of duplicated entries where Set is working like a charm just keeping one record:
const tmp1=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp2=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp = [...new Set([...tmp1],[...tmp2])];

This was the original idea, but how about if one of the lists is empty. Then, I am getting an empty array if this occurs.
Thank you

A: Set should take 1 argument but it's taking 2, merge them into one:
const tmp = [...new Set([...tmp1, ...tmp2])];

Note: that this method won't remove duplicates because you are passing an object to the set and not a reference for it, in this case, you can do this instead:
const tmp1 = [];
const tmp2 = [{
  guid: "e695d848-7188-4741-9c95-44bec634940f",
  name: "Spreading.pdf",
  code: "G1"
},
{
  guid: "e695d848-7188-4741-9c95-44bec634940f",
  name: "Spreading.pdf",
  code: "G1"
}
];

// pass a special unique key that differs object from each other to item, in this case i passed guid
const tmp = [...new Map([...tmp1, ...tmp2].map(item => [item['guid'], item])).values()]

A: Just to explain why this example in the question seemingly work:
const tmp1=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp2=[{
    guid:"e695d848-7188-4741-9c95-44bec634940f",
    name: "Spreading.pdf",
    code: "G1"
  }];
const tmp = [...new Set([...tmp1],[...tmp2])];

It results in one object because Set() only take one iterable object, so it takes the first one.
If const tmp2=[1, 2, 3] in the above example, tmp will still result in the one object in tmp1.
More about Set()


text:
Q: How can I store multiple values in a Perl hash table? Up until recently, I've been storing multiple values into different hashes with the same keys as follows:
%boss = (
    "Allan"  => "George",
    "Bob"    => "George",
    "George" => "lisa" );

%status = (
    "Allan"  => "Contractor",
    "Bob"    => "Part-time",
    "George" => "Full-time" );

and then I can reference $boss("Bob") and $status("Bob") but this gets unwieldy if there's a lot of properties each key can have and I have to worry about keeping the hashes in sync.
Is there a better way for storing multiple values in a hash?  I could store the values as
        "Bob" => "George:Part-time"

and then disassemble the strings with split, but there must be a more elegant way.

A: Hashes can contain other hashes or arrays. If you want to refer to your properties by name, store them as a hash per key, otherwise store them as an array per key.
There is a reference for the syntax.

A: This is the standard way, as per perldoc perldsc.
~> more test.pl
%chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
           "Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );

print $chums{"Allan"}{"Boss"}."\n";
print $chums{"Bob"}{"Boss"}."\n";
print $chums{"Bob"}{"Status"}."\n";
$chums{"Bob"}{"Wife"} = "Pam";
print $chums{"Bob"}{"Wife"}."\n";

~> perl test.pl
George
Peter
Part-time
Pam

A: Hashes of hashes is what you're explicitly asking for. There is a tutorial style piece of documentation part of the Perl documentation which covers this: Data Structure Cookbook But maybe you should consider going object-oriented. This is sort of the stereotypical example for object oriented programming tutorials.
How about something like this:
#!/usr/bin/perl
package Employee;
use Moose;
has 'name' => ( is => 'rw', isa => 'Str' );

# should really use a Status class
has 'status' => ( is => 'rw', isa => 'Str' );

has 'superior' => (
  is      => 'rw',
  isa     => 'Employee',
  default => undef,
);

###############
package main;
use strict;
use warnings;

my %employees; # maybe use a class for this, too

$employees{George} = Employee->new(
  name   => 'George',
  status => 'Boss',
);

$employees{Allan} = Employee->new(
  name     => 'Allan',
  status   => 'Contractor',
  superior => $employees{George},
);

print $employees{Allan}->superior->name, "\n";

A: my %employees = (
    "Allan" => { "Boss" => "George", "Status" => "Contractor" },
);

print $employees{"Allan"}{"Boss"}, "\n";

A: %chums = ( "Allan" => {"Boss" => "George", "Status" => "Contractor"},
           "Bob" => {"Boss" => "Peter", "Status" => "Part-time"} );
works great but is there a faster way to enter the data?
I am thinking of something like
%chums = (qw, x)( Allan Boss George Status Contractor Bob Boss Peter Status Part-time)
where x = the number of secondary keys after the primary key, in this case x = 2, "Boss" and "Status"


text:
Q: Organize Stylesheets in Visual Studio 2013 with Region (Collapse and Expand ) Is there any extension for VS2013 to make it possible to organize CSS files and collapse and expand some sections of .css files?

A: You can change the shortcuts under Tools/Options/Environment/Keyboard. Here is a description: https://msdn.microsoft.com/en-us/library/5zwses53.aspx?f=255&MSPPError=-2147217396#Anchor_1

A: Ctrl+M, Ctrl+L (press in order) will toggle the sections

A: This worked for me (visual studio 2010):

*

*Select lines you want to collapse

*Press Ctrl+M and Ctrl+H (in order)

https://msdn.microsoft.com/library/td6a5x4s%28v=vs.100%29.aspx


text:
Q: Why this Model Binding not working in Razor Page I am using ASP.NET Core 3.1 with a simple example to test model binding to post a form. The property to be bound is an object named "Student". Bud the model binding is not working with post method. I will appreciate any help to point out what's wrong here.
Here are the code of my test programs:
'Student Class':
namespace ModelBindPost.Models
{
    public class Student
    {
        public int Id;
        public string FirstName;
        public string LastName;

    }
}

'Edit.cshtml.cs'
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using ModelBindPost.Models;

namespace ModelBindPost.Pages
{
public class EditModel : PageModel
{
[BindProperty(SupportsGet = true)]
public Student Student { get; set; }
    public EditModel()
    {
        Student = new Student();
    }

    public IActionResult OnGet()
    {
        Student.Id = 1;
        Student.FirstName = "Jean";
        Student.LastName = "Smith";
        return Page();
    }
    public IActionResult OnPost()
    {
        string name = this.Student.FirstName;
        return Page();
    }

}

}
' Edit.cshtml':
@page
@model ModelBindPost.Pages.EditModel
@{
}

Model Binding Test

<form method="post">

    <lable asp-for="Student.Id"></lable>
    <input asp-for="Student.Id" class="form-control" />

    <lable asp-for="Student.FirstName"></lable>
    <input asp-for="Student.FirstName" class="form-control" />

    <lable asp-for="Student.LastName"></lable>
    <input asp-for="Student.LastName" class="form-control" />

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

A: A simple public field cannot work for model binding. You need add getter and setter to create property like below:
public class Student
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

}


text:
Q: Potential outside long rectangular conductor So I have a long conductor with a rectangular cross section (sides a and 2a). All sides have zero potential and one of the small ones has a constant potential $V_{0}$. Finding the potential inside is easy you just use separation of variables. But I have two problems:
1)How do i find the potential outside or to phrase it better my only thought was approximating the conductor as a long line and I can find it's charge distribution from my inside solution, but is there a way to find it without approximating ?
2)I find that the corners are a major problem in finding the outside solution as there is a discontinuity in the potential. Is that a true concern or am I completely wrong ?


text:
Q: Bind int to checkbox In my web site I have a bunch of checkboxes but unfortunately, ASP evaluates true as 1. The database I'm working with requires true to evaluate to -1.
How can I convert checkbox.checked to -1 and bind that? So far in my aspx source code I have:
asp:Checkbox ID="AFCanInstCheckbox" runat="server" OnCheckedChanged="CheckboxValue"

I realize that I need some sort of code behind that evaluates checkbox.checked to either 0/-1 and binds that int value. Can anybody suggest anything? I'm a bit stuck.

A: Well I guess it depends upon how you are passing your data beyond your presentation layer. Do you have a data-access layer (DAL)?
If you are doing in-line SQL in the code-behind on the click event handler, then you just need to check setup an int variable and set its value, like this:
int isChecked = 0; // Assume false
isChecked = AFCanInstCheckbox.Checked;

// Now in your SQL logic just use the value of isChecked to pass to database

If you are building a domain object (read: class) to pass to a data-access layer, then you can do it like this:
public class AFDomainObject
{
    public bool IsSelected { get; set; }
}

var theAFDomainObject = new AFDomainObject();
theAFDomainObject.IsSelected = AFCanInstCheckbox.Checked;

// Call DAL to do something
DAL.DoSomething(theAFDomainObject);


text:
Q: How to center a text in javascript inside jade template? I have retrieve from a query a variable with this content:
geneModel = [
    {
        x: 35,
        y: 55,
        description: "CC",
        id: "CC"
    },
    {
        x: 122,
        y: 142,
        description: "CC",
        id: "CC"
    },
    {
        x: 3,
        y: 14,
        description: "TIR",
        id: "TIR"
    }
]

I would like to center description field in the output, but I don't know how to do that inside a javascript code which is inside a template jade.
I have attached the code below:
 body(role='document')

  .row.jumbotron
    h3
      strong Gene model
         #div1.col-md-10.col-md-offset-1(style='margin-top: 0px')
      script.
         var FeatureViewer = require("feature-viewer");
         //Create a new Feature Viewer and add some rendering options
         window.onload = function() {
         //Create a new Feature Viewer and add some rendering options
         var ft2 = new FeatureViewer("...", {
         showAxis: true,
         showSequence: true,
         brushActive: true,
         toolbar:true,
         bubbleHelp:true,
         zoomMax:10
         });
         //Add some features
         ft2.addFeature({
         data: "#{geneModel}",
         name: "Domains",
         className: "test4",
         color: "#F4D4AD",
         type: "rect",
         height: 30,
         filter: "type1",
         style: "align-center"
         });
         };


text:
Q: Incorrect Frame Position when defined in ViewDidLayoutSubviews I have an imageView inside an ovalView constrained with auto layout.
Inside viewDidLayoutSubviews(), I am creating a UILabel
let label = UILabel(frame: imageView.frame)
imageView.superview?.addSubview(label)

The frame of label shows slightly off-centered from imageView.
However, if I move my above code inside viewDidAppear(), label is perfectly centered to imageView but user sees the change which is undesireable.
How do I keep my code in viewDidLayoutSubviews() and make it work?

A: When viewDidLayoutSubviews is called you can't assume that your views have their final frames before that method is called. In your case that's what happened. When you call viewDidAppear your view has drawn all its frames and you get the right frame that's why it works for you. So call it in viewDidAppear instead.

A: For others, who may be facing similar issues. I was able to keep my code in viewDidLayoutSubviews() by adding
self.view.layoutIfNeeded()

in my code after
let label = UILabel(frame: imageView.frame)
imageView.superview?.addSubview(label)


text:
Q: Off Platform Sybase connection using Spring Boot and Cloud Foundry I am trying to create an off-platform sybase connection in my application.
I am using Spring boot and have also created a user provided service at CF.
what extension classes would I need to create or use to achieve this ?
I have done oracle connection using OracleServiceInfo and  OracleServiceInfoCreator class.
but there is no SybaseServiceInfo class.
Below are the details for the ups
{
   "credentials": {
     "hostname": "host",
     "jdbcUrl": "jdbc:sybase://username:password@host:port/name",
     "name": "name",
     "password": "password",
     "port": "port",
     "uri": "sybase://username:password@host:port/name",
     "username": "username"
   },
   "label": "user-provided",
   "name": "SYBDB",
   "syslog_drain_url": "",
   "tags": []
 }

I am new to CF. Any help would be great.
After looking into Scott Fredrick's reply I took below mentioned steps :
I have created a ServiceInfoCreator class and a ServiceInfo class as mentioned below:
ServiceInfoCreator
import java.util.Map;

import org.springframework.cloud.cloudfoundry.CloudFoundryServiceInfoCreator;
import org.springframework.cloud.cloudfoundry.Tags;
import org.springframework.context.annotation.Profile;

@Profile({ "cloud" })
public class SybaseServiceInfoCreator extends
        CloudFoundryServiceInfoCreator<SQLDBServiceInfo> {

    public SybaseServiceInfoCreator(Tags tags, String[] uriSchemes) {
        super(new Tags(), "sybase");
        // TODO Auto-generated constructor stub
    }

    @Override
    public SQLDBServiceInfo createServiceInfo(Map<String, Object> serviceData) {
        // TODO Auto-generated method stub
        @SuppressWarnings("unchecked")
        Map<String, String> credentials = (Map<String, String>) serviceData
                .get("credentials");

        String id = serviceData.get("name").toString();
        String uri = credentials.get("uri");

        return new SQLDBServiceInfo(id, uri);
    }

}

ServiceInfo
import org.springframework.cloud.service.UriBasedServiceInfo;

public class SQLDBServiceInfo extends UriBasedServiceInfo {

    public SQLDBServiceInfo(String id, String uriString) {
        super(id, uriString);
        // TODO Auto-generated constructor stub
    }

}

and I made an entry in META-INF/Services/org.springframework.cloud.cloudfoundry.CloudFoundryServiceInfoCreator
com.x.y.SybaseServiceInfoCreator

but I get the below error when I push the application :
2015-04-20T16:28:59.85+0530 [App/0]   ERR       ... 190 more
2015-04-20T16:28:59.85+0530 [App/0]   ERR Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.C
loud]: Factory method 'cloud' threw exception; nested exception is java.util.ServiceConfigurationError: org.springframework.cloud.CloudConnector: Provider or
g.springframework.cloud.cloudfoundry.CloudFoundryConnector could not be instantiated
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrat
egy.java:189)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorRes
olver.java:588)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       ... 202 more
2015-04-20T16:28:59.85+0530 [App/0]   ERR Caused by: java.util.ServiceConfigurationError: org.springframework.cloud.CloudConnector: Provider org.springframew
ork.cloud.cloudfoundry.CloudFoundryConnector could not be instantiated
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader.fail(ServiceLoader.java:232)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader.access$100(ServiceLoader.java:185)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:384)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at org.springframework.cloud.CloudFactory.scanCloudConnectors(CloudFactory.java:91)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at org.springframework.cloud.CloudFactory.<init>(CloudFactory.java:35)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at com.x.y.config.CloudAdminConfig.cloud(CloudAdminConfig.java:56)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.lang.reflect.Method.invoke(Method.java:483)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrat
egy.java:162)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       ... 203 more
2015-04-20T16:28:59.85+0530 [App/0]   ERR Caused by: java.util.ServiceConfigurationError: org.springframework.cloud.cloudfoundry.CloudFoundryServiceInfoCreat
or: Provider com.x.y.config.SybaseServiceInfoCreator could not be instantiated
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader.fail(ServiceLoader.java:232)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader.access$100(ServiceLoader.java:185)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:384)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
2015-04-20T16:28:59.85+0530 [App/0]   ERR       at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at org.springframework.cloud.AbstractCloudConnector.scanServiceInfoCreators(AbstractCloudConnector.java:53)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at org.springframework.cloud.AbstractCloudConnector.<init>(AbstractCloudConnector.java:33)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at org.springframework.cloud.cloudfoundry.CloudFoundryConnector.<init>(CloudFoundryConnector.java:32)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.lang.Class.newInstance(Class.java:438)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       ... 213 more
2015-04-20T16:28:59.86+0530 [App/0]   ERR Caused by: java.lang.InstantiationException: com.x.y.config.SybaseServiceInfoCreator
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.lang.Class.newInstance(Class.java:423)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:380)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       ... 224 more
2015-04-20T16:28:59.86+0530 [App/0]   ERR Caused by: java.lang.NoSuchMethodException: com.x.y.config.SybaseServiceInfoCreator.<init>()
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.lang.Class.getConstructor0(Class.java:3074)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       at java.lang.Class.newInstance(Class.java:408)
2015-04-20T16:28:59.86+0530 [App/0]   ERR       ... 225 more
2015-04-20T16:29:02.38+0530 [DEA]     OUT Instance (index 0) failed to start accepting connections
2015-04-20T16:29:02.39+0530 [API]     OUT App instance exited with guid e946c9db-afdc-459a-bd01-ff718a5900db payload: {"cc_partition"=>"default", "droplet"=>
"e946c9db-afdc-459a-bd01-ff718a5900db", "version"=>"aeb7dbc8-e856-445b-80f1-0ff56339e1f5", "instance"=>"3efe1b541e2a4c6eb6aaecd7daac1143", "index"=>0, "reaso
n"=>"CRASHED", "exit_status"=>1, "exit_description"=>"app instance exited", "crash_timestamp"=>1429527542}

Not sure what I am messing up.
There's also a warning that it cannot find the ServiceInfoCreator in the beginning
2015-04-20T18:04:59.98+0530 [App/0]   OUT 2015-04-20 12:34:59.988  WARN 33 --- [           main] o.c.r.o.s.cloud.AbstractCloudConnector   : No suitable servi
ce info creator found for service SYBDB Did you forget to add a ServiceInfoCreator?

A: Spring Cloud Connectors is the project that provides the OracleServiceInfo and OracleServiceInfoCreator classes that you mentioned. As you've said, Spring Cloud Connectors doesn't support Sybase database connections. So, you have two choices:
1) Extend Spring Cloud Connectors to support Sybase connections via a user-provided service. Documentation on writing such an extension can be found here and here. These extension classes can be in your project or in a separate library, they don't need to be a part of the core SCC project for you to use them.
2) Use the vcap properties that Spring Boot automatically adds to the environment when it detects that an app is running on Cloud Foundry. You could do something as simple as including a @Value("${vcap.services.sybase.credentials.jdbcUrl}") annotation on a Spring bean and use that value to create a DataSource bean. See here for more details.
The second choice is far simpler, and is a good place to start. If you just have one application that will use this type of connection then this might suffice. If you need to use this type of connection in multiple apps then writing the SCC extension in the first option and making that a re-usable library would be a better option.

A: Thanks.That seemed to be the problem.
This is how I created my classes now
ServiceInfoCreator
@Profile({ "cloud" })
public class SybaseServiceInfoCreator extends
        RelationalServiceInfoCreator<SybaseServiceInfo> {

    public SybaseServiceInfoCreator() {
        super(new Tags(), "sybase");
        }

    @Override
    public SybaseServiceInfo createServiceInfo(String id, String uri) {
        // TODO Auto-generated method stub

        return new SybaseServiceInfo(id, uri, "sybase");
    }

    }

ServiceInfo
@Profile({ "cloud" })
@ServiceInfo.ServiceLabel("sybase")
public class SybaseServiceInfo extends RelationalServiceInfo {

     public SybaseServiceInfo(String id, String url, String uri) {
            super(id, validateUrl(url), uri);
        }
        private static String validateUrl(String url) {
            if (parse(url).getHost() == null) {
                throw new IllegalArgumentException("The URL " + url
                        + " does not appear to contain a hostname - are you missing a trailing slash?");
            }

            return url;
        }

        private static URI parse(String url) {
            try {
                return new URI(url);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e);
            }
        }

        @Override
        public String getJdbcUrl() {
            return String.format("jdbc:%s:Tds:%s:%d/%s",
                    jdbcUrlDatabaseType,getHost(), getPort(), getPath());
        }

}


text:
Q: Why won't my sql command work on asp when it showed the correct result in ACCESS? Now that I have help from this forum's,I have the sql command which can produce the correct result in ACCESS. However when I brought that to use in ASP the error said like this..
Microsoft JET Database Engine error '80040e14'

The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect.

what did I do wrong ?  my asp code is ….
Dim rsBill
set rsBill = Server.CreateObject("ADODB.Recordset")
rsBill.ActiveConnection = Conn_string<br>
rsBill.Source ="select sum(tbt.bill_total) as bill_total ,iif(sum_vat_total is null, 0, sum_vat_total) as vat_total, iif(sum_vat_total is null, 0, sum_vat_total) + sum(bill_total) as sum_of_all, month(showndate) as month from tbl_bill_total tbt left join (select sum(vat_total) as sum_vat_total , month(showndate) as month from tbl_vat_bill_total where if_paid = true and year(showndate) = 2013 group by month(showndate)) tvt on tvt.month = month(tbt.showndate) where year(showndate) = 2013 group by  month(showndate) , sum_vat_total"
rsBill.CursorType = 0
rsBill.CursorLocation = 3
rsBill.LockType = 3
rsBill.Open()
rsBill.PageSize = 20

I've tried for several days to find out what's wrong but still couldn't get it.

A: The SELECT statement includes month as an alias (in two places) ...
month(showndate) as month

Since there is a function with the same name, month is likely the reserved word the db engine is complaining about.  If you want to keep that alias, enclose it in square brackets.
month(showndate) as [month]

You reported the query ran without error in an Access session.  In that situation, the query is run from DAO.  But it fails when run from ADO because ADO seems to be less forgiving about reserved words.


text:
Q: How to change color on svg and text at same time when hover? Hi I have question about my css code.
How can I achieve my svg element to change color at same time with text before it on hover.

#den-otvorenych-dveri-container {
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  position: relative;
  justify-content: center;
  padding: 20px;
}

#den-otvorenych-dveri-img {
  width: 100%;
  height: auto;
  fill: #d63c41;
  position: absolute;
  cursor: pointer;
  left: 0;
  top: 0;
  z-index: -1;
}

#den-otvorenych-dveri {
  text-transform: uppercase;
  text-decoration: none;
  width: 150px;
  text-align: center;
  color: #fff;
  letter-spacing: 0.1em;
  font-weight: bold;
  margin-top: 20px;
  font-size: 0.8em;
  text-shadow: 1px 1px 10px #333;
}

/**
      tHIS IS NOT WORKING AS I EXCEPT
      */

#den-otvorenych-dveri:hover {
  color: #d63c41;
}

#den-otvorenych-dveri-img:hover {
  fill: yellow;
  /*Not working why?*/
}

        Deň

        otvorených

        dverí
        <svg
          id="den-otvorenych-dveri-img"
          enable-background="new 0 0 24 24"
          height="512"
          viewBox="0 0 24 24"
          width="512"
          xmlns="http://www.w3.org/2000/svg"
        >
          <path
            d="m23.363 8.584-7.378-1.127-3.307-7.044c-.247-.526-1.11-.526-1.357 0l-3.306 7.044-7.378 1.127c-.606.093-.848.83-.423 1.265l5.36 5.494-1.267 7.767c-.101.617.558 1.08 1.103.777l6.59-3.642 6.59 3.643c.54.3 1.205-.154 1.103-.777l-1.267-7.767 5.36-5.494c.425-.436.182-1.173-.423-1.266z"
          />
        </svg>

My sandbox:
https://codesandbox.io/s/elastic-hooks-vvgf3?file=/index.html:0-1902

A: Wrap the text in a span, and use correct z-index as well as selector for svg hover #den-otvorenych-dveri:hover svg{}:

#den-otvorenych-dveri-container {
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  position: relative;
  justify-content: center;
  padding: 20px;
}

#den-otvorenych-dveri-img {
  width: 100%;
  height: auto;
  fill: #d63c41;
  position: absolute;
  cursor: pointer;
  left: 0;
  top: 0;
  z-index: 0;
}

#den-otvorenych-dveri {
  text-transform: uppercase;
  text-decoration: none;
  width: 150px;
  text-align: center;
  color: #fff;
  letter-spacing: 0.1em;
  font-weight: bold;
  margin-top: 20px;
  font-size: 0.8em;
  text-shadow: 1px 1px 10px #333;
}

#den-otvorenych-dveri span {
  position: relative;
  z-index: 1;
}

#den-otvorenych-dveri:hover {
  color: #d63c41;
}

#den-otvorenych-dveri:hover svg {
  fill: yellow;
}

    Deň
otvorených
dverí
    <svg id="den-otvorenych-dveri-img" enable-background="new 0 0 24 24" height="512" viewBox="0 0 24 24" width="512" xmlns="http://www.w3.org/2000/svg">
      <path d="m23.363 8.584-7.378-1.127-3.307-7.044c-.247-.526-1.11-.526-1.357 0l-3.306 7.044-7.378 1.127c-.606.093-.848.83-.423 1.265l5.36 5.494-1.267 7.767c-.101.617.558 1.08 1.103.777l6.59-3.642 6.59 3.643c.54.3 1.205-.154 1.103-.777l-1.267-7.767 5.36-5.494c.425-.436.182-1.173-.423-1.266z"/>
    </svg>

A: Just put z-index to your container element
#den-otvorenych-dveri-container {
    width: 150px;
    height: 150px;
    display: flex;
    align-items: center;
    position: relative;
    justify-content: center;
    padding: 20px;
    z-index: 0;
}


text:
Q: Apply new array changes to useEffect with socket.io and change streams I'm currently building out a social platform, I making use of Mongo Change Streams to detect any changes, where the changes will be "emit" to separate sockets, the previous issue I've had was, that everything had worked perfectly fine, but now due to implementation of nested comments and replies my database structure has changed. So I've come up with a work around by merging the three separate arrays into a single array with the nested arrays information associated with likes and comments. So what I'd like to have is that I'd like to grab the data from the separate sockets (posts, likes, comments) and merge into one, thus where I've already applied an handler to check for any changes between the old and new data, so basically I'm only stuck on merging these three sockets data into one array, I'm abit lost on how to take this approach.
change streams
const db = mongoose.connection;
db.once('open', () => {
    //post changes
    console.log(chalk.blueBright("Setting change streams"));
    db.collection('posts').watch()
    .on('change', change => {
        if(change.operationType === 'insert'){
            console.log(chalk.yellowBright('INSERTED'))
            io.emit('posts', change.fullDocument);
            console.log(change.fullDocument)
        }
    });
    db.collection('posts').watch({ fullDocument: 'updateLookup' })
    .on('change', change => {
        if(change.operationType === 'update'){
            console.log(chalk.yellowBright('UPDATED'));
            io.emit('posts', change.fullDocument);
            console.log(change.fullDocument)
        }
    })

    //comments changes
    db.collection('comments').watch({ fullDocument: 'updateLookup' })
    .on('change', change => {
        if(change.operationType === 'insert'){
            console.log(chalk.yellowBright('INSERTED'))
            io.emit('comments', change.fullDocument);
            console.log(change.fullDocument)
        }
    });
    db.collection('comments').watch({ fullDocument: 'updateLookup' })
    .on('change', change => {
        if(change.operationType === 'update'){
            console.log(chalk.yellowBright('UPDATED'));
            io.emit('comments', change.fullDocument);
            console.log(change.fullDocument)
        }
    })
});

client-side
useEffect for detecting any changes posts
//Check socket changes
    useEffect(() => {
      //merged posts with comments and likes sockets?
      //this is the solution I've come up on merging three arrays but
      //I'd like to apply this with the three sockets data that are being retrieved or applied
      const newPosts = posts.map(post => ({
        ...post,
        likes: likes.filter(like => post.likes.map(like => like._id).includes(like._id)),
        comments: comments.filter(comment => post.comments.map(comment => comment._id).includes(comment._id)),
      }))

      const handler = (item) => {
        setPosts((oldPosts) => {
          const findItem = oldPosts.find((post) => post._id === item._id);
          if (findItem) {
            return oldPosts.map((post) => (post._id === item._id ? item : post));
          } else {
            return [item, ...oldPosts];
          }
        });
      };

      //Sockets
      //socket.off("comments", handler);
      //socket.off("likes", handler);

      return () => socket.off("posts", handler);
       //eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

A: There has been two solutions to this, first one is changing how the socket is being called to socket.onMany(handler) which adds a listener that will be fired when any event is emitted. there, the output would be stored as [["posts",{}],["comment",{}],["likes"],{}], the next thing would do is to remove the string values with the use of ".splice(indexOf('posts'))", then you would need to flatten the three arrays into objects, and to merge them with one another by the associated id's likes:
const newPosts = posts.map(post => ({
    ...post,
    likes: likes.filter(like => post.likes.map(like => like.id).includes(like.id)),
    comments: comments.filter(comment => post.comments.map(comment => comment.id).includes(comment.id)),
}))

The second approach would be to modify the change streams, to call the Post Model and to make use of populate(), which will every time call a new request to the database with the populated data as needed and then emitting it to your socket, therefor since posts would be the parent document, only changes should be checked in the posts socket.
//post changes
    console.log(chalk.blueBright("Setting change streams"));
    db.collection('posts').watch()
    .on('change', change => {
        if(change.operationType === 'insert'){
            PostModel.find({}).lean().populate('comments')
            .then((posts) => io.emit('posts', posts))
        }
    })
    db.collection('posts').watch({ fullDocument: 'updateLookup' })
    .on('change', change => {
        if(change.operationType === 'update'){
            PostModel.find({}).lean().populate('comments')
            .then((posts) => io.emit('posts', posts))
        }
    })


text:
Q: I need a Android Wifi/bluetooth program for transferring photos taken to another Wifi device, can anybody kindly provide any resources/example code I am trying to write an Android Program to transfer a photo taken on a android phone to a remote device(e.g. another phone or computer) using Wifi or Bluetooth

A: Do you mean something like this?
http://www.howtogeek.com/167344/how-to-easily-transfer-files-between-nearby-smartphones/


text:
Q: Should I use Buffer and UTF-8 in Node.js for sending data across the wire? I have a system with two process, one in Java and one in Node.js. The node.js process is a web front-end. It ingests data and sends it to a queue for process, where it is consumed by the Java process. The data is a string of user data collected from browser code, and I create a string of the data in Node.js using JSON.stringify(data), and push it to kinesis, the aws version of kafka. The java process receives the raw bytes, creates a string object, and then parses the json.
My question is this: I am not sure what decoding I should instruct Java to use on the raw bytes. Right now, it "just works" with the default decoding, but I feel this is a bad idea, since the default decoding could be platform-dependent. Should I use Buffer on the Node.js side, and encode the string into UTF-8 before I push it to the queue? That way I could explicitly set UTF-8 as the decoding on the java side? Is this a best practice? Any advice much appreciated.


text:
Q: What is the difference between "Are you sure to xxx?" and "Do you sure to xxx?" What is the difference between "Are you sure to xxx?" and "Do you sure to xxx?"
I am writing an app that requires to ask the user to confirm some actions.
E.g. I want to confirm the user whether to delete a file,
Should I use "Are you sure to delete this file?" or "Do you sure to delete this file?
I am not sure which one is better.

A:
What is the difference between "Are you sure to xxx?" and "Do you sure to xxx?"

Both don't really make much sense. "Do you sure to ..." is simply incorrect, whereas you can say "be sure to do something", meaning "don't forget to do it" (e.g. be sure to lock the door before you go to bed), yet this is also not how you would phrase things in the context of asking a user to confirm an action.

E.g. I want to confirm the user whether to delete a file, Should I use "Are you sure to delete this file?" or "Do you sure to delete this file?

What you want to ask is "Are you sure you want to xxx?". In your case this would be "Are you sure you want to delete this file?"
Edit: As @BoldBen points out, this phrase might be a little long. Something like "Are you sure?" or "Really delete file?" is probably better.


text:
Q: Put satin on women's panties Was watching Prison Break Season 5 Episode 1 and came across this very sentence at the beginning:
"What is it with you killers that put the satin on women's panties anyhow?"
What does "put satin on women's panties" mean?

A: This is funny, I think it's a phrase taken from a Tupac song. Satin is a "sexy" fabric.
"You put the satin on women's panties" in more-boring-speak would be something like "You are the reason women wear sexy underwear."

A: The implication may be that a woman gets wet when thinking about a killer. The cotton panties suffused with the juices turn to satin.
Oh, and the sentence needs a comma before "anyhow".


text:
Q: macbook pro absurdly small battery life My Macbook Pro lasts me about 1.5 to 2 hours max on a single charge. This feels ridiculously low.
What can I do to increase the battery life on Macbook Pro?
Battery Information:

  Model Information:
  Manufacturer: SMP
  Pack Lot Code:    0000
  PCB Lot Code: 0000
  Firmware Version: 0201
  Hardware Revision:    000a
  Cell Revision:    0157
  Charge Information:
  Charge remaining (mAh):   6079
  Fully charged:    No
  Charging: Yes
  Full charge capacity (mAh):   6930
  Health Information:
  Cycle count:  3
  Condition:    Normal
  Battery Installed:    Yes
  Amperage (mA):    2139
  Voltage (mV): 12492

A: Make sure there are no processes hogging your CPU (this eats battery).
Open Activity Monitor from /Applications/Utilities.
Set the Show menu at the top right to All Processes
Click the %CPU column head so the triangle faces down.
Which processes are at the top? How much are they using?
This may reveal what's going on.
Also, you can check the health of your battery to make sure it's not a hardware problem.
Download the free coconutBattery app and see what it has to say about your batter's capacity.

A: Use the laptop plugged in as much as possible.  Any time you drain the battery at all, and then charge it, the drain + charge is counted towards 'a cycle', where 'a cycle' means the battery has drained, and been charged, 100%.
So if you drain it half way and charge it fully, twice, that counts as 'a cycle'.  These batteries will last a certain number of cycles.  There are utilities out there that will check your cycle count, I often use one called "Pow!".
Other than that;  run as few applications as possible.  Turn off any sensors (ambient light sensor, keyboard backlighting, etc).  Run the laptop with as dim a setting on the screen as possible.
Also, try to know what's running in the background.  If you've got processes you don't need doing stuff, that will drain your battery faster.

A: I've just gone through two brand new MacBook Pro Retina 15's, "fresh" from Apple Store, both of which were giving me only 3-4 hours on a fresh charge.
After resetting NVRAM and SMC, I now get 5-6 or more hours.
If you buy a new MacBook -- and are getting less than 5 hours per charge -- try resetting your NVRAM and SMC.
How to Reset NVRAM:

*

*Shut down the computer.

*Locate the following keys on your keyboard:  COMMAND  , OPTION, the letter  P, and the letter R.

*Turn on the computer

*Press and hold the COMMAND - OPTION - P and R keys before the gray screen appears and before you hear any chimes.

*Hold the keys down until the computer restarts and you hear the startup sound for the second time.

*Release the keys.

Reset SMC:

*

*Shut down the computer.

*Plug in the MagSafe power adapter to a power source, connecting it to the Mac if its not already connected.

*On the built-in keyboard, press the (left side) Shift-Control-Option keys and the power button at the same time.  The OPTION key is also known as ALT.

*Count to 5 then release all the keys and the power button at the same time.

*Press the power button to turn on the computer.

*Note: The LED on the MagSafe power adapter may change states or temporarily turn off when you reset the SMC.

References:

*

*SMC: http://support.apple.com/kb/HT3964

*NVRAM: http://support.apple.com/kb/ht1379