text:
Q: DB2 case statement for updating a table but multiple columns I am trying to merge 4 separate update statements into one single update statement.
I have no experience with case statements or if what I'm attempting to do would even work.
Any input on how to structure this?
This is my attempt, but it's not working.
  UPDATE URL
  SET CONTENT_TITLE =
  CASE
     WHEN ID = ? AND SYSTEM_UPDATE_REASON = ? AND CONTENT_TITLE IS NOT NULL AND ? NOT BETWEEN 400 AND 599 OR ID = ? AND SYSTEM_UPDATE_REASON = ? AND CONTENT_TITLE != '' AND ? NOT BETWEEN 400 AND 599 THEN ?
     WHEN ID = ? AND CONTENT_TITLE IS NULL AND ? NOT BETWEEN 400 AND 599 OR ID = ? AND CONTENT_TITLE = '' AND ? NOT BETWEEN 400 AND 599 THEN ?
     WHEN ID = ? AND CONTENT_TITLE IS NOT NULL AND ? BETWEEN 400 AND 599 THEN ?
     WHEN ID = ? AND CONTENT_TITLE IS NULL AND ? BETWEEN 400 AND 599 OR ID = ? AND CONTENT_TITLE = '' AND ? BETWEEN 400 AND 599 THEN ?
  SET CONTENT_DSCR =
  CASE
     WHEN ID = ? AND CONTENT_DSCR IS NULL AND ? NOT BETWEEN 400 AND 599 OR ID = ? AND CONTENT_DSCR = '' AND ? NOT BETWEEN 400 AND 599 THEN ?
     WHEN ID = ? AND CONTENT_TITLE IS NOT NULL AND ? BETWEEN 400 AND 599 THEN ?
  SET SYSTEM_UPDATE_REASON = 'title and dscr update'
  SET UPDATED_ON = SYSDATE
  END

Here are the placeholders (?) I'm using:
u.urlId, 'title and dscr update', u.statusCode, u.urlId, 'title and dscr update',
u.statusCode, u.contentTitle, u.urlId, u.statusCode, u.urlId, u.statusCode,
u.contentTitle, u.urlId, u.statusCode, null, null, u.urlId, u.statusCode, u.urlId,
u.statusCode, u.contentDescription, u.urlId, u.statusCode, 'title and dscr update'

A: Maybe it won't help at all, but - let me try (as there's no reply for hours):
I don't know DB2; if its SQL is anything similar to Oracle's then

*

*CASE should have its END

*there's only one SET keyword in the whole UPDATE statement

*logically, when there's OR, you should use parentheses (otherwise you'll get unexpected result)

Something like this:
UPDATE URL
  SET CONTENT_TITLE =
        CASE
           WHEN     (ID = ? AND SYSTEM_UPDATE_REASON = ?  AND CONTENT_TITLE IS NOT NULL AND ? NOT BETWEEN 400 AND 599)
                 OR (ID = ? AND SYSTEM_UPDATE_REASON = ?  AND CONTENT_TITLE != ''       AND ? NOT BETWEEN 400 AND 599) THEN ?
           WHEN     (ID = ? AND CONTENT_TITLE IS NULL     AND ? NOT BETWEEN 400 AND 599)
                 OR (ID = ? AND CONTENT_TITLE = ''        AND ? NOT BETWEEN 400 AND 599) THEN ?
           WHEN      ID = ? AND CONTENT_TITLE IS NOT NULL AND ? BETWEEN 400 AND 599 THEN ?
           WHEN     (ID = ? AND CONTENT_TITLE IS NULL AND ? BETWEEN 400 AND 599)
                 OR (ID = ? AND CONTENT_TITLE = ''    AND ? BETWEEN 400 AND 599) THEN ?
        END,
  CONTENT_DSCR =
        CASE
           WHEN    (ID = ? AND CONTENT_DSCR IS NULL AND ? NOT BETWEEN 400 AND 599)
                OR (ID = ? AND CONTENT_DSCR = ''    AND ? NOT BETWEEN 400 AND 599) THEN ?
           WHEN ID = ? AND CONTENT_TITLE IS NOT NULL AND ? BETWEEN 400 AND 599 THEN ?
        END,
  SYSTEM_UPDATE_REASON = 'title and dscr update',
  UPDATED_ON = SYSDATE


text:
Q: Recursively adding words to a LinkedHashMap character by character I'm trying to write a class into which I can enter words, and a tree of characters will be created from the entered word. The tree can then be checked whether a certain word exists in it. My issue is that I can only get it to save one character from any word - if a word has more than one character, only the first one is saved (I'm pretty sure the contains method is right). This is my code, something is evidently wrong with it however I can't tell what:
public class Dictionary {

  private Map<Character, DictionaryTree> children = new LinkedHashMap<>();
  private boolean endOfWord;

  DictionaryTree() {
    endOfWord = false;
  }

  void insert(String word) {
    if (!contains(word)) {
      DictionaryTree newDictionaryTree = new DictionaryTree();
      if (word.length() > 1) {
        newDictionaryTree.insert(word.substring(1, word.length()));
      } else if (word.length() == 1) {
        newDictionaryTree.endOfWord = true;
      }
      children.put(word.charAt(0), newDictionaryTree);
    }
  }

  boolean contains(String word) {
    if (word.length() > 0) {
      // Check if first letter is a child node
      if (children.containsKey(word.charAt(0))) {
        if (word.length() > 1) {
          DictionaryTree extractedDictionaryTree = children.get(word.charAt(0));
          extractedDictionaryTree.contains(word.substring(1, word.length()));
        }
        // If only one character left, check if end of word
        else if (children.get(word.charAt(0)).endOfWord == true) {
          return true;
        } else {
          return false;
        }
      }
      return false;
    }

    return false;
  }
}

Any help would be much appreciated.

A: As per your requirement you want to search a word, if it exists or not.
You will achieve it with LinkedHashmap but you try with the Trie data structure. Which provides the efficient way to insert as well as search the String or any data in an efficient way.
Source code is referenced from GeeksForGeeks
                   root
                /   \    \
                t   a     b
                |   |     |
                h   n     y
                |   |  \  |
                e   s  y  e
             /  |   |
             i  r   w
             |  |   |
             r  e   e
                    |
                    r

Implementation:
// Java implementation of search and insert operations
// on Trie
public class Trie {

    // Alphabet size (# of symbols)
    static final int ALPHABET_SIZE = 26;

    // trie node
    static class TrieNode
    {
        TrieNode[] children = new TrieNode[ALPHABET_SIZE];

        // isEndOfWord is true if the node represents
        // end of a word
        boolean isEndOfWord;

        TrieNode(){
            isEndOfWord = false;
            for (int i = 0; i < ALPHABET_SIZE; i++)
                children[i] = null;
        }
    };

    static TrieNode root;

    // If not present, inserts key into trie
    // If the key is prefix of trie node,
    // just marks leaf node
    static void insert(String key)
    {
        int level;
        int length = key.length();
        int index;

        TrieNode pCrawl = root;

        for (level = 0; level < length; level++)
        {
            index = key.charAt(level) - 'a';
            if (pCrawl.children[index] == null)
                pCrawl.children[index] = new TrieNode();

            pCrawl = pCrawl.children[index];
        }

        // mark last node as leaf
        pCrawl.isEndOfWord = true;
    }

    // Returns true if key presents in trie, else false
    static boolean search(String key)
    {
        int level;
        int length = key.length();
        int index;
        TrieNode pCrawl = root;

        for (level = 0; level < length; level++)
        {
            index = key.charAt(level) - 'a';

            if (pCrawl.children[index] == null)
                return false;

            pCrawl = pCrawl.children[index];
        }

        return (pCrawl != null && pCrawl.isEndOfWord);
    }

    // Driver
    public static void main(String args[])
    {
        // Input keys (use only 'a' through 'z' and lower case)
        String keys[] = {"the", "a", "there", "answer", "any",
                         "by", "bye", "their"};

        String output[] = {"Not present in trie", "Present in trie"};

        root = new TrieNode();

        // Construct trie
        int i;
        for (i = 0; i < keys.length ; i++)
            insert(keys[i]);

        // Search for different keys
        if(search("the") == true)
            System.out.println("the --- " + output[1]);
        else System.out.println("the --- " + output[0]);

        if(search("these") == true)
            System.out.println("these --- " + output[1]);
        else System.out.println("these --- " + output[0]);

        if(search("their") == true)
            System.out.println("their --- " + output[1]);
        else System.out.println("their --- " + output[0]);

        if(search("thaw") == true)
            System.out.println("thaw --- " + output[1]);
        else System.out.println("thaw --- " + output[0]);

    }
}

Hope it helps!!!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue with SOAP Header created via Apex We are trying to make a SOAP callout to an API. The sample header provided by the API is as follows
<env:Header>
     <Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
           <UsernameToken>
                <Username>abcdef</Username>
                <Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">*****</Password>
            </UsernameToken>
      </Security>
</env:Header>

After wsdltoapex, when I made the call out I get the following Header as a part of my request.
<env:Header>
     <Security xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
           <UsernameToken>
                <Username>abcdef</Username>
                <Password>*****</Password>
            </UsernameToken>
      </Security>
</env:Header>

I could see that the Type attribute in the header generated by the apex class is missing.
This is the apex code in the class that constructs the Username and password tags in the XML
public class UsernameToken_element {

        public UsernameToken_element(String username, String password) {

             this.username = username;
             this.password = password;
        }

        public String username;
        public String password;
        private String[] username_type_info = new String[]{'Username','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
        private String[] password_type_info = new String[]{'Password','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
        private String[] field_order_type_info = new String[]{'username','password'};
}

In order to include the Type attribute in the Password tag where should I include it in the Apex code? I tried adding it as another private string and also tried to include it in the password_type_info. But it was not added in the password tag.

A: Looking at http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd I see
<xsd:complexType name="PasswordString">
  <xsd:annotation>
    <xsd:documentation>
      This type is used for password elements per Section 4.1.
    </xsd:documentation>
  </xsd:annotation>
  <xsd:simpleContent>
    <xsd:extension base="wsse:AttributedString">
      <xsd:attribute name="Type" type="xsd:anyURI"/>
    </xsd:extension>
  </xsd:simpleContent>
</xsd:complexType>

So they Type attribute can just be any URL.
You will likely need to use the rare and elusively documented _att_info string array to populate the Attribute. This would be a good time to pause and consider voting for Documentation for WebServiceCallout.
The open source version of WSDL2Apex includes a test case against this attribute.
From the source WSDL:
        <xs:complexType name="Angle">
            <xs:simpleContent>
                <xs:extension base="xs:double">
                    <xs:attribute name="uom" type="tns:AngularUnit" use="required"/>
                </xs:extension>
            </xs:simpleContent>
        </xs:complexType>

Corresponding test assertion.
public class wwwMapinfoComMidevServiceUnitsV1 {
    public class Angle {
        public String uom;
        private String[] uom_att_info = new String[]{'uom'};
        private String[] apex_schema_type_info = new String[]{'http://www.mapinfo.com/midev/service/units/v1','false','false'};
        private String[] field_order_type_info = new String[]{};
    }
}

So, you create a member on the class to store the actual attribute value and a memberName_att_info String array that contains the name of the attribute.
public class UsernameToken_element {

    public UsernameToken_element(String username, String password) {

        this.username = username;
        passwordToken = new password_element(password);
        system.debug('passwordTokennnn '+passwordToken);
    }

    public String username;
    public password_element passwordToken;
    private String[] username_type_info = new String[]{'Username','http://www.w3.org/2001/XMLSchema','string','1','1','false'};
    private String[] passwordToken_type_info = new String[]{'Password','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText','string','1','1','false'};
    private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
    private String[] field_order_type_info = new String[]{'username','passwordToken'};
}

public class password_element{
    public password_element( String password) {
        system.debug('passworddddd '+password);
        this.password = password;
        type = 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText';
    }

    public String password;
    public string type; // Set to 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'
    public String[] type_att_info = new String[]{'Type'};
    private String[] password_type_info = new String[]{'Password','http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText','string','1','1','false'};
    private String[] apex_schema_type_info = new String[]{'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd','true','false'};
    private String[] field_order_type_info = new String[]{'password'};
}

Give that a try, it might work. I say might as I made a note in my version of Wsdl2Apex that

"Simple Content Types with Attributes are not supported by WebServiceCallout.invoke"


text:
Q: How to have IN operator work to have hard coded values match Have accountId ={001,3456,78902,456}

I wanted to get the details of these accountId from existing table using  IN clause and a left join on operation, how should I form the query? Being new to DB end I am not able to put the correct pieces together:
select t1.col2, case when CASE WHEN t1.col3 is null THEN 'False' ELSE 'True' END as value
FROM table2 t2 left join table1 t1 on t2.col1=t1.col1
WHERE accountID IN (001,3456,78902,456); //The query is wrong because, I wanted to map using those accountID and get the data?

Any quick help on forming the query would be great
The Existing table have accountId as one of the columns.

A: Guessing ...
SELECT t2.col1, t1.col2, (t1.col3 IS NULL) AS value
FROM   table2 t2
LEFT   JOIN table1 t1 USING (col1)
WHERE  t2.accountid IN (1,3456,78902,456); -- t1 or t2 ???

I added t2.col1 or you might get rows with only NULL values.
Using the simpler (t1.col3 IS NULL) AS value which returns boolean TRUE / FALSE directly.
Also using the simpler USING to join on a column of the same name.
If accountid is in table1 as well, you don't need to join at all ..
SELECT t1.col2, (t1.col3 IS NULL) AS value
FROM   table1
WHERE  t1.accountid IN (1,3456,78902,456);


text:
Q: Changing Redis port in Docker Compose not working I have a Docker Compose file that starts two services: Redis and Redis Commander. Using the default Redis port 6379 works fine. After changing the Redis port to 6380 Redis Commander cannot connect to Redis anymore.
Error:
setUpConnection Redis error Error: connect ECONNREFUSED 172.19.0.2:6380

This is the docker-compose.yml file:
version: '3.7'
services:
  redis:
    container_name: redis
    hostname: redis
    image: sameersbn/redis:4.0.9-2
    ports:
      - "6380:6379"
    expose:
      - "6380"
    volumes:
      - type: volume
        source: redis-data
        target: /data
    restart: always
  redis-commander:
    container_name: redis-commander
    hostname: redis-commander
    image: rediscommander/redis-commander:latest
    restart: always
    environment:
      - REDIS_HOSTS=local:redis:6380
    ports:
      - "8082:8081"
volumes:
  redis-data: {}

I can connect to Redis on port 6380 using the following Node code:
import redis from 'redis'

const config = {
  host: '127.0.0.1',
  port: 6380,
  no_ready_check: true
}

const client = redis.createClient(config.port, config.host)

client.set('expireName', 'nidkil', (err, reply) => {
  if (err) {
    console.error('Error occurred:', err)
  } else {
    console.log('Response:', reply)
  }
})

If I change the port back to 6379 in the docker-compose.yml then Redis Commander can connect.
Any suggestions how I can make Redis Commander connect to Redis on port 6380?

A: You changed the exposed port on the host. You did not change the internal port in the container. Your redis instance continues to run on the default port (6379).
Also this statement expose: - "6380" can be omitted since it is not useful.

A: The answer of @Mihai helpt me figure out the solution. I needed to change the port Redis is running on as well as the exposed port. This is the working Docker compose file.
version: '3.7'
services:
  redis:
    container_name: redis
    hostname: redis
    image: sameersbn/redis:4.0.9-2
    command: --port 6380
    ports:
      - "6380:6380"
    expose:
      - "6380"
    volumes:
      - type: volume
        source: redis-data
        target: /data
    restart: always
  redis-commander:
    container_name: redis-commander
    hostname: redis-commander
    image: rediscommander/redis-commander:latest
    restart: always
    environment:
      - REDIS_HOSTS=local:redis:6380
    ports:
      - "8082:8081"
volumes:
  redis-data: {}


text:
Q: Elastic Search Performance Solution We have records taken every 30 seconds. Over the past few years we have a quite a few built up. Creating a windowing search on those records based on some interval of time.
For Example:

*

*User inputs 15 minute increment between records based on current time: Time now: 8:53 (next 15 would be 9:08, 9:23, etc) within 1 hour.

*User wants records between two dates (could be as big as 3 years of records at a 15 minute increment).

*The records are not guaranteed to be exactly at those times but more like a maybe... we need to return the closest record to each 15 minute window of time.

*There are several other query additions to filter these records by but the main issue is the problem above.

I have already created something that meets this goal but it likely can be refined and more performant. Also the way the UI queries and applies the incremented records can likely be improved.
Tell me if anyone has an idea for a solution? Thanks in advance.


text:
Q: cisco license install tftp no response from tftp server I am trying to install a license through tftp in the CLI of a Cisco 2504 controller. My computer is a Mac Pro running Mojave version 10.14.6.
I have enable the tftp server on my mac. When I do netstat -na |grep \*.69 I see the following:
udp4       0      0  *.69                   *.*
udp6       0      0  *.69                   *.*

My computer has the ip address 10.0.11.156 on the network. I have installed the license in the /private/tftpboot directory. I also did chmod 766 on the /private directory /private/tftpboot and the license file itself.
I am able to get files by tftp from other machines on the network. On another computer on the network I entered:
tftp 10.0.11.156
tftp> get [license filename]

I got the response:
received 2236 bytes in 0.1 seconds

But when I go to the controllers CLI and enter
 (Cisco Controller)> license install tftp://10.0.11.156/[license filename]

the cli says Transfering licenses from tftp://[license filename], then hangs for about a minute then responds
% Error: License file transfer failed - No reply from the TFTP server

In short, I'm able to tftp the file from another computer, but I get no response from the server when trying to install a license.
I forgot to add that I am able to ping from the controller to 10.0.11.156.
How do I install my license on my controller?

A: No reply from the TFTP server means communication from the TFTP server back is not working.

*

*Make sure the correct port is open. If you say you can make transfers from another PC this may be fine, but check anyway.

*Make sure you do not have multiple WAN/network connections on the computer you use because routing may mess things up and your return packets may end nowhere because they try to return via another route/path. If you do, disable the unneeded one or use administrative distances to make the default route the correct one.

A: What worked for me was to hardwire a windows machine directly into the network instead of using the wifi, then used the tftpd64 app.


text:
Q: Crop image according to frame of any View I have an image and I want to crop it according to frame of any view. For example;
I really can't find the solution. I have been searching it for 2 days.
BEFORE
AFTER
EDITTED
Thanks to @Ajharul Islam and @Bence Pattogato. Both of answers work.
Swift version of @Ajharul Islam 's solution.
      func images(byCroppingImage image: UIImage?, to size: CGSize) -> UIImage? {
        // not equivalent to image.size (which depends on the imageOrientation)!
        let refWidth = (image?.cgImage?.width)!
        let refHeight = (image?.cgImage?.height)!

        let x = (Double(refWidth) - Double(size.width)) / 2
        let y = (Double(refHeight) - Double(size.height)) / 2

        let cropRect = CGRect(x: CGFloat(x), y: CGFloat(y), width: size.width, height: size.height)

        let imageRef = image?.cgImage!.cropping(to: cropRect) as! CGImage

        var cropped: UIImage? = nil
        if let imageRefs = image?.cgImage!.cropping(to: cropRect) {
            cropped = UIImage(cgImage: imageRefs, scale: 0.0, orientation: UIImage.Orientation.up)
        }

        return cropped
    }

Let me tell my mistake and what was i trying for
I was trying  take picture and crop it according to any view's frame. I was trying to crop the picture without resize it according to that main view. So it was cropping from wrong way every time.
I resized the picture and now I can successfully crop picture. But resizing  reduce picture's quality. So now I am tring to find the best method.
Thank you

A: I think the simplest way to achieve it is the following:
extension UIImage {
    func crop(to rect: CGRect) -> UIImage? {
        guard let imageRef = cgImage, let cropped = imageRef.cropping(to: rect) else {
            return nil
        }
        return UIImage(cgImage: cropped)
    }
}

A: You can crop image using this code :
   - (UIImage *)imageByCroppingImage:(UIImage *)image toSize:(CGSize)size
{
    // not equivalent to image.size (which depends on the imageOrientation)!
    double refWidth = CGImageGetWidth(image.CGImage);
    double refHeight = CGImageGetHeight(image.CGImage);

    double x = (refWidth - size.width) / 2.0;
    double y = (refHeight - size.height) / 2.0;

    CGRect cropRect = CGRectMake(x, y, size.height, size.width);
    CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);

    UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:self.imageOrientation];
    CGImageRelease(imageRef);

    return cropped;
}

pass your image and rect of the view you will get a cropped image from center

A: You are searching for the
CIAffineTransform or the CIPerspectiveCorrection. I am not sure which is better for your use case but they should work both. For example you can use the CIPerspectiveCorrection like that:
(CIImageToWorkWith).applyingFilter("CIPerspectiveCorrection", parameters: [
                            "inputTopLeft" : CIVector(cgPoint: topleft),
                            "inputTopRight" : CIVector(cgPoint: topright),
                            "inputBottomLeft" : CIVector(cgPoint: bottomleft),
                            "inputBottomRight" : CIVector(cgPoint: bottomright)
                            ])

edit: You don not want to crop the Image. Cropping is like cutting out something from an Image without scaling it.


text:
Q: API Key Invalida OpenWeatherMap Estoy tratando de hacer una sencilla aplicación web para obtener los datos del clima a través de la API Openweathermap, pero no logro avanzar, a pesar de haber usado 3 keys distintas, siempre obtengo el mismo resultado por consola:
{"cod":401, "message": "Invalid API key. Please see <http://openweathermap.org/faq#error401> for more info."}

Les dejo el código de JS para que vean si estoy haciendo algo mal, quizás sea algo simple y no esté dándome cuenta:
const api = {
    key: 'xxx',
    url: 'https://api.openweathermap.org/data/2.5/weather'
}

async function search(query) { // obtener informacion de la API
    try {
      const response = await fetch(`${api.url}?q=${query}&appid${api.key}&lang=es`);
      const data = await response.json();
      console.log(data);
    } catch (err) {
        console.log(err);
        alert('Hubo un error');
    }
}


text:
Q: Difficulty in connecting to wifi on my Ubuntu 14.04. HP-pavalion g6 I am not able to connect to wireless network on my Ubuntu 14.04 machine. I reinstalled the OS but still getting the same problem. I went through certain post and ran wireless-info.txt on my machine the result of whic is as follows. Please help me resolve this issue.Thanks in advance.
http://paste.ubuntu.com/16321584/

A: Assuming that the network you want to connect to is (you didn't specify, but it is the loudest):
Wireless Access Points
MyHP_Network:    Infra, <MAC 'MyHP_Network' [AC1]>, Freq 2412 MHz, Rate 54 Mb/s, Strength 90 WPA WPA2

You can follow the tutorial on linuxconfig.org.


text:
Q: Excel function to make SQL-like queries on worksheet data? I have a largish table in an Excel worksheet:
Column_1 | Column_2 | Column_3

ValueA       ValueB     ValueC
....

What I need is a function that will take as input the range and an SQL-like query String and return a range of rows that match the query, e.g.:
=SQL_SELECT(A1:C1000, "SELECT * WHERE Column_1 = ValueH AND Column_3 = blah")

Does something like this exist? Or what would be the best way to implement myself?

A: If you can save the workbook then you have the option to use ADO and Jet/ACE to treat the workbook as a database, and execute SQL against the sheet.
The MSDN information on how to hit Excel using ADO can be found here.

A: You can use Get External Data (despite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself.  Use From Other Sources From Microsoft Query to connect to Excel
Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query.  This query does reference the in memory workbook, so doesn't require a save to refresh the latest data.
Here's a quick Sub to demonstrate accessing the connection objects
Sub DemoConnection()
    Dim c As Connections
    Dim wb As Workbook
    Dim i As Long
    Dim strSQL As String

    Set wb = ActiveWorkbook
    Set c = wb.Connections
    For i = 1 To c.Count
        ' Reresh the data
        c(i).Refresh
        ' view the SQL query
        strSQL = c(i).ODBCConnection.CommandText
        MsgBox strSQL
    Next
End Sub

A: One quick way to do this is to create a column with a formula that evaluates to true for the rows you care about and then filter for the value TRUE in that column.

A: If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools
Example, function BS_SQL("SELECT ..."):

A: Sometimes SUM_IF can get the job done.
Suppose you have a sheet of product information, including unique productID in column A and unit price in column P. And a sheet of purchase order entries with product IDs in column A, and you want column T to calculate the unit price for the entry.
The following formula will do the trick in cell Entries!T2 and can be copied to the other cells in the same column.
=SUMIF(Products!$A$2:$A$9999,Entries!$A2, Products!$P$2:$9999)

Then you could have another column with number of items per entry and multiply it with the unit price to get total cost for the entry.


text:
Q: Getting textbox value from one page to another page textbox value I am creating a form in my website and i link this form to the google docs (FORM which i created there). But this new form that i am trying to do is this in such a way that a textbox value from the first page should be passed over to the next page lets say page2 textbox value
CODE IS ROUGHLY SOMETHING LIKE THIS
PAGE 1.html,aspx,asp (Watever)
"/>
Page2.html,aspx,asp (Watever)
 **readonly**"/>
So since i am using the google docs to save my data
          **
form action="http://docs.google.com
i am unsure how to pass these values, tks for the help.
Presently i am just getting the values from page1 to page2 using this microsoft tutorial
http://support.microsoft.com/kb/300104

A: I think you need to read
How to: Pass Values Between ASP.NET Web Pages
you can store values using the approaches listed there.
Eg:
On your Page 1:
Create a textbox named  textbox  and an asp button.
on button.click code behind add
Session["test"] = textbox.Text;
Response.Redirect("Page2.aspx"); //Open page 2

On your Page 2 :
Creata a label named label1
Then on its Pageload Event in code behind
Add
string IpassAstringfrompage1 = Convert.ToString(Session["test"]);

label1.Text = IpassAstringfrompage1; //label1 will display TESTING from textbox on Page1

To test. On Page1 input "TESTING" on your textbox then click button
Regards


text:
Q: How to do git status from powershell? I tried this and it doesn't show any output. What is the right way to do this?
invoke-expression 'git status'

A: *

*Install-Module posh-git -Scope AllUsers

*Import-Module posh-git

*CD in Powershell to any cloned Git repo folder and the prompt itself gives you the full status
More info:
 https://github.com/dahlbyk/posh-git

Otherwise, you can always fall back on the standard Git shell with a "git status" but issuing an invoke-expression etc. in PS for the non-PS CIM is certainly not the most efficient way to work with Git locally in PS.


text:
Q: two dropdownlist I have two dropdownlist boxes. If I click on the first dropdown box, then the values have been changed in the second listbox accordingly to first listbox.
For example:
One is Fruits,vegetables,Birds. If i click on the Fruits then it shows the fruit list items in the second list box. It is same for other list also.

A: Hai Praveen,
Have a look at these examples for question reguarding cascading dropdown
http://www.phpclasses.org/browse/package/2053.html
http://www.skillfusion.com/articles/ajaxDropdown.php
http://codestips.com/php-ajax-cascading-dropdown-using-mysql/
http://www.daniweb.com/forums/thread132703.html
http://www.weberdev.com/get_example-4505.html


text:
Q: terrible image quality after resize
Possible Duplicate:
Resizing an Image without losing any quality

I'm resizing images using the following method:
public static Bitmap Resize(Image source, int width, int height)
{
    Bitmap bitmap = new Bitmap(width, height);

    using (Graphics graphics = Graphics.FromImage(bitmap))
    {
        graphics.SmoothingMode = SmoothingMode.AntiAlias;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
        graphics.DrawImage(source, new Rectangle(0, 0, width, height));
    }

    return bitmap;
}

The output image quality is terrible bad. Is there a way to resize the image without messing up the quality?
PS: the image source width and height is always bigger than the width and height parameters and the width and height ratio is being preserved.

A: Depends on resize and resolution of the image. If you make image bigger it's natural to get a bad result, you can get the same bad result on making image smaller, without maintaining its proportion.
In general, if you want to have scallable nice looking image, hold on Vector Graphics.
In other words use: Metafile or some SVG library for images.


text:
Q: reorder a field of a table I have this table named Employee :
IdEmploye    |     Order
    10                1
    17                5
    102               6
    66                77

I want to re-order this table into this :
IdEmploye    |     Order
    10                1
    17                2
    102               3
    66                4

How it's possible in SQL ?
Thanks !

A: SQL Server supports the use of ROW_NUMBER(), so this will get you there.
UPDATE tbl
SET [Order] = sub.NewOrder
from tbl
JOIN
(select IdEmploye, ROW_NUMBER() OVER (ORDER BY IdEmploye) as NewOrder
 from tbl) as sub
 ON sub.IdEmploye = tbl.IdEmploye;

A: You can use CTE :
with empupdt as (
     select e.*, row_number() over (order by IdEmployee) as seq
     from employee e
)
update empupdt
     set Order = seq;

A: You can do a straight update
Update tbl
Set Order = IdEmploye


text:
Q: Scala pattern matching variable binding with auto type conversion In scala we can pattern match on types. So is it possible to bind a variable to the matched pattern with the type. Right now the bounded variable has type Any
val a: Any = "hello"
a match {
     case v @ String {
          v.length() // not working
     }
}

A: Your syntax is not correct!!!, it should be like:
val a: Any = "hello"
a match {
     case v: String => v.length()
}

use : to match type, and => with the next block

A: To pattern match on a type follow the syntax exposed in @chengpohi .
The bind operator @ is used to refer to a (sub)structure of the data extracted in pattern matching. For example in
("hello",123) match {
  case t @ (fst: String, snd: Int) => println(s"got tuple $t")
  case _                           =>
}

label t refers to the entire tuple, not having to denote fst and snd.


text:
Q: Cannot compare BCRYPT passwords I am following the guide in this website http://www.gregboggs.com/php-blowfish-random-salted-passwords/ but for some reason when checking if password are the same it fails.
The html is simple, 2 forms one for creating accounts and then one for checking. code can be seen here http://jsfiddle.net/Xf2Tc/
As output i get:
salt = salt in database
password in database: $2a$05$BcTDz3GVPJrLH3YRPF9FZ.uRBssr0ncQ4exG4/EtmnJ7Fz2CkoVha
but the re-ENCRYPTED password is always something REALLY REALLY small.
BcPgSBqZz80dw
I must be using the salt wrong or something.
If someoen can edit to be more organized, i would appreciate it.
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
    $hostname="exampleHost";
    $database="exampleDB";
    $username="exampleUsername";
    $password="examplePassword";
    if(isset($_POST['Upassword'])&&isset($_POST['account'])&&!empty($_POST['Upassword'])&&!empty($_POST['account']))    {
        try {
            $pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

            $Upassword = mysql_real_escape_string($_POST['Upassword']);
            $account = mysql_real_escape_string($_POST['account']);

            //This string tells crypt to use blowfish for 5 rounds.
            $Blowfish_Pre = '$2a$05$';
            $Blowfish_End = '$';

            $Allowed_Chars ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789./';
        $Chars_Len = 63;

            // 18 would be secure as well.
            $Salt_Length = 21;

            $mysql_date = date( 'Y-m-d' );
            $salt = "";

            for($i=0; $i<$Salt_Length; $i++)
            {
                $salt .= $Allowed_Chars[mt_rand(0,$Chars_Len)];
            }
            $bcrypt_salt = $Blowfish_Pre . $salt . $Blowfish_End;

            $hashed_password = crypt($Upassword, $bcrypt_salt);
            $stmt = $pdo->prepare("INSERT INTO users (reg_date, account, salt, password) VALUES (:mysql_date, :account, :salt, :hashed_password)");
            $stmt->bindParam(':mysql_date', $mysql_date, PDO::PARAM_STR);
            $stmt->bindParam(':salt', $salt, PDO::PARAM_STR);
            $stmt->bindParam(':account', $_POST['account'], PDO::PARAM_STR);
            $stmt->bindParam(':hashed_password', $hashed_password, PDO::PARAM_STR);
            $stmt->execute();
        } catch(PDOException $e) {
            //file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
            echo 'ERROR: ' . $e->getMessage();
        }
    }
            /*
                * to test for correct encryption
                *
            */
                  if(isset($_POST['Upassword2'])&&isset($_POST['account2'])&&!empty($_POST['Upassword2'])&&!empty($_POST['account2']))  {
    try {
        $pdo = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
        $stmt = $pdo->prepare("SELECT salt, password FROM users WHERE account=:account");
        $stmt->bindParam(':account', $_POST['account2'], PDO::PARAM_STR);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $Upassword2 = mysql_real_escape_string($_POST['Upassword2']);
        echo $row['salt'];
        $bcrypt_salt = $Blowfish_Pre . $row['salt'] . $Blowfish_End;
        $hashed_password = crypt($Upassword2, $bcrypt_salt);

        echo "PassDB: " .  $row['password'];
        echo '-------------------------------------------';
        echo "result: " .  $hashed_password;
            echo '-------------------------------------------';
        if ($hashed_password == $row['password']) {
          echo 'Password verified!';
          }
          echo 'i am here';

    } catch(PDOException $e) {
    //file_put_contents('PDOErrors.txt', $e->getMessage(), FILE_APPEND);
    echo 'ERROR: ' . $e->getMessage();
    }
}
?>

A: As you see I am separating my code into 2 if statements, meaning my Blowfish_Pre and $Blowfish_End were not being set when checking for correct password.
Solution either set this variables before the if statement or to use set them twice.
Hope it helps someone.


text:
Q: Separate semicolon separated values in Pandas Data Frame I am using Pandas to separate the semicolon separated values in a column. But there are more or less values in each row. For example:
row1: SVANN=TANDEM; SVTYPE=DEL; SVLENGTH=500

row2: IMPRECISE; SVANN=TANDEM; SV TYPE=INS; SVLENGTH= 300

How to separate these semicolon values into separate coulmns.
I tried the following steps but the values are misplaced:
df_checknew = pd.read_excel("annotated.xlsx")
df_checknew['INFO'] = df_checknew['INFO'].str.split(';')
df_new = pd.DataFrame(df_checknew['INFO'].tolist()).fillna('')
df = pd.concat([df_checknew, df_new], axis=1)

INFO is the column with many semicolon separated values. df_new has column names 0, 1,2 and 3 and the values are misplaced in each column. In df the column names are missing
Example:
##input
 ## values are misplaced because of the variable fish
 ##output
Thanks


text:
Q: No items displayed in list in tab I'm developing an app for ubuntu touch and I have tabs there. In one of them there is a list.
if I have this it don't show me any of items.
        Tab {
        objectName: "Tab3"

        title: i18n.tr("List")

        page: Page {
            ListView {

            ListItem.Subtitled {
                    text: "Item One"
                    subText: "21 m \t North"
                }
            ListItem.Subtitled {
                    text: "2nd item"
                    subText: "2.61 km \t South"
                }
            }
        }
    }

Where is the mistake? Thanks very much.

A: ListViews get data from a ListModel, you don't directly add ListItems to them.  See http://qt-project.org/doc/qt-5.0/qtquick/qml-qtquick2-listview.html#model-prop for more information about that.
A ListItem.* is used on the delegate property of your ListView, and will be used as kind of a template component, a new copy will be made for each item in your ListModel


text:
Q: Plotting a jqPlot in Symfony2 Hi and thanks for all your answers.
My problem is that I want to use the jqPlot library in my webapp which Im developing using the framework Symfony2.
Here goes my view:

 {% javascripts '@PreditBundle/Resources/public/js/*'  %}

{% endjavascripts %}

test

  {% javascripts '@PreditBundle/Resources/public/js/*'  %}

  {% endjavascripts %}

the problem is that when I render my view the graphic is not plotted although the graph is there when I check it on "view source code".
UPDATE: I just check the code several times and I think it is no problem of the code. Could it be a symfony problem? An Internet navigator config problem (I'm using Chrome)
UPDATE2: In the javascript console of Google Chrome i have these error messages "Uncaught ReferenceError: $ is not defined test:21
(anonymous function)"
UPDATE3: This is the same code I used in a .html file I've created and it works so I think that the problem is related to the Symfony2 framework. I guess now this is a question that any person who has worked with symfony and included javascript code can easyly answer

A: Ok the problem was the way I include the .js files. Instead of :
{% javascripts '@PreditBundle/Resources/public/js/*'  %}

{% endjavascripts %}

The CORRECT way to do it is :
{% javascripts '@PreditBundle/Resources/public/js/jquery.min.js'
               '@PreditBundle/Resources/public/js/jquery.jqplot.min.js'
               '@PreditBundle/Resources/public/js/plugins/jqplot.cursor.min.js'
               '@PreditBundle/Resources/public/js/plugins/jqplot.dateAxisRenderer.min.js'
               '@PreditBundle/Resources/public/js/plugins/jqplot.logAxisRenderer.min.js'
               '@PreditBundle/Resources/public/js/plugins/jqplot.canvasTextRenderer.min.js'
               '@PreditBundle/Resources/public/js/plugins/jqplot.canvasAxisTickRenderer.min.js' %}

{% endjavascripts %}


text:
Q: How to get a sum of some closures 2 simple functions with escaping closures
func A(closure: @escaping (Int) -> () {
       //some delay
         closure(value1)
    }

func B(closure: @escaping (Int) -> () {
   //some delay
     closure(value2)
}

In other function I need to get sum of value1 and value2
for example
func sum(completion: @escaping: (Int)->()){
     A(closure: { value1 in
        B(closure: { value2 in
           sum = value1 + value2
           completion(sum)
        })
     })
}

But I don't understand what to do if I need to sum results of many functions

A: You can use DispatchGroup
    func a(closure: @escaping (Int) -> ()) {
       //some delay
         closure(value1)
    }

    func b(closure: @escaping (Int) -> ()) {
       //some delay
         closure(value2)
    }

    func c(closure: @escaping (Int) -> ()) {
       //some delay
         closure(value3)
    }

    func sum(completion: @escaping: (Int)->()){
        let g = DispatchGroup()
        var sum = 0
         g.enter()
         a(closure: { value1 in
            sum += value1
            g.leave()
         })
         g.enter()
        b(closure: { value2 in
           sum += value2
           g.leave()
        })
         g.enter()
        c(closure: { value3 in
           sum += value3
           g.leave()
        })

        g.notify(queue: .main) {
            completion(sum)
        }

    }


text:
Q: Indexing Hash Bang #! Content Using Google Search Appliance (GSA) Has anyone had success indexing content that contains #! (Hashbang) in the URL? If so, how did you do it?
We have a third party help center of ours that we are hosting that requires the use of #! in the URL, however, we need the ability to index this content within our GSA. We are using version 7.0.14.G.238 of our GSA
Here's an example of one of our help articles with a hashbang in the URL:

/templates/selfservice/example/#!portal/201500000001006/article/201500000006039/Resume-and-Cover-Letter-Reviews

I understand #! requires JavaScript, not the most friendly SEO in the world and many popular sites (Facebook, Twitter, etc.) deprecated the use of it.

A: While some Javascript content is indexed, if you want to make sure there is absolutely content in the index for this site you have two options. Either make sure the site is non-JS friendly which is supported in a lot of JS frontend sites, or alternatively use a content feed to push the data into the GSA instead. Turn off JS in your browser and access the site and see if content links are created.
If you have access to the database, you could just send the content straight in, however read up here: http://www.google.com/support/enterprise/static/gsa/docs/admin/72/gsa_doc_set/feedsguide/ on feeds which can send data straight in, or possibly read up on connectors in general https://support.google.com/gsa/topic/2721859?hl=en&ref_topic=2707841


text:
Q: Reprojection WFS GeoJSON I need to display my layer from geoserver on the map. I have problems with the projection system (EPSG:7749). I can't change the projection system with proj4 in my vector layer. I chose GeoJSON format because I will need to build a filter for the feature of my layer. Someone can help me?
`
proj4.defs('EPSG:7749', '+proj=aea +lat_1=34.0733 +lat_2=34.3833 +lat_0=34.2283 +lon_0=-112.7915 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs');
    ol.proj.proj4.register(proj4);
    console.log("Console: " + ol.proj.get('EPSG:7749'));
    var test = ol.proj.get('EPSG:7749');

    var urltest = 'http://myGeoserverIP/geoserver/ows?service=WFS&version=1.1.0&request=GetFeature&typeName=myworkspace:201910081246140571_Perimeters&outputFormat=application%2Fjson';

    var vectorSource = new ol.source.Vector({
        format: new ol.format.GeoJSON(),
        projection: test,
        url: urltest,
    });

    var vector = new ol.layer.Vector({
        source: vectorSource,
    });

    var raster = new ol.layer.Tile({
        source: new ol.source.OSM()
    });
    var map = new ol.Map({
        layers: [raster, vector],
        target: 'map',
        view: new ol.View({
            projection: test,
            center: [-8908887.277395891, 5381918.072437216],
            maxZoom: 19,
            zoom: 3
        })
    });

`


text:
Q: Storing a Variable in a .dat file I am writing a simple batch script to compare what the user enters, to a line of text in a .dat (I can put it in a .txt file if necessary).
So far, I have a way of getting the user's input, using set:
set /P username=Please enter your Username:
set /P given_password=Please enter your Password:

And the program navigates to the correct directory using cd:
cd C:\Users\Luke\Desktop\Dropbox\BATCH SERVER\USERS\%login_username%\

But now I need a way of reading the contents of the .dat file, and comparing it to what the user inputed (given_password)
Thanks in advance for any help,
-Luke
Edit:
More info on the .dat file:
The file is called config.dat. & is formatted like this, where Geronimo is the correct password.
password = Geronimo

I also plan to have other information stored in there, which I also would like to assign to variables later on in the script.

A: you can parse the file like this:
for /f "tokens=1,2 delims== " %%i in ('findstr "=" "ini.dat"') do set "%%i=%%j"

findstr "=" "ini.dat" will process only lines, that have  = in it. So you can store also Comments in the file like this:
This is the dat file
ist stores the username
user = Luke
and the password
password = Geronimo
and some other stuff...

EDIT:
for is used to do the same thing on several objects. For more info see for /?
Especially here:
findstr "=" "ini.dat finds all lines in the file ini.dat that contains =
The single qoutes around it ' tells the forcommand to process the output of that command.
in (...) says: "For every of those found lines"
"tokens=1,2 delims== " says: "Take the first and second part (called "token") where they are separated by = or SPACE". (consecutive delimitors are treated as one)
The first part (Token) is assigned to a special variable %%i. As there is a second token, it is assigned to the following letter: %%j
/f tells the forcommand which syntax to use (see for /? for other possibilities)
in (...) says: "For every of those found lines"
do set %%i=%%j sets the variable (Token1 (= %%i ) to Token2 (= %%j)
Mona's way is better to understand and the preferable way, if there is only one "data" in the file. If there are more datasets (as you asked "I also plan to have other information stored in there") a forloop is the better way to go.
I know, this is hard stuff to understand, but it's worth the time spent. Try it with echo on, so you can see better, what it does.

A: If the .dat file simply contains one line defining the password to compare to, your batch file could simple be:
set /p "uname=Username: "
set /p "pass=Password: "
set /p comparepass=< "C:\Users\Luke\Desktop\Dropbox\BATCH SERVER\USERS\%login_username%\NAME.dat"
if "%pass%"=="%comparepass%" (
:: Insert code for when passwords are the same
) else (
:: Insert code for when passwords are not the same
)

And that should help you out.
Mona


text:
Q: Favourite Colour: Myrtle At work we use confluence.
On occasion it crashes, resulting in an error 500 page being generated.
This page includes some interesting reference information, including:

System Information:
  favouriteColour: Myrtle
  javaRuntime: Java(TM) SE Runtime Environment
  jvmVersion: 1.0
  operatingSystem: Linux 2.6.18-92.1.13.el5
  ...

Myrtle?
Many thoughts raged through my head. What's Myrtle? Why is it my favourite colour? Is it my favourite colour? Why does that particular tidbit of information require its own system property?
At first I assumed it was just something that someone at work had done. A remnant of a project long forgotten, an old April Fools joke perhaps?
It seems I was mistaken. In fact, even Atlassian acknowledges the colour, though they give no reason for its existence.
Now, I know what you're thinking? Who cares?
I do, gentle reader, I do. And you should too. It's little mysteries like this that make life worth living.
So, is there one among you who knows the secret of The Mysterious Myrtle uh.. Mystery? At least one inquiring mind wants to know..

A: This looks like an obfuscation of their version or the error number.
You're not supposed to give your exact version away when selling corporate enterprise systems - it supposedly makes it easier for hackers to know what vulnerabilities to hit.
However they still want to be able to know what version you're on or what error id you got when you call for technical assistance, so they have a code word for each release.
I suppose the colours run out pretty quickly.

A: Maybe it's something incredibly fundamental to programming - like pi for math, 42 for the universe, or the L-unit for space travel (as we all know, without it, space travel is but the fevered dream of a madman).
We can only guess.

A: Your Confluence System Favourite Colour (Australian spelling FTW) is also available from Admin -> System Info.
And if I told you any more, I'd have to kill you.

A: FWIW, I've frequently put "interesting" information in error dumps -- I've found it's easier to get people to report it in bug reports, and they're more likely to accurately report something like "myrtle" as opposed to "error #47" or whatever...


text:
Q: Differentiating an infinite series in Hilbert space Suppose $H$ is separable Hilbert space and $w_j$ is a basis. Suppose we have $h=\sum a_j(t)w_j$ an infinite sum where the coefficients are functions of $t$. The sum makes sense in the sense that the partial sums converge to $h$. When are we allowed to differentiate term by term and write $h'=\sum a_j'(t)w_j$?
Also, how about if the basis functions depended on $t$ too?


text:
Q: Python Requests — Throttle upload speed NOTE: This is not a duplicate, rate limiting uploads and downloads are totally different and many libs I've seen can rate limit downloads but not uploads. This should be reopened.
I'm running a large file upload (2.8 GB) in Python, the code I'm using looks roughly like this:
files = {'md5': ('', md5hash),
         'modified': ('', now),
         'created': ('', now),
         'file': (os.path.basename(url), fileobject, 'application/octet-stream')}
m = requests_toolbelt.MultipartEncoder(fields=files)
headers['content-type'] = m.content_type
r = s.post(url, data=m, params=params, headers=headers)

When I run this code, everything else on my network just stops working. Websites stop working, etc. My guess would be that Python is saturating my router's TCP packet buffer or something. This behavior will be well known to anyone who has tried running a BitTorrent client without specifying limits on their upload speed.
Is there any way I can throttle the upload speed so my users won't have their network destroyed?


text:
Q: Can I get certificates for other recipients of an encrypted email? I run into this problem fairly often at work using Outlook. There is an email thread going and someone decides to encrypt their response to the group (sometimes justified, sometimes not). Now I want to Reply-All to continue the conversation, but I don't have the certificates for half of the recipients.
Is there a way to get the public certificates for all recipients on an encrypted email, or is that just an impossibility? Clearly the sender would have needed them all to encrypt the first email, but I don't know if those public certificates are included and visible to all other recipients as well.

A: It depends on the owner of the public/private key pair, everyone can choose for themselves on how to distribute the public key (see here). There is no general answer here.
Worst case the public keys have not been publicly published, then you'll have to ask the sender for his/her public key. I used to attach my public key in my messages - which is sort of (very) unsecure since it leaves quite a bit of room for different attack types. Therefore I don't think this option is used as an automatic key exchange, but I'm not 100% sure.
I assume Outlook just sends an encrypted message to people it knows the public key and to everyone else it sends an unencrypted message (you can probable tell Outlook what to do via some kind of setting). But I'm guessing here, I never used this Outlook feature.
Note: if it's a work environment, the public keys are probable handled by a server, and integrated into the exchange server thus integrated in Outlook, you might want to ask your IT department. Or just ask a person who did send out the encrypted email on how they did it.
Note2: Assuming the mail you are getting actually is a multi-key encrypted mail (some background info here and here) - which wasn't 100% clear without the comments (could have been a shared private key as well)
This answer was edited according to the new info from the comments.

A: The message does not carry the recipients' actual certificates – it includes only enough information to allow them to identify themselves as recipients, but most likely not enough information for you or someone else to download them.
For example, in S/MIME, the 'RecipientInfo' field only includes the certificate's issuer + serial number, or the certificate's "subject key identifier" (public key hash), but not the actual public key, let alone the actual certificate. (See here and here.)
(In the idealized OSI world, issuer + serial number would be sufficient to retrieve the certificate from "The Directory" via X.500 or LDAP, in reality not so much. Although if the recipients are within the same Active Directory system their certificates could be stored in their AD user account objects.)
Likewise, in OpenPGP, the 'Public-Key Encrypted Session Key' packet only includes a 64-bit key ID of the specific encryption subkey that's necessary to decrypt the message – not even the full fingerprint.
The key ID can be searched on various public keyservers, although it's too short to be used for serious verification (by now it is possible to generate keys with chosen 64-bit key IDs).

A: To send encrypted to one or more recipients, you must have the
public key of each recipient stored in his contact information.
You may save in Outlook the public key of any of your contacts
this way:

*

*Request that the contact send you a signed e-mail.
An indicator will appear on the e-mail to indicate it is signed.

*Right-click on the sender's name and click "Add to Outlook Contacts"
(even if he is already a contact)

*Enter the details of the new contact and click Save.
If they are an existing contact, choose "Yes" to update the
contact details.
Note: When you add or update a contact directly from
a signed e-mail, Outlook will pull in the sender's public key
and associate it with the contact details.
Now when you send an encrypted e-mail, it will know
what certificate to use for the recipient.


text:
Q: CSS In Handlebars Layout Does Not Apply to Body I am using express-handlebars in my node.js project. I have included CSS and JS files in the  section of my handlebars layout. The problem is, the CSS only gets applied to the   part of the code and NOT to the . If I link the CSS within the body tags of the layout file, it still doesn't work. The only way I can get it to come out right is if I link the CSS in each "body" file that gets inserted into the layout. I am using bootstrap if that matters.
I'm somewhat new to using handlebars but I can't find anything like this online, so hopefully someone here knows what the issue is.
Here is my layout.handlebars file:
    <link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.css"/>

    <link rel="stylesheet" type="text/css" href="/css/main.css"/>

                <button type="button" className="navbar-toggle"
                    data-toggle="collapse" data-target="#my-navbar">

                </button>
                 Home

  Messenger

  Contact

  Login

  Register

    {{{ body }}}

And here is the "body" handlebars file:

        Welcome.

I want to link the CSS files in the layout and have it applied to all the content. I do know the CSS is loaded because it is changing the font and background color, so it's not a problem with the path.

A: I had previsouly been using react instead of handlebars, and all my css "class" tags were changed to "className". Changing it back fixes everyting.


text:
Q: How to use push notification with a react created with create-react-app The problem is how to add to the sw.js so that it can speak with the rest of my code.
I need it because each time that a notification arrives I need to do all sorts of changes to the indexeddb.
If needed I'm ready to eject the app.


text:
Q: Having trouble understanding csv.reader Python newbie here so excuse my ignorance. I'm working with the Google Analytics Reporting API (v4) and Google Search Console API using scripts I found from Google and this site.
The script tries to get basic analytics data like clicks and impressions both by page and by query and saves it into a csv file. Because this data is spread across 2 APIs the script fetches and saves the data separately and then uses a function update_file(flags) to combine the contents of 4 csv files. For example, one file has a list of all Google Search queries that generated impressions for the site in question. Flags here are the command-line arguments - site URL, start date, and end date.
def update_file(flags):
  #Combining all the data previously collected and stored in 3 seperate csv files into one global csv file
  print("Merging files")
  basic_url = flags.property_uri
  basic_url = basic_url.replace("://","_")
  basic_url = basic_url.replace(".","-")

  matchfile ="Landingpage_analytics_"+flags.start_date+"_"+flags.end_date+"_"+basic_url+".csv"

  matchfile2 ='Landingpage_'+flags.start_date+"_"+flags.end_date+"_"+basic_url+".csv"
  matchfile3 ="Keyword_"+flags.start_date+"_"+flags.end_date+"_"+basic_url+".csv"
  csvfile="Landingpage_keyword_"+basic_url+"_"+flags.start_date+"_"+flags.end_date+".csv"
  newfile="Global_report_"+basic_url+"_"+flags.start_date+"_"+flags.end_date+".csv"
  print(matchfile)
  print(matchfile2)
  print(matchfile3)
  new_data=[]
  new_data2=[]
  new_data3=[]
  with open(csvfile) as fin, open(matchfile) as fmatch, open(matchfile2) as fmatch2,
       open(matchfile3) as fmatch3, open(newfile,'w') as fout:
    reader = csv.reader(fin)
    checker = csv.reader(fmatch)
    checker2 = csv.reader(fmatch2)
    checker3 = csv.reader(fmatch3)
    writer = csv.writer(fout)
    header_reader = next(reader)
    next(checker)
    next(checker2)
    next(checker3)
    header_checker =["Clicks Keyword", "Impressions Keyword","Avg. Pos. Keyword","CTR Keyword",
                     "Clicks Landingpage","Impressions Landingpage","Avg. Pos. Landingpage",
                     "CTR Landingpage","GA Sessions","GA Bouncerate","GA Avg session duration","GA Avg. Pages/Session"]
    new_header = header_reader + header_checker
    writer.writerow(new_header)
    analytics = {}
    keyword = {}
    landingpage = {}

    for a in checker3:
      keyword[a[0]]=[a[2],a[1],a[3],float(a[2])/float(a[1])]

    for b in checker2:
      landingpage[b[0]]=[b[2],b[1],b[3],float(b[2])/float(b[1])]

    for xl in checker:
      url = flags.property_uri+xl[0]
      analytics[url] = [xl[1],float(xl[2])/float(xl[1]),xl[3],xl[4]]

    for i in reader:
      if i[0] in keyword:
        newrow = i + keyword[i[0]]
      else:
        # if keyword doesn't have specific data
        newrow = i + ['N/A', 'N/A', 'N/A', 'N/A']
      new_data.append(newrow)

    for i in new_data:
      if i[1] in landingpage:
        newrow = i + landingpage[i[1]]
      else:
        # if landingpage doesn't have specific data
        newrow = i + ['N/A', 'N/A', 'N/A', 'N/A']
      new_data2.append(newrow)

    for i in new_data2:
      if i[1] in analytics:
        newrow = i + analytics[i[1]]
        new_data3.append(newrow)

    new_data3.sort(key=lambda row: float(row[2]), reverse=True)
    writer.writerows(new_data3)

The update_file(flags) function is not working and is generating an empty file. I tried debugging and discovered that the file referenced by matchfile, fmatch, and the csv reader checker has content before update_file(flags) is run, but is empty after.
for xl in checker:
      url = flags.property_uri+xl[0]
      analytics[url] = [xl[1],float(xl[2])/float(xl[1]),xl[3],xl[4]]

analytics stays empty after these lines, but keyword and landingpage contain the right data and use similar code. I'm not sure what's going on. Is there something I'm missing that could be causing these files to return empty?


text:
Q: cargo generate using ssh results in: Git Error: Failed to authenticate SSH session: ; class=Ssh (23) I'm currently struggling getting cargo-generate to work properly with ssh.
Generating from github using https works fine.
I have no issues using git by itselve as well, but for some obscure reason cargo generate does not play nicely with it.
Here is the error I am presented with, after trying to clone a simple template of mine:
cargo generate git@github.com:VirtualNonsense/rust_bluepill_minimal_template.git
 Using application config: C:\Users\VirtualNonsense\.cargo\cargo-generate.toml
 Using ssh-identity from application config: $HOME/.ssh/id_rsa
 Favorite git@github.com:VirtualNonsense/rust_bluepill_minimal_template.git not found in config, using it as a git repo url
 Using private key: `%userprofile%\.ssh\id_rsa` for git-ssh checkout
Error:  Git Error: Failed to authenticate SSH session: ; class=Ssh (23)

My cargo-generate.toml file consists only of the following lines:
[defaults]
ssh_identity = "$HOME/.ssh/id_rsa"

I've seen that there seems to be an issue with passphrase protected keys so I made sure mine does not have one. I also tied an ed25519 key but it did not change the result as well.
I feel like I'm missing something obvious and would appreciate some guidance


text:
Q: What values are stored in the padding bytes of an aligned struct/class object
struct Data
{
    std::uint32_t b;
    char a;
};

The Data type is aligned by 4 bytes, so sizeof(Data) == 8.
But what the values are in 5th-7th bytes? Is it default zero?

A: It actually depends on a few things, all detailed in the C++ standard [dcl.init].
The various sections of that end up either default-initialising, zero-initialising or value-initialising depending on the storage duration, presence of various types of constructors, and so on.
Default initialising means the entire variable will be some arbitrary value while zero initialising zero-initialises all members and sets padding bytes to zero.
So Data d1; and static Data d2; will not necessarily have the same padding bytes.
Value initialising is a little more complex since it effectively first chooses default or zero initialisation before calling the constructor (if one exists).

But the bottom line is that it probably shouldn't matter. If the content of padding was important, you should be "registering" that space as real member variables so that you can use them (and have them properly initialised). Padding is very much unimportant in the "value" of a variable unless you do something crazy like memcmp it, or run a checksum over the entire memory block it occupies :-)

A: I always believe it's unpredictable but still unsure in case of the object of the struct has static storage duration.
So I have made a search to see whether there is a clear mention about this in C standards and C++ standards or not (since you are asking in C and C++).
It is mentioned in C standards (C99, C11 and C18):

J.1    Unspecified behavior

*

*The value of padding bytes when storing values in structures or unions (6.2.6.1).

For C++, I could not find out it's mentioned anywhere in C++ standards.


text:
Q: Trying to load messages from Azure Service Bus to ADLS with Apache Spark Databricks I am trying to move messages in Azure Service Bus queues to ADLS with Databricks.
The code that I'm using is as follows:
from azure.servicebus import ServiceBusClient, ServiceBusMessage

CONNECTION_STR = "Endpoint=sb://carlsbus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=2BIOtFdooJFIkhZF0qxtYEoK32hJa39DseStw="

QUEUE_NAME = "myqueue"

servicebus_client = ServiceBusClient.from_connection_string(conn_str=CONNECTION_STR, logging_enable=True)

receiver = servicebus_client.get_queue_receiver(queue_name=QUEUE_NAME, max_wait_time=5)

And when I execute the following:
mystream2 = spark.readStream.format(receiver).load("/mnt/lake/RAW/FormulaClassification/F1Area/F1Domain/flightStream/1")

But I keep on getting the error:
'ServiceBusReceivedMessage' object has no attribute '_get_object_id'

Any thoughts why I'm getting the error?

A:
Error - 'ServiceBusReceivedMessage' object has no attribute '_get_object_id'

Above error occurs when you try to use dataframe inside a function. In your case you have used receiver inside format() function.
You can not use dataframe inside function.
For more information Follow this SO thread and this article


text:
Q: Galois correspondence in infinite extension Definition of Galois extension: An extension $K$ of $F$ will be called Galois, if it is algebraic (edited after comment by Thorgott) and the fixed subfield under all $F$-automorphisms of $K$ is precisely $F$.
Let $L/k$ be Galois.
For $k\subset M\subset L$ (intermediate subfield), $L/M$ is Galois and  ${\rm Gal}(L/M)$ is subgroup of ${\rm Gal}(L/k)$.
Claim: The association $M\mapsto {\rm Gal}(L/M)$ is one-one i.e. injective (even if $[L:k]$ is infinite).
Justification: If $\mathcal{M}$ is the collection of subfields of $L$ (containing $k$) and $\mathcal{H}$ is the collection of subgroups of ${\rm Gal}(L/k)$, then we have mappings between them as:
$$
M\mapsto {\rm Gal}(L/M) \,\,\,\,\, and \,\,\,\, H\mapsto L^H=\mbox{subfield of L fixed by H }
$$
Given $M\in\mathcal{M}$, the subfield of $L$ fixed under ${\rm Gal}(L/M)$ contains $M$, but it is exactly $M$ since $L$ is Galois over $M$. This means the composition
$$
M\mapsto {\rm Gal}(L/M)\mapsto L^{{\rm Gal}(L/M)}
$$
is identity, hence passing from $\mathcal{M}$ to $\mathcal{H}$ in natural way is always $1-1$ map.
Question: Is the above claim with justification correct? (If not, what corrections should I do? I did not find mention of simple remark in books, so worried of above thought.)


text:
Q: Upload Button in meta box not opening library First, thank you for your help.
I have created a custom template, added two metaboxes in Pages using a 'Page_Fiche_Metier.php' template.
One meta box is to upload an image. But the Upload Button is not opening the media library, although I have added the jQuery script.
Here is the code for the meta-boxes.php

    <?php

function prfx_custom_meta(){
  global $post;
    if ( 'page_fiche_metier.php' == get_post_meta( $post->ID, '_wp_page_template', true ) ) {
    add_meta_box( 'prfx_meta', __( 'Vidéo Présentation Bas de Page', 'prfx-textdomain' ), 'prfx_meta_callback', 'page' );
  }
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );

function prfx_meta_callback( $post ) {
    wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
    $prfx_stored_meta = get_post_meta( $post->ID );
    ?>

        <?php _e( 'Titre', 'prfx-textdomain' )?>
        <input type="text" name="meta-text" id="meta-text" value="<?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?>" />

        <?php _e( 'URL', 'prfx-textdomain' )?>
        <input type="text" name="meta-url" id="meta-url" value="<?php if ( isset ( $prfx_stored_meta['meta-url'] ) ) echo $prfx_stored_meta['meta-url'][0]; ?>" />

        <?php _e( 'Example File Upload', 'prfx-textdomain' )?>
        <input type="text" name="meta-image" id="meta-image" value="<?php if ( isset ( $prfx_stored_meta['meta-image'] ) ) echo $prfx_stored_meta[
        'meta-image'][0]; ?>" />
        <input type="button" id="meta-image-button" class="button" value="<?php _e( 'Choisir un fichier', 'prfx-textdomain' )?>" />

    <?php
}

function prfx_meta_save( $post_id ) {

    // Checks save status
    $is_autosave = wp_is_post_autosave( $post_id );
    $is_revision = wp_is_post_revision( $post_id );
    $is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';

    // Exits script depending on save status
    if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
        return;
    }

    if( isset( $_POST[ 'meta-text' ] ) ) {
        update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
    }

    if( isset( $_POST[ 'meta-url' ] ) ) {
        update_post_meta( $post_id, 'meta-url', sanitize_text_field( $_POST[ 'meta-url' ] ) );
    }

    if( isset( $_POST[ 'meta-image' ] ) ) {
    update_post_meta( $post_id, 'meta-image', $_POST[ 'meta-image' ] );
    }

}
add_action( 'save_post', 'prfx_meta_save' );

function prfx_image_enqueue() {
    global $typenow;
    if( $typenow == 'post' ) {
        wp_enqueue_media();

        // Registers and enqueues the required javascript.
        wp_register_script( 'meta-box-image', plugin_dir_url( __FILE__ ) . 'meta-box-image.js', array( 'jquery' ) );
        wp_localize_script( 'meta-box-image', 'meta_image',
            array(
                'title' => __( 'Choose or Upload an Image', 'prfx-textdomain' ),
                'button' => __( 'Use this image', 'prfx-textdomain' ),
            )
        );
        wp_enqueue_script( 'meta-box-image' );
    }
}
    add_action( 'admin_enqueue_scripts', 'prfx_image_enqueue' );

And the code for js:
/*
 * Attaches the image uploader to the input field
 */
jQuery(document).ready(function($){

    // Instantiates the variable that holds the media library frame.
    var meta_image_frame;

    // Runs when the image button is clicked.
    $('#meta-image-button').click(function(e){

        // Prevents the default action from occuring.
        e.preventDefault();

        // If the frame already exists, re-open it.
        if ( meta_image_frame ) {
            meta_image_frame.open();
            return;
        }

        // Sets up the media library frame
        meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
            title: meta_image.title,
            button: { text:  meta_image.button },
            library: { type: 'image' }
        });

        // Runs when an image is selected.
        meta_image_frame.on('select', function(){

            // Grabs the attachment selection and creates a JSON representation of the model.
            var media_attachment = meta_image_frame.state().get('selection').first().toJSON();

            // Sends the attachment URL to our custom image input field.
            $('#meta-image').val(media_attachment.url);
        });

        // Opens the media library frame.
        meta_image_frame.open();
    });
});

A: You mentioned that you've added the meta box for pages:

I have created a custom template, added two metaboxes in Pages using a
  'Page_Fiche_Metier.php' template.

However, in prfx_image_enqueue(), the code only runs if the post type is post. Changing prfx_image_enqueue() so that it checks for the page post type will fix the issue.
function prfx_image_enqueue() {
    global $typenow;
    if ( $typenow == 'page' ) {
        wp_enqueue_media();

        // Registers and enqueues the required javascript.
        wp_register_script( 'meta-box-image', plugin_dir_url( __FILE__ ) . 'meta-box-image.js', array( 'jquery' ) );
        wp_localize_script( 'meta-box-image', 'meta_image',
                array(
                        'title' => __( 'Choose or Upload an Image', 'prfx-textdomain' ),
                        'button' => __( 'Use this image', 'prfx-textdomain' ),
                )
        );
        wp_enqueue_script( 'meta-box-image' );
    }
}
add_action( 'admin_enqueue_scripts', 'prfx_image_enqueue' );

A: Thank you for your response.
I found the issue.
The path "plugin_dir_url( FILE ) . 'meta-box-image.js' " was not the correct one. I just changed to the correct directory!
Best


text:
Q: Why does the confidence boundary contain fewer points than expected in R (`ggplot`)? I use a LOESS regression and draw a confidence boundary with a 99% level.
# R code
library(ggplot2)

ggplot(mtcars) +
  aes(x = mpg, y = disp) +
  geom_point() +
  geom_smooth(level = 0.99, method = "loess")

Why are there way fewer than 99% points in the confidence boundary? (7 points out of 32 are outside the confidence boundary).
Is it because it's only an estimate of the confidence boundary, and not the "real" one?

A: The reason this happens is because a confidence interval quantifies the uncertainty about a fixed parameter (here: the mean at a given point) rather than the sample. This means that as the number of observations grows bigger, the width of the confidence interval actually goes to $0$. In the limit, the proportion of data point inside the confidence interval goes to $0$ (see comments)!
A different way to quantify uncertainty of your data is by a prediction interval that additionally quantifies the uncertainty stemming from sampling variability.


text:
Q: VisualStateManager and generated transitions Just when I think I understand the VisualStateManager, something proves me wrong.
I'm using WPF 4 and am trying to simply enlarge an item on mouse over, and shrink it back on mouse leave. I figured I'd just define each state in a VisualStateGroup and then specify a VisualTransition with a GeneratedDuration:
<Border x:Name="PART_Root" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" RenderTransformOrigin="0.5,0.5">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup Name="CommonStates">
            <VisualStateGroup.Transitions>
                <VisualTransition GeneratedDuration="0:0:1"/>
            </VisualStateGroup.Transitions>

            <VisualState Name="Normal"/>

            <VisualState Name="MouseOver">
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="scaleTransform" Storyboard.TargetProperty="ScaleX" To="1.5" Duration="0"/>
                    <DoubleAnimation Storyboard.TargetName="scaleTransform" Storyboard.TargetProperty="ScaleY" To="1.5" Duration="0"/>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <Border.RenderTransform>
        <ScaleTransform x:Name="scaleTransform" ScaleX="1" ScaleY="1"/>
    </Border.RenderTransform>

    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>

Since I have a catch-all VisualTransition with a GeneratedDuration, I was expecting the VSM to generate intermediate animations. That is, mousing over the control should animate the ScaleTransform properties from 1 to 1.5 over the course of 1 second. Same with mousing off. Instead, there's a delay of 1 second and then the ScaleTransform properties instantly snap to 1.5 or back to 1.
If I manually specify transitions as follows then I get the desired behavior:
<VisualStateGroup.Transitions>
    <VisualTransition From="Normal" To="MouseOver">
        <Storyboard>
            <DoubleAnimation Storyboard.TargetName="scaleTransform" Storyboard.TargetProperty="ScaleX" To="1.5" Duration="{StaticResource MouseEnterDuration}"/>
            <DoubleAnimation Storyboard.TargetName="scaleTransform" Storyboard.TargetProperty="ScaleY" To="1.5" Duration="{StaticResource MouseEnterDuration}"/>
        </Storyboard>
    </VisualTransition>

    <VisualTransition From="MouseOver" To="Normal">
        <Storyboard>
            <DoubleAnimation Storyboard.TargetName="scaleTransform" Storyboard.TargetProperty="ScaleX" To="1" Duration="{StaticResource MouseLeaveDuration}"/>
            <DoubleAnimation Storyboard.TargetName="scaleTransform" Storyboard.TargetProperty="ScaleY" To="1" Duration="{StaticResource MouseLeaveDuration}"/>
        </Storyboard>
    </VisualTransition>
</VisualStateGroup.Transitions>

But why do I have to do this? I thought the whole point of generated transitions was that the transition would be, you know, generated. What am I misunderstanding here?
UPDATE: As per Rick's answer, Blend generates something that does work. Thus, working backwards I determined that it is indeed the fact that I'm referencing the ScaleTransform directly rather than through the UIElement that contains it. I changed my XAML to the following and it works as expected:
<Border x:Name="PART_Root" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" RenderTransformOrigin="0.5,0.5">
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup Name="CommonStates">
            <VisualStateGroup.Transitions>
                <VisualTransition From="Normal" To="MouseOver" GeneratedDuration="{StaticResource MouseEnterDuration}"/>

                <VisualTransition From="MouseOver" To="Normal" GeneratedDuration="{StaticResource MouseLeaveDuration}"/>
            </VisualStateGroup.Transitions>

            <VisualState Name="Normal"/>

            <VisualState Name="MouseOver">
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="PART_Root" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleX)" To="{StaticResource MouseOverScale}" Duration="0"/>
                    <DoubleAnimation Storyboard.TargetName="PART_Root" Storyboard.TargetProperty="(UIElement.RenderTransform).(ScaleTransform.ScaleY)" To="{StaticResource MouseOverScale}" Duration="0"/>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>

    <Border.RenderTransform>
        <ScaleTransform/>
    </Border.RenderTransform>

    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>

Seems ridiculous (and an obvious bug), but it works.
Thanks

A: I can't say that I fully understand why it doesn't work the way we'd expect it to, but in these situations we can use Expression Blend to perform the task and see what markup it produces.  I've done that and here's a working example based on your sample:
<Grid>
    <Grid.Resources>
        <Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="PART_Root" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" RenderTransformOrigin="0.5,0.5">
                            <Border.RenderTransform>
                                <TransformGroup>
                                    <ScaleTransform/>
                                    <SkewTransform/>
                                    <RotateTransform/>
                                    <TranslateTransform/>
                                </TransformGroup>
                            </Border.RenderTransform>
                            <VisualStateManager.VisualStateGroups>
                                <VisualStateGroup Name="CommonStates">
                                    <VisualStateGroup.Transitions>
                                        <VisualTransition GeneratedDuration="0:0:1"/>
                                    </VisualStateGroup.Transitions>
                                    <VisualState Name="Normal"/>
                                    <VisualState x:Name="MouseOver">
                                        <Storyboard>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="PART_Root">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="2"/>
                                            </DoubleAnimationUsingKeyFrames>
                                            <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" Storyboard.TargetName="PART_Root">
                                                <EasingDoubleKeyFrame KeyTime="0" Value="2"/>
                                            </DoubleAnimationUsingKeyFrames>
                                        </Storyboard>
                                    </VisualState>
                                </VisualStateGroup>
                            </VisualStateManager.VisualStateGroups>
                            <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Grid.Resources>
    <Button Content="Button" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Style="{StaticResource ButtonStyle1}"/>
</Grid>

Although Blend uses a more general transform group, the main difference we can see is that the storyboard targets an element and a property path through that element to the scaling factors.


text:
Q: Why can't the var keyword in Java be assigned a lambda expression? It is allowed to assign var in Java 10 with a string like:
var foo = "boo";

While it is not allowed to assign it with a lambda expression such as:
var predicateVar = apple -> apple.getColor().equals("red");

Why can't it infer a lambda or method reference type when it can infer the rest like String, ArrayList, user class, etc.?

A: This has nothing to do with var.  It has to do with whether a lambda has a standalone type.  The way var works is that it computes the standalone type of the initializer on the RHS, and infers that.
Since their introduction in Java 8, lambda expressions and method references have no standalone type -- they require a target type, which must be a functional interface.
If you try:
Object o = (String s) -> s.length();

you also get a type error, because the compiler has no idea what functional interface you intend to convert the lambda to.
Asking for inference with var just makes it harder, but since the easier question can't be answered, the harder one cannot either.
Note that you could provide a target type by other means (such as a cast) and then it would work:
var x = (Predicate<String>) s -> s.isEmpty();

because now the RHS has a standalone type.  But you are better off providing the target type by giving x a manifest type.

A: From the Local-Variable Type Inference JEP:

The inference process, substantially, just gives the variable the type of its initializer expression. Some subtleties:

*

*The initializer has no target type (because we haven't inferred it yet). Poly expressions that require such a type, like lambdas, method references, and array initializers, will trigger an error.

Because a lambda expression by itself does not have a type, it can not be inferred for var.

... Similarly, a default rule could be set.

Sure, you can come up with a way to work around this limitation. Why the developers made the decision not to do that is really up to speculation, unless someone who was part of the decision making can answer here. (Update: answered here.)  If you're interested anyway, you could ask about it on one of the openjdk mailing lists: http://mail.openjdk.java.net/mailman/listinfo
If I were to guess, they probably didn't want to tie lambda inference in the context of var to a specific set of functional interface types, which would exclude any third party functional interface types. A better solution would be to infer a generic function type (i.e. (Apple) -> boolean) that can than be converted to a compatible functional interface type. But the JVM does not have such function types, and the decision to not implement them was already made during the project that created lambda expressions. Again if you're interested in concrete reasons, ask the devs.

A: To answer this we have to go into details and understand what a lambda is and how it works.
First we should understand what a lambda is:
A lambda expression always implements a functional interface, so that when you have to supply a functional interface like Runnable, instead of having to create a whole new class that implements the interface, you can just use the lambda syntax to create a method that the functional interface requires. Keep in mind though that the lambda still has the type of the functional interface that it is implementing.
With that in mind, lets take this a step further:
This works great as in the case of Runnable, I can just create a new thread like this new Thread(()->{//put code to run here}); instead of creating a whole new object to implement the functional interface. This works since the compiler knows that Thread() takes an object of type Runnable, so it knows what type the lambda expression has to be.
However, in a case of assigning a lambda to a local variable, the compiler has no clue what functional interface this lambda is implementing so it can't infer what type var should be. Since maybe it's implementing a functional interface the user created or maybe it's the runnable interface, there is just no way to know.
This is why lambdas do not work with the var keyword.

A: As several people have already mentioned, what type should var infer and why should it?
The statement:
var predicateVar = apple -> apple.getColor().equals("red");

is ambiguous and there is no valid reason why the compiler should pick Function<Apple, Boolean> over Predicate<Apple> or vice versa assuming the apple identifier in the lambda represents an Apple isntance.
Another reason is that a lambda in its own doesn't have a speakable type hence there is no way for the compiler to infer it.
Also, "if this was possible" imagine the overhead as the compiler would have to go through all the functional interfaces and determine which functional interface is the most appropriate each time you assign a lambda to a var variable.

A: To everyone who is saying this is impossible, undesired, or unwanted, I just want to point out that Scala can infer the lambda's type by specifying only the argument type:
val predicateVar = (apple: Apple) => apple.getColor().equals("red")

And in Haskell, because getColor would be a standalone function not attached to an object, and because it does full Hindley-Milner inference, you don't need to specify even the argument type:
predicateVar = \apple -> getColor apple == "red"

This is extraordinarily handy, because it's not the simple types that are annoying for programmers to explicitly specify, it's the more complex ones.
In other words, it's not a feature in Java 10.  It's a limitation of their implementation and previous design choices.

A: Because that is a non-feature:

This treatment would be restricted to local variables with initializers, indexes in the enhanced for-loop, and locals declared in a traditional for-loop; it would not be available for method formals, constructor formals, method return types, fields, catch formals, or any other kind of variable declaration.

http://openjdk.java.net/jeps/286

A: In a nutshell, the types of a var and lambda expression both need inference, but in opposite way.  The type of a var is inferred by the initializer:
var a = new Apple();

The type of a lambda expression is set by the context. The type expected by the context is called the target type, and is usually inferred by the declaration e.g.
// Variable assignment
Function<Integer, Integer> l = (n) -> 2 * n;
// Method argument
List<Integer> map(List<Integer> list, Function<Integer, Integer> fn){
    //...
}
map(List.of(1, 2, 3), (n) -> 2 * n);
// Method return
Function<Integer, Integer> foo(boolean flag){
    //...
    return (n) -> 2 * n;
}

So when a var and lambda expression are used together, the type of the former needs to be inferred by the latter while the type of the latter needs to be inferred by the former.
var a = (n) -> 2 * n;

The root of this dilemma is Java cannot decide the type of a lambda expression uniquely,  which is further caused by Java's nominal instead of structural type system.   That is,  two types with identical structures but different names are not deemed as the same, e.g.
class A{
    public int count;
    int value(){
        return count;
    }
}

class B{
    public int count;
    int value(){
        return count;
    }
}

Function<Integer, Boolean>
Predicate<Integer>


text:
Q: how do I fix this error in this section latex says that there  is package inputenc:Unicode character×(U+7D). how should I fix this. this is the section of text where latex throws the error:
humans have tried to help mother nature many times, most of the time this has been a failure resulting in the destruction of delicate ecosystems. Humans have also ended up polluting ecosystems, introducing alien species into ecosystems. the biggest example of Introduction of a alien species is the snakehead, this fish was realised into a river into a river in California. soon these fish began to move out as the fish can breathe on land moving from river to river. with no natural predator the precious ecosystems have been destroyed but this does not mean humans are only causing damage. In Dubai a team relocated a large amount of corals from a busy harbour. Without the ten million dollar project the corals would have died and, in a world, first only 9 corals did not make it. Usually during relocation one in three corals would have died. In 2013 when it was finally opened to the public people saw a thriving coral reef that would have died if it wasn`t relocated. this is just one of the major examples that humans can help the environment. these events have become more and more common in a positive trend. pollution provides a cocktail of problems like the break down which takes dissolved oxygen out of the water.  this drop in the oxygen content will affect animals like penguins as the have a lower amount of prey. this combined with high concentrations of heavy metals is a recipe for disaster. this is combined with things like the longevity of chemicals makes thing worse. Duursma and Marchand (1974) reported an estimated world production of DDT about 2.8 × 106 tons of which 25 percent is released into the ocean. this was the state in 1974. a study for DDT and its breakdown products in the tails of rat fish in the arctic regions long after the ban on DDT.