text:
Q: Can a GAE Spring DispatcherServlet save different Data Objects to the same PersistenceManagerFactory? I am working on a Spring DispatcherServlet deployed to Google App-Engine that uses a JDO PersistenceManagerFactory for storage.
I am developing in Eclipse using a combination of the eclipse Maven Plugin and the Maven appengine Plugin. (I do not have the Google App Engine Plugin for Eclipse installed because I was unsuccessful getting that setup to work.)
I've used this project as a basis for my own:
https://github.com/juleswhite/mobilecloud-14/tree/master/examples/12-VideoSvcAppEngineJDO
Copyright 2014, Jules White
I'll admit that although I am an experienced C++ developer I have little to no previous experience with any of the technologies/tools that I'm attempting to use here. I've exhausted myself trying to figure this out and I can't say for sure where in the process the mistakes are. I have a partially working project and will be happy to post any additional code that you feel is helpful.
Topic 1:
Let me start with a fundamental presumption of my design. I am of the understanding that one PersistenceManagerFactory should be able to handle many different JDO Classes. In my example I have a Caregiver Object and a Patient Object each marked up with DataNucleus Annotation.
Caregiver.java
@PersistenceCapable
public class Caregiver {

@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long id;

    @Persistent
    private String firstName;

    @Persistent
    private String lastName;

    @Persistent
    private String phone;

    @Persistent
    private String email;

    @Persistent
    public ArrayList<Long> patients;

    public Caregiver() {
        patients = new ArrayList<Long>();
    }
    ...

Patient.java
@PersistenceCapable
public class Patient {

    @PrimaryKey
    @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
    private Long sysId;

    @Persistent
    private Long caregiverId;

    @Persistent
    private String firstName;

    @Persistent
    private String lastName;

    @Persistent
    private String recordNum;

    @Persistent
    private String dob;

    @Persistent
    private ArrayList<Long> checkIns;

    @Persistent
    private ArrayList<Long> meds;

    public Patient() {
        checkIns = new ArrayList<Long>();
        meds = new ArrayList<Long>();
    }
    ...

I access the PersistenceManagerFactory through and adaptation of the interface provided in Dr. Whites Code. My adaptation is supposed to extent the PMF to multiple data types.
JDOCrudRepository.java
....
public Object save(Object entity) {
    return PMF.get().getPersistenceManager().makePersistent(entity);
}
....
public Iterable<Object> findAll(Class<?> type) {
    Query query = PMF.get().getPersistenceManager().newQuery(type);
    Object rslt = query.execute();
    return (Collection<Object>) rslt;
}
....

PMF.java
/*
 * @author jules
 *
 */
public final class PMF {
     private final PersistenceManagerFactory pmfInstance = JDOHelper
                .getPersistenceManagerFactory("transactions-optional");

     public PMF() {
     }

     public PersistenceManagerFactory get() {
          return pmfInstance;
     }
}

I am able to build and test the project using the command "mvn appengine:dev_server"
Using my spring dispatcherServlet I have wired functions to add and retrieve Caregiver Objects from the PersistenceManagerFactory.
CaregiverService.java
....
// GET ////////////////////////////////////////////////////////////////////
// TODO: Dangerous in production
@Override
@RequestMapping(value = CaregiverSvcApi.CAREGIVER_SVC_PATH, method = RequestMethod.GET)
public @ResponseBody
Collection<Caregiver> getCaregiverList() {
    ArrayList<Object> objList = Lists.newArrayList(repo
            .findAll(Caregiver.class));

    ArrayList<Caregiver> cg = new ArrayList<Caregiver>();
    for (Object object : objList) {
        cg.add(object != null ? (Caregiver) object : null);
    }

    return cg;
}
...
// POST ///////////////////////////////////////////////////////////////////
@Override
@RequestMapping(value = CaregiverSvcApi.CAREGIVER_SVC_PATH, method = RequestMethod.POST)
public @ResponseBody
Caregiver postCaregiver(@RequestBody Caregiver cg) {
    cg.setIdNull();
    Caregiver newCg = (Caregiver) repo.save(cg);
    return newCg;
}
...

These work fine as demonstrated by the results fetched from my dev server
GET http://127.0.0.1:8080/caregiver
[{"id":5676073085829120,"firstName":"Cg","lastName":"One","phone":"1234567","email":"1@x.com","patients":[]},
{"id":5682617542246400,"firstName":"z","lastName":"z","phone":"123","email":"z@z.com","patients":[]},
{"id":5715999101812736,"firstName":"c","lastName":"s","phone":"123","email":"c@s.com","patients":[]}]

To the meat of the problem…
If I apply the same methodology to my Patient Object
CaregiverSvc.java
...
// GET ////////////////////////////////////////////////////////////////////
@Override
@RequestMapping(value = CaregiverSvcApi.PATIENT_SVC_PATH, method = RequestMethod.GET)
public @ResponseBody
Collection<Patient> getPatientList() {
    ArrayList<Object> objList = Lists.newArrayList(repo
            .findAll(Patient.class));

    ArrayList<Patient> p = new ArrayList<Patient>();
    for (Object object : objList) {
        p.add(object != null ? (Patient) object : null);
    }

    return p;
}
...
// POST ///////////////////////////////////////////////////////////////////
@Override
@RequestMapping(value = CaregiverSvcApi.PATIENT_SVC_PATH, method = RequestMethod.POST)
public @ResponseBody
Patient postPatient(@Body Patient p) {
    p.setIdNull();
    Patient newP = (Patient) repo.save(p);
    return newP;
}
...

Now when I post or get Patient Objects my results are always null.
GET http://127.0.0.1:8080/patient
[{"id":5113123132407808,"caregiverId":null,"firstName":null,"lastName":null,"recordNum":null,"dob":null,"checkIns":[],"meds":[]},
{"id":5697423099822080,"caregiverId":null,"firstName":null,"lastName":null,"recordNum":null,"dob":null,"checkIns":[],"meds":[]}]

All of my patient objects are stored as null values as if my PersistenceManagerFactory does not know how to interpret the Patient Object.
Topic 2:
If I indeed am using a PersistenceManagerFactory appropriately. Is there anything more I need to do to get the PersistenceManagerFactory to properly handle the Patient Object?
Your time is greatly appreciated.

A: @Body Annotation is used in Retrofit.. Your Service should use @RequestBody Annotation to get the Data Object.. That's why server never stored anything and thus returns Null...


text:
Q: Using a Makefile for Debain packages I'm trying to put together a Makefile that will create a folder and clone repositories from GIT
I'm having trouble putting it all together so I'm starting with a generic Makefile
My makefile:
$(shell mkdir -p myDir)
$(shell git.sh)

The shell script that I am trying to get to invoke
#!/bin/sh
REPOSRC="my bitbucket repo URL"
LOCALREPO="myDir"

# We do it this way so that we can abstract if from just git later on
LOCALREPO_VC_DIR=$LOCALREPO/.git

if [ ! -d $LOCALREPO_VC_DIR ]
then
    git clone $REPOSRC $LOCALREPO
else
    cd $LOCALREPO
    git pull $REPOSRC
fi

# End

When I run make I'm getting the following error:
Makefile:2: *** missing separator.  Stop.

Also, is this the correct way to go about this task?

A: What you have is not a makefile.  It's really a shell script written in makefile syntax (and, as you've discovered from the errors, not correct makefile syntax).
Make is a tool that allows commands to be run to update a set of target files, or not run if any of the target files don't need to be updated, based on comparing timestamps of the target files and their prerequisite files.  These dependency relationships can be chained.
That's all that make is for.
To prototypical example is compiling a program: if any of the source files have been modified then you need to recompile the object files for those sources; if object files are updated then libraries might need to be re-created; if object or library files are updated then programs might need to be re-linked.
If your problem space doesn't map, or can't be made to map, to that mechanism, then make and makefiles are not the correct tool for the job you have in mind.  Based on your description of your problem, make is not the right tool for this job.
You should just write a shell script, as you've basically done here already, and move forward.
If you do want to write a makefile you should spend some time understanding the syntax of makefiles and how they work, rather than just searching on Stack Overflow and trying to put together a makefile based on the answers.  For example, try reading at least the introduction of the GNU make manual.

A: With $(shell ...) construct you substitute shell command output into the makefile. Of course after calling mkdir or invoking git the output is not a valid makefile.
Your makefile should be like this
all:
    mkdir -p myDir
    ./git.sh

note that indentation after all: has to be done with tabs.
And it looks like you don't need make for your task. Just shell script would be enough.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Concourse CI + MVN I am trying to create a pipeline using Concourse CI using Maven. The pipeline should:

*

*Get the code from git.

*Build and run test using maven.

*the project generates html report in target folder

above steps are executing properly. The question how to access the output i.e target folder generated by the maven project.
I am not able to access the generated folder and copy to the required folder for later usage.
File pipeline.yml:
resources:
- name: branch-master
  type: git
  source:
    uri: {{git-url}}
    branch: master

jobs:
- name: MavenJob
  serial: true
  plan:
  - get: branch-master
    trigger: true
  - task: mvn-test
    privileged: true
    file: branch-dev/AppDemo/test.yml

File test.yml:
platform: linux

image_resource:
  type: docker-image
  source:
    repository: maven
    tag: latest

inputs:
  - name: branch-master
outputs:
  - name: mvn-output

run:
  path: "mvn"
  args: ["-f", "branch-master/AppDemo/pom.xml", "test"]

Please some body help me.
Thanks in advance.

A: For sake of simplicity and unambiguity I renamed your git repo to project. Let's assume it contains concourse's yamls. And there is a directory AppDemo with java-maven app
project/pipeline.yml:
resources:
- name: project
  type: git
  source:
    uri: {{git-url}}
    branch: master

jobs:
- name: MavenJob
  serial: true
  plan:
  - get: project
    trigger: true
  - task: mvn-test
    privileged: true
    file: project/test.yml

the job above should locate and trigger the test.yml task
project/test.yml:
platform: linux

image_resource:
  type: docker-image
  source:
    repository: maven   # let's hope bin/bash is available there. if no, use sh
    tag: latest

inputs:
  - name: project   # project is your git-repo. all paths are relative to it's location
outputs:
  - name: mvn-output

run:
  path: /bin/bash
  args:
    - project/test-script.sh:

project/test-script.sh:
_ROOT=$(pwd)
echo "starting test-script from directory: $ROOT"

cd _ROOT/AppDemo
mvn test

if you want to pass outputs of maven job somewhere further, then you should just copy all those files into mvn-output directory later in the script.
I would also recommend using this bash-script as wrapper rather than raw "maven call" - it's more convenient for debugging the whole process as you can, e.g. echo'ing paths.
in case of any error, if container still alive, try hijacking into it to see what has actually happened there and where files are located:
fly -t <target> hijack -u <url-of-failed-job-from-your-browser>

hope this helps


text:
Q: Probability proof of a function with independent uniformly distributed variables I'm currently reading through the introduction section of a research paper which states the following:

Let $Y_0$, $Y_1$, $Y_2$ and $Y_3$ be independent uniformly distributed variables over the field $\mathbb{F_2=\{0,1\}}$. Then,
$P\left[ f(Y_0, Y_1, Y_2, Y_3)=0 \right] = 1/2$
where
$f(Y_0, Y_1, Y_2, Y_3) := \{\left( Y_0 \lor Y_1 \right)\oplus \left( Y_0 \land Y_3 \right) \}\oplus\{Y_2\land\left[\left(Y_0 \oplus Y_1\right) \lor Y_3\right]\}$

The paper offers only a proof "by inspection". After thinking about it for myself, it doesn't appear obvious to me to why this is true. Here is my thought process:
$P\left[Y_0\lor Y_1 = 0\right]=1/4$
$P\left[Y_0\land Y_3 = 0\right] = 3/4$
$P\left[\{\left( Y_0 \lor Y_1 \right)\oplus \left( Y_0 \land Y_3 \right) \}=0\right]=\frac{1}{4}\cdot\frac{3}{4}+\frac{3}{4}\cdot\frac{1}{4}=\frac{3}{8}$
$P\left[\left(Y_0 \oplus Y_1\right)=0\right]=1/2$
$P\left[\left[\left(Y_0 \oplus Y_1\right) \lor Y_3\right]=0\right]=1/4$
$P\left[\{Y_2\land\left[\left(Y_0 \oplus Y_1\right) \lor Y_3\right]\}=0\right]=1-\frac{1}{2}\cdot\frac{3}{4}=5/8$
$P\left[ f(Y_0, Y_1, Y_2, Y_3)=0 \right]=\frac{3}{8}\cdot\frac{5}{8}+\frac{5}{8}\cdot\frac{3}{8}=30/64=15/32\neq1/2$

Where is the fault in my understanding? What am I missing?

A: Your third calculation
$$P\left[\{\left( Y_0 \lor Y_1 \right)\oplus \left( Y_0 \land Y_3 \right) \}=0\right]=\frac{1}{4}\cdot\frac{3}{4}+\frac{3}{4}\cdot\frac{1}{4}=\frac{3}{8}$$
is incorrect. It is true that
$$P(A\oplus B=0)=P(A=0)P(B=0) + P(A=1)P(B=1)$$
when $A$ and $B$ are independent, but here $Y_0\lor Y_1$ is not independent of $Y_0\land Y_3$, since $Y_0$ is involved in both of these. (You have the same problem with your final line.)
I get $$P\left[\{\left( Y_0 \lor Y_1 \right)\oplus \left( Y_0 \land Y_3 \right) \}=0\right]=\frac12$$
by tediously counting the possibilities. This may be the most direct way to work out the final probability (which I find is $1/2$, as claimed): evaluate the truth of the assertion on all 16 possibilities (aka "inspection").

A: The third line is incorrect.  $\def\getsto{\mathop{\leftrightarrow}}\def\P{\mathsf P}$
Well, because $\{A\oplus B=0\}$ is equivalent to $\{A\getsto B=1\}$, therefore this is $(\{A=1\}\cap\{B=1\})\cup(\{A=0\}\cap \{B=0\})$
However, when $A=(Y_0\wedge Y_1)$ and $B=(Y_0\vee Y_3)$, the conjunction is not of independent events.   The truth value of $A,B$ will both be dependent on truth value of $Y_0$ .
So instead the third line will be:
$ \P\{(Y_0\wedge Y_1)\oplus (Y_0\vee Y_3)=0\} ~{= \P\{(Y_0\wedge Y_1)\getsto(Y_0\vee Y_3)=1\}\\ =\P\{(Y_0\wedge Y_1)\vee(\neg Y_0\wedge\neg Y_3)=1\}\\= \tfrac 12 }$
Alternatively:
$\P\{(Y_0\wedge Y_1)\oplus (Y_0\vee Y_3)=0\} ~{= 1-\P\{(Y_0\wedge Y_1)\oplus (Y_0\vee Y_3)=1\}\\ = 1-\P\{(Y_0\wedge\neg Y_1)\vee(\neg Y_0\wedge Y_3)=1\}\\= \tfrac 12 }$

Notes: $\getsto$ is the "biconditional" connective; aka "material equivalence". $~(Y_0\wedge Y_1)\getsto (Y_0\vee Y_3)$ is true iff $(Y_0\wedge Y_1)$ and $(Y_0\vee Y_3)$ have the same truth value.$~$  In that event, there are two cases: $Y_0$ is either true or false.$~$

*

*In the case where $Y_0$ is true, then $(Y_0\vee Y_3)$ is too (whatever $Y_3$ is), which means $Y_0\wedge Y_1$ is also true, and thus $Y_1$ must be true.

*In the case where $Y_0$ is false, then $Y_0\wedge Y_1$ is false (whatever $Y_1$ may be), and so $Y_1\vee Y_3$ must be false too, and so $Y_3$ is false.

*

*Thus the event $\{(Y_0\wedge Y_1)\getsto (Y_0\vee Y_3)=1\}$ is exactly the event $\{(Y_0\wedge Y_1)\vee(\neg Y_0\wedge\neg Y_3)=1\}$

Apply similar reasoning to $\{f(Y_0,Y_1,Y_2,Y_3)=0\}$


text:
Q: Unlink Phone from a Specific User The following Google Cloud Function should unlink the phone number from a specific user. If the code was executed on the client, it would look like the following. However, (currentUser) is undefined, which makes sense because the cloud function does not know anything about the current user.
What should I replace (currentUser - below) with?
const admin = require('firebase-admin');

module.exports = async function (request, response) {
/* eslint-disable */
    admin.auth().getUserByPhoneNumber(request.body.phoneNo)
        .then( (userRecord) => {
            // WHAT SHOULD I REPLACE currentUser (BELOW) WITH?
            admin.auth().currentUser.unlink(firebase.auth.PhoneAuthProvider.PROVIDER_ID)
                .then ( () => {
                    console.log("getUserByPhoneNumber - unlink - then");
                })
                .catch( (error) => {
                    console.log("getUserByPhoneNumber - unlink - catch - error:", error);
                })
            ;
            response.send({ success: true });
        })
        .catch( (error) => {
            console.log('getUserByPhoneNumber - catch - error:', error);
            response.send({ success: false });
        });
/* eslint-enable */
};

I tried the following with no success.
admin.auth().getUser(userRecord.uid).unlink(firebase.auth.PhoneAuthProvider.PROVIDER_ID)
admin.auth().userRecord.unlink(firebase.auth.PhoneAuthProvider.PROVIDER_ID)
Thank you for your effort and time to help...

A: If you want to remove the phone number from a user via Admin SDK, here is how you do it:
admin.auth().getUserByPhoneNumber(phoneNumber)
  .then((userRecord) => {
    return admin.auth().updateUser(userRecord.uid, {phoneNumber: null});
  })
  .then((userRecord) => {
    // Phone number should be cleared from the user record.
  })
  .catch((error) => {
    // Error occurred.
  });


text:
Q: Identical balls for non-identical people I have 40 identical black balls, 23 identical red balls, and 31 identical yellow balls. I want to distribute this to 12 distinct people such that each person gets at least one of each color ball. How many ways can I make this distribution?
I started with the stars and bars method.
For the 40 black balls:
$\binom{39}{11}$
For the 23 red balls:
$\binom{22}{11}$
For the 31 yellow balls:
$\binom{30}{11}$
After this I'm unsure. Do I just apply multiplication rule and multiply all three of these combinations?

A: Since the distribution of one color of balls does not affect the other one, that means that the number of distributions for each color are independent, thus you can safely multiply all the numbers you got. I also checked your work, and I believe you got the right numbers to multiply together.


text:
Q: WHERE Clause to get month and year from current date in asp.net I want to filter data by month and also year from sql database. I set my current date to (yyyy-MM-dd) format. From there i want to filter by month and year. Below is my source code.
     Dim ServerDate As String
        ServerDate = Date.Now.ToString("yyyy-MM-dd")
        Dim nowYear As Integer
        nowYear = Date.Now.Year
        Dim nowMonth As Integer
        nowMonth = Date.Now.Month

This one my select statement:
 cmd.CommandText = "Select COUNT(*) FROM ScanningData WHERE ASSET_NUMBER=" & AssetTxt.Text & " And LOC_DEPT=" & DeptCodeTxt.Text & " AND UNIT_NO=" & UnitNoTxt.Text & " AND UPDATE_DATE='" & nowMonth & nowYear & "';"

Can someone help me on this. Thank you in advance

A: Use DATEPART
Eg(not tested for syntax error)
Select COUNT(*) FROM ScanningData
WHERE ASSET_NUMBER=" & AssetTxt.Text & " And LOC_DEPT=" & DeptCodeTxt.Text & "
AND UNIT_NO=" & UnitNoTxt.Text & " AND ( DATEPART(mm, CreationDate) = "& nowMonth & ") and (DATEPART(yy, CreationDate)="& nowYear  & " )


text:
Q: How can i reach child node values of firebase realtime database in node.js? I am trying to make push notifications in chat page of my application. So i am trying to make an rest-api for it.  I have a realtime database properties like this;
UserProfile
  -->child (user id)
     --> Token : token.value
         UserName : username.value

So how can i reach token and username in node.js
I tried this but not reached child node value

  var db = firebase.database().ref(`UserProfile`);
        db.once("value").then(function (snapshot) {
            $("#users").empty();

            if (snapshot.exists()) {
                snapshot.foreach(function (userSnapshot) {
                    var html = "<option value='";
                    html += userSnapshot.val().Token;
                    html += "'>";
                    html += userSnapshot.val().Username;
                    html += "</option>";

                    $("#users").append(html);
                });
            }

        });

I want to reach username and token values and actually id of every item of database. I want to add as a list. how can i reach them?

A: You can simply use Object.values():
db.once("value").then(function (snapshot) {
   Object.values(snapshot.val()); // Array of UserProfile child
}

https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/values


text:
Q: Escape an & (ampersand) at the start of a YAML entry? An ampersand at the start of a YAML entry is normally seen as a label for a set of data that can be referenced later.  How do you escape a legitimate ampersand at the start of a YAML entry.  For example:
---
- news:
    news_text: "Text!'
I am looking to not have &ldquo be a label within the yaml file, but rather when I get parse the YAML file to have the news_text come back with the " in the entry.

A: You probably can enclose the text in quotes:
---
- news:
    news_text: ""Text!'"

Besides, you can probably just as well use the proper characters there:
---
- news:
    news_text: "Text!'

Putting escapes specific to a totally different markup language into a document written in another markup language seems ... odd to me, somehow.

A: Or you could put the string on the next line, if you put a '>' or '|' at the spot where the string used to be. Using the '|' character your parser will keep your custom line breaks, while '>' turns it into one long string, ignoring line breaks.
- news:
    news_text: >
        "Text!'

A: Just put quotes around the text
require 'yaml'

data = <<END
---
- news:
    news_text: "“Text!’"
END

puts YAML::load(data).inspect

# produces => [{"news"=>{"news_text"=>"“Text!’"}}]

A: Putting the entire string in single quotes would do what you want:
---
- news:
    news_text: '“Text!’'

But, I think that any yaml library should be smart enough to do that for you?


text:
Q: how to make a php script regarding permission issues 0755 in Codeigiter 3? I've created a small scale CMS for the website I'm working on and have a form that uploads image files for use on the website. It uploads files successfully but the permissions it sets do not allow files to be viewed in the browser. this is my controller. I am still a beginner using Codeigniter, when running locally there is no problem, when it is uploaded to the server there are problems related to permission problems.
            $config['upload_path']     = './assets/backend/img/banner';
            $config['allowed_types']   = 'jpg|jpeg|png';
            $config['encrypt_name']    = 'True';

            $this->load->library('upload', $config);
            if (!$this->upload->do_upload('path_banner')) {
                $this->session->set_flashdata(
                    'pesan',
                    '

                        Maaf :(! Upload gagal, format photo jpg, jpeg, png
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            ×
                        </button>

'
                );

                redirect('backend/admin/banner');

A: I not really agree with permission 755 or with the need to do so through the code and not through the operating system.
For your question, you can add that code if do_upload return true
$full_path = $this->upload->data('full_path');
chmod($full_path, 0755);


text:
Q: Alignment issue when running simulator I am trying to run a simple sample using a nib file and it looks like this

However when I run it in my simulator it looks like this

My question is why is the alignment of the simulator not correct ?
The elements should be close to the middle and the screen height should be longer. Any suggestions on how I could fix this ? I am using Xcode 6.2
Here are the things I tried so far :
1 ) I made sure that the alignment in my nib file is set to Auto Layout.
These are the details of my project. I am testing on an iphone 6 as my simulator.

Any suggestions on how I can fix this ?

A: You need to set Constrain in AutoLayout if u don't want to use auto-layout then u can unCheck it .. you can refer this tutorial http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1

A: You probably need to configure size classes for the class device that you use.
If your app is only for iphone, you can also disable size and keep size classes for iphone only.

Hint Use preview from: Assistant editor -> Automatic > Preview, you will be able to see a preview of the view with all device screen sizes


text:
Q: Using an IF statement with a string using .value Does the .value command return strings and if not how do you have an IF statement check if the cell(s) holds the correct string.
I am working on a budget sheet where a certain column sets which department the budget and its breakdown should be forwarded to.
Sub calcMonthly()

Dim ws As Worksheet
Dim wssum As Worksheet

'set worksheets to copy values
Set ws = Sheets("Sheet 1")
Set wssum = Sheets("Sheet 2")

Dim i As Integer
Dim j As Integer
Dim k As Integer

Dim bumonth As Currency
Dim busum As Currency

'sort through Departments for % breakdown
For k = 0 To 18

    'sort through months
    For i = 0 To 11
    busum = 0
        'sort through each item
        For j = 0 To 350
            bumonth = 0
            bumonth = CCur(ws.Cells(3 + j, 37 + k).Value * ws.Cells(3 + j, 24 + i).Value)
            busum = busum + bumonth
        Next j
    'row C holds the string which details if the item if physical hardware or digital then uploads it to the cell
    If ws.Cells(3 + j, 3) = "SW" Then
        wssum.Cells(3 + k, 2 + i).Value = busum
    Else
        wssum.Cells(3 + k, 14 + i).Value = busum
    End If
    Next i
Next k

End Sub

A: .Value does return a string, but it doesn't look like you included it in the IF statement.
If ws.Cells(3 + j, 3).value = "SW" Then

A: Range.Value returns a Variant whose subtype depends on the content of the cell.
Given a #N/A, #VALUE, #REF!, or any other cell error value, it returns a Variant/Error that can't be coerced into anything other than a Variant - trying to compare it to a string or numeric value or expression will throw error 13 "type mismatch".
You can avoid this runtime error by evaluating whether the variant subtype is Error using the IsError function, ideally by capturing the cell's value into a local Variant variable first, so you don't have to access the cell twice.
Given an empty cell that has no formula, no value, no content whatsoever, it returns a Variant/Empty; the IsEmpty function can be used to validate this variant subtype.
Given a Date value, it returns a Variant/Date. Given any numeric value, it returns a Variant/Double. Given a TRUE or FALSE value, it returns a Variant/Boolean.
And given a String value, it does return a Variant/String.

Note that the default member of the Range class is a hidden [_Default] property with two optional parameters:

When no parameters are provided, an explicit call to .Value is equivalent. Explicit member calls should generally be preferred over implicit default member calls, and whether implicit or explicit, the calls should be consistent:

If ws.Cells(3 + j, 3) = "SW" Then ' implicit: .Value
    wssum.Cells(3 + k, 2 + i).Value = busum
Else
    wssum.Cells(3 + k, 14 + i).Value = busum
End If


text:
Q: How to organize strings from Selenium in Pandas Dataframe? **I am trying to extract data from whatsapp chatroom, but i am having trouble to send the data to a dataframe.
The code i have is:**

chatroom = driver.find_element_by_class_name('_1_q7u')

pos= 0
df = pd.DataFrame(columns=['Time','Msgs'], index=None)

for ol in chatroom.find_elements_by_class_name('message-in'):
    data = []
    msgs = ol.find_elements_by_class_name('woe4f')
    times = ol.find_elements_by_class_name('_1RNhZ')
    for msg in msgs:
        data.append(msg.text)
    for time in times:
        data.append(time.text)
    df.loc[pos] = data
    pos+=1
    print(df)

**The error returned error comes as "ValueError: cannot set a row with mismatched columns" but the times i got the code to work, it brings me just the first elemnets in time and msg, i need all of them organized.
Noob trying to code here.**

A: So if you want to drop somthing into a dataframe with loc you're going to have to make sure that the thing you drop in has the same dimensions as your df. Because you have 2 columns you need 2 things... You can achieve this by putting your times in a list and your messages in a list.
chatroom = driver.find_element_by_class_name('_1_q7u')

pos= 0
df = pd.DataFrame(columns=['Time','Msgs'], index=None)

for ol in chatroom.find_elements_by_class_name('message-in'):
    msgs = [k.text for k in ol.find_elements_by_class_name('woe4f')]
    times = [k.text for k in ol.find_elements_by_class_name('_1RNhZ')]
    df.loc[pos] = [times,msgs]
    pos+=1
    print(df)


text:
Q: Simplest configuration for Emacs (OS X) I use Emacs everyday on my PC, running on Ubuntu... I use to run it directly on the terminal, with the "emacs -nw option".
I also have a mac, running on OS-X Yosemite, but I can't figure how to configure it.
On my Ubuntu, I do "M-i" to do some tabulations, and every shortcuts are working properly.
But on my mac, by default, the Alt key isn't set as the meta key. I can set the option "Alt key as virtual key" in the Terminal preferences, but if set this option, I can't write "braces" anymore because "Alt + (" writes now a some parenthesis.
I tried many times some options, some .emacs configurations found on the internet, but nothing worked. All I want, is my OS X Emacs working like an ordinary Linux emacs. I also tried AquaEmacs, but I can't run it from the terminal...
Could someone tell me a basic configuration, or maybe an other version of emacs ?
Thanks for the help !

A: I am answering back my own question as I found a solution.
My advice would be to use the ITerm terminal instead of the native OS X Terminal App.
Iterm allows more flexibility, and thus, more ways to configure meta keys.


text:
Q: How to set calendar view in list view web part using CSOM in share point 2013 I have a calendar type of list in which I have set up overlays.
When manually I add the same calendar list in the list view web part, it shows me  all the events and the overlays in the web part.
I want to have the same using CSOM in O365.
Please suggest .


text:
Q: Linear interpolation between a set of points? I have an array that contains x,y values. Now i can draw those points on the screen but i am having trouble interpolating between those points.
I have tried to search but everyone using different algorithms and its confusing me. I have tries Bresenham's line algorithm but i cant seem to understand it either.
var myVar = setInterval(function () {
    ctx.clearRect(0, 0, 1000, 800);
    ctx.strokeRect(pts[q].x, pts[q].y, 20, 20);
    q++;
}, 1000/60);

pts has all the x,y cordinates and q is simply a variable to access the array. Now i can get the distance between the current point and the next point but then i get confused. I dont know what to do with that distance?
Can anyone please explain to me how it works? or point me to the right direction?


text:
Q: Fatal error while installing keras I was trying to install keras (for using LSTM) on my Windows 10 system in Anaconda using the method provided by Yelaman. But after running the command pip install git+git://github.com/Theano/Theano.git, I received the following fatal error -

C:\Anaconda>pip install git+git://github.com/Theano/Theano.git
Collecting git+git://github.com/Theano/Theano.git
Cloning  git://github.com/Theano/Theano.git to
  c:\users\krishna\appdata\local\temp\pip-reettr-build fatal: protocol
  error: bad line length character:
Er
Command "git clone -q git://github.com/Theano/Theano.git
  c:\users\krishna\appdata\local\temp\pip-reettr-build" failed with
  error code 128 in None

I don't have a github account but i use git using bitbucket (if that matters).
Could anyone explain to me what error I am committing and if there is a way out? My main goal is to use keras in Anaconda in Windows.
Thanks!

A: It seems that the error may be because we have a git repository listed as a dependency. Not still fully sure, though. (Source)
The solution is to replace pip install git+git://github.com/Theano/Theano.git with pip install git+http://github.com/Theano/Theano.git i.e. replacing the second git with http (this works since the repository is public)


text:
Q: Can citeindex and bibindex contain section number in biblatex? I hope the serial numbers of references in the appendix include section number. That is, [1]->[A.1], [2]->[A.2], [3]->[B.1], [4]->[B.2], [5]->[B.3]. Just like the equation number shown by following command.
\renewcommand{\theequation}{\thechapter-\arabic{equation}}

\documentclass{article}

\usepackage{filecontents}
\begin{filecontents}{\jobname.bib}
@article{A,title={A}}
@article{B,title={B}}
@article{C,title={C}}
@article{D,title={D}}
@article{E,title={E}}
@article{F,title={G}}
\end{filecontents}

\usepackage[style=gb7714-2015]{biblatex}
\addbibresource{\jobname}

\begin{document}

\section{mainbody}
text\cite{A}
text\cite{B}
\printbibliography

\appendix

\begin{refsection}

\section{appendix 1}
text\cite{C}
text\cite{A}
\section{appendix 2}
text\cite{D,E,F}
\printbibliography

\end{refsection}

\end{document}


text:
Q: Weak convergence to a Gaussian measure in coarser topology induced by a covariance operator I'm currently studying Gaussian measures on Hilbert spaces and would like to find conditions under which convergence to a Gaussian measure with respect to a coarser topology induced by a covariance operator implies weak convergence with respect to the original topology. This question is an asymptotic version of this related question, where it was shown that if two measures agree on such a coarser topology, then they also agree on the original topology.
Full details are as follows:
Let $H$ be a real separable Hilbert space and $S$ a bijective, non-negative, self-adjoint trace-class operator on $H$ (for example the covariance operator of some Gaussian measure on $H$). Denote the inner product by $\left\langle \cdot,\cdot \right\rangle$ and define a new inner product $\left\langle \cdot,\cdot \right\rangle_1$ on $H$ by
$$
\left\langle x,y  \right\rangle_1 := \left\langle \sqrt{S} x, \sqrt{S} y \right\rangle, \qquad x,y \in H.
$$
This inner product is weaker than $\left\langle \cdot,\cdot  \right\rangle$, as for the induced norms we have that $\left\lVert \cdot \right\rVert_1 \leq \left\lVert T \right\rVert_{op} \left\lVert \cdot \right\rVert$. Let $H_1$ be the completion of $H$ with respect to $\left\lVert \cdot \right\rVert_1$. Then $H_0 \subseteq H_1$ densely and as a Borel set.
Let $\mathcal{B}(H)$ and $\mathcal{B}(H_1)$ denote the Borel sets of $H$ and $H_1$, with respect to the norms $\left\lVert \cdot \right\rVert$ and $\left\lVert \cdot \right\rVert_1$,respectively. Then $\mathcal{B}(H_1) \cap H \subseteq \mathcal{B}(H)$, where $\mathcal{B}(H_1) \cap H = \{ A \cap H \colon A \in \mathcal{B}(H_1) \}$.
Finally, let $\nu_n$ be a sequence of probability measures on $(H,\mathcal{B}(H))$ with trace class covariance operators and $\mu$ be a Gaussian measure on $(H,\mathcal{B}(H))$. Then $\mu$ is completely determined by its values on $\mathcal{B_1}\cap H$ (see the above linked question).
My question is:
If $\nu_n$ converges weakly on $(H,\mathcal{B}(H_1)\cap H)$ to $\mu$ ("weakly" in the probabilistic sense, i.e. with respect to real-valued, bounded continuous functions), does this convergence also hold on $(H,\mathcal{B}(H))$, maybe under some additional conditions on the covariance operator defining the weaker inner product?


text:
Q: Get the average of elements values in xsl I've been dealing with xsl for the first time today. The XML file I have looks like the following:
<student_course>
<students>
    <student num="">
    <name gender=""></name>
    <course cid="1"></course>
    <course cid="2"></course>
    <course cid="3"></course>
    <course cid="4"></course>
    <comments></comments>
    </student>
</students>
<courses>
    <course cid="1"></course>
    <course cid="2"></course>
    <course cid="3"></course>
    <course cid="4"></course>
</courses>
</student_course>

There are 10+ students, and I need to print out all the grades for each course for each student. That I've done using for-each. What I need to do, is at the bottom of the column, show the average grade for that course (student/course) I was thinking a variable would be the way to go, and increment it in the for-each and divide it or something, but that does not seem to work, everytime I try to make a variable I can only call it immediately after I set it, I must be doing something wrong. How would I get the average for all values under student_courses/students/student/course[@cid]?
Currently I have my xsl display a table with 4 columns and 11 rows (1 row for the titles, and 10 for the student grades) and then a 12th row to have the averages.
Thanks in advanced!

A: I figured it out. To get the average, the easiest way was to use a for-each and the sum() and count() functions. All I needed was to add this where ever I wanted the average to display:
<xsl:value-of select="sum(/student_course/students/student/course[@cid='1']) div count(/student_course/students/student/course[@cid='1'])"/>

and just change the cid value for the different courses.


text:
Q: "Setting up tick label, The disappearance of first array list, jumping up to the second array list", so basically why the first array not setted up? Please see the result below, as you can see in the image when i set the label it suddenly jump to second list (x_tick[1] and y_tick[1])  why? what happen to first list (x_tick[0] and y_tick[0]).
When i use image to plot this happen but without image it show up.
Note: for image in matplotlib. y label, set from top to bottom and x label, set from left to right

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image, ImageDraw

point=(1.28358, 103.86921, 1.11504, 104.16138) #BATAM3
im = Image.open('BATAM3.png', 'r')
x_tick = list(map(lambda x: round(x, 7), np.linspace(point[1], point[3], endpoint=True, num=9)))
y_tick = list(map(lambda x: round(x, 7), np.linspace(point[2], point[0], endpoint=True, num=6)))
y_tick = sorted(y_tick, reverse=True)

print(x_tick)
print(y_tick)
#print(x_tick[0])

fig, ax = plt.subplots(figsize=(15, 15))
ax.imshow(im)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_xticklabels(x_tick)
ax.set_yticklabels(y_tick)
ax.grid()

This yields:
[103.86921, 103.9057312, 103.9422525, 103.9787737, 104.015295, 104.0518162, 104.0883375, 104.1248587, 104.16138]
[1.28358, 1.249872, 1.216164, 1.182456, 1.148748, 1.11504]

here the result for the image imshow(im) :
https://files.fm/thumb_show.php?i=c6u8b5bhg
to make my question easy to understand :
https://files.fm/thumb_show.php?i=7vucbyuhg

A: As the documentation says, you need to set the ticks locations using set_xticks first before setting the labels.
https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.set_xticklabels.html
w, l = im.size
x_pos = list(map(lambda x: round(x), np.linspace(0, w, endpoint=True, num=9)))

fig, ax = plt.subplots(figsize=(15, 15))
ax.imshow(im)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_xticks(x_pos) #set the positions
ax.set_xticklabels(x_tick)
ax.set_yticklabels(y_tick)
ax.grid()

A: it Solved, thanks to @Said Al Faraby for the answer.
Here the fix :
point=(1.28358, 103.86921, 1.11504, 104.16138)
im = Image.open('BATAM3.png', 'r')
x_pos = list(map(lambda x: round(x), np.linspace(0, im.size[0], endpoint=True, num=10)))
y_pos = list(map(lambda x: round(x), np.linspace(0, im.size[1], endpoint=True, num=6)))
x_tick = list(map(lambda x: round(x, 7), np.linspace(point[1], point[3], endpoint=True, num=10)))
y_tick = list(map(lambda x: round(x, 7), np.linspace(point[2], point[0], endpoint=True, num=6)))
y_tick = sorted(y_tick, reverse=True)

fig, ax = plt.subplots(figsize=(15, 15))
ax.imshow(im)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_xticks(x_pos)
ax.set_yticks(y_pos)
ax.set_xticklabels(x_tick)
ax.set_yticklabels(y_tick)
ax.grid()

and here for the image :
https://imgur.com/ESTdLhE


text:
Q: While loop JOptionPane issues Ok - I know that I am fairly close to the solution but need a nudge in the right direction. I need the user to hit YES and the program to begin asking the question again.
After execution, I get the following errors

Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
  String index out of range: 1  at java.lang.String.charAt(Unknown
  Source)   at Vowel3.main(Vowel3.java:49)

// java class for Panel I/O
import javax.swing.JOptionPane;

// declaration of the class
public class Vowel33
{

    // declaration of main program
    public static void main(String[] args)
    {

    // objects used to store data
    String input_string = null;
    int a_count = 0;
    int e_count = 0;
    int i_count = 0;
    int o_count = 0;
    int u_count = 0;
    int i = 0;
    int yes = 0;

    // 1. display a descriptive message
    String display_message = "This program asks the user for a sentence,\n"
        + "searches the sentence for all vowels,\n"
        + "and displays the number of times each"
        + "vowel appears in the sentence";
    JOptionPane.showMessageDialog(null, display_message, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);

    // 4. visit each String posotion

     do{

        // 3. input the character string

        input_string = JOptionPane.showInputDialog("Enter the sentence to search");

        // 5.  if position i of String is a vowel
        // 6.  increase the appropriate vowel counter
        if (input_string.charAt(i) == 'a' || input_string.charAt(i) == 'A')
        a_count++;

        else if (input_string.charAt(i) == 'e' || input_string.charAt(i) == 'E')
        e_count++;

        else if (input_string.charAt(i) == 'i' || input_string.charAt(i) == 'I')
        i_count++;

        else if (input_string.charAt(i) == 'o' || input_string.charAt(i) == 'O')
        o_count++;

        else if (input_string.charAt(i) == 'u' || input_string.charAt(i) == 'U')
        u_count++;

        i++;

        String display_message1 = input_string                                      // 7. display the String
        + "\n\n" + "has " + input_string.length() + " characters.\n\n"          // 8. display the number of characters
        + "There are \n"
        + a_count + " a's,\n"                                                   // 9. disaply the number of each vowel
        + e_count + " e's,\n"
        + i_count + " i's,\n"
        + o_count + " o's, and\n"
        + u_count + " u's.\n\n";

        JOptionPane.showMessageDialog(null, display_message1, "Lab 3 Description", JOptionPane.INFORMATION_MESSAGE);

        yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);

    }   while (i < input_string.length());

            if (i == input_string.length())
            {
                yes = JOptionPane.showConfirmDialog(null, "Would you like to enter another string?\n\n", "Extra Credit", JOptionPane.YES_NO_OPTION);
                if (yes == 1)
                {
                    input_string = JOptionPane.showInputDialog("Enter the sentence to search");
                }
            }

    } // end of main
} // end of the class

A: In your code you have a condition where the loop can still be executed if yes is 0.  Since yes is never redefined from what I can see, you basically have an infinite loop and your code will error out when i exits the bounds of your string's length.
Also not sure why you have two JOptionPanes at the bottom of the loop (which would execute x times where x = input_string.length())
Consider something like:
if(i == input_string.length()) {
    //ask the user if they want to enter another string
    if(the user selected yes){
        yes = 1;
        //instantiate again with new input_string
    }
}

Another note: Assuming you want to show a message asking if the user wants to enter another string once you've finished iterating through their first entry, it seems moot to have the yes variable and condition.


text:
Q: SQLite iOS warning : Comparison of constant 101 with expression of type BOOL is always false I have downloaded sample code for SQLite learning. I'm using Xcode 6.1.1 and iPhone 6 plus simulator. After running app on simulator I'm getting DB Error : unknown error from query execution. Below is part of code where I'm getting warning as Comparison of constant 101 with expression of type 'BOOL' (aka 'bool') is always false.
// Execute the query.
BOOL executeQueryResults = sqlite3_step(compiledStatement);
 if (executeQueryResults == SQLITE_DONE) {
     // Keep the affected rows.
      self.affectedRows = sqlite3_changes(sqlite3Database);

       // Keep the last inserted row ID.
       self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
  }
  else {
      // If could not execute the query show the error message on the debugger.
       NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
  }

What might be fix for this?

A: Checking condition for compiledStatement directly solved the problem :
// Execute the query.
// BOOL executeQueryResults = sqlite3_step(compiledStatement);
// if (executeQueryResults == SQLITE_DONE) {

 if (sqlite3_step(compiledStatement)) {
     // Keep the affected rows.
      self.affectedRows = sqlite3_changes(sqlite3Database);

      // Keep the last inserted row ID.
       self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
 }
 else {
     // If could not execute the query show the error message on the debugger.
       NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
 }

A: Try changing Your code
if (sqlite3_step(compiledStatement) == SQLITE_DONE) {
     // Keep the affected rows.
      self.affectedRows = sqlite3_changes(sqlite3Database);

       // Keep the last inserted row ID.
       self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
  }
  else {
      // If could not execute the query show the error message on the debugger.
       NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
  }

A: That's beacause TRUE is probaly 1 or -1, but never 101 (SQLITE_DONE = 101). Boolean values are true and false but never SQLITE_DONE.
You could write something like
bool done = sqlite3_step(compiledStatement) == SQLITE_DONE;
if (done) {
    ...
}

But if don't need this result later, there is no point in defining this variable at all
if (sqlite3_step(compiledStatement) == SQLITE_DONE) {
    ...
}

A: I know it's late,but it can help someone in future .
// This is the case of an executable query (insert, update, ...).

                // Execute the query.
                BOOL executeQueryResults = sqlite3_step(compiledStatement);
                if (executeQueryResults) {
                    // Keep the affected rows.
                    self.affectedRows = sqlite3_changes(sqlite3Database);
                    NSLog(@"affected row = %d",self.affectedRows);

                    // Keep the last inserted row ID.
                    self.lastInsertedRowID = sqlite3_last_insert_rowid(sqlite3Database);
                    NSLog(@"last iserted row = %lld",self.lastInsertedRowID);
                }
                else {
                    // If could not execute the query show the error message on the debugger.
                    NSLog(@"DB Error: %s", sqlite3_errmsg(sqlite3Database));
                }


text:
Q: Why doesn't the input element fit inside the image? I am trying to put 2 input elements inside an image element. I set the position of the input elements to absolute and only the left input was entered inside the image element, While the second stayed outside.
I like to know why its happening and I also need a solution for putting the right input inside the image.

.container-fluid {
  text-align: center;
  position: relative;
}

img {
  display: inline;
  max-height: 100%;
}

.myB {
  position: absolute;
  top: 50%;
}

  <input class='myB' type='button' value='<'>

  <input class='myB' type='button' value='>'>

A: Multiple problems:

*

*Set the position of the Buttons, and dont let the browser decide to do it. Small things like that, can destroy the layouts in older/different browsers

*Set the container to inline-block because you dont want it to cover the whole width

.container-fluid {
      position: relative;
      display:inline-block;
      width:auto;
    }

    img {
      max-height: 100%;
    }

    .myB {
      position: absolute;
      top: 50%;
    }
    .myBRight{
      right:0px;
    }
    .myBLeft{
      left:0px;
    }

      <input class='myB myBLeft' type='button' value='<'>

      <input class='myB myBRight' type='button' value='>'>

A: I hope this will be helpfull, basically i set the position of button, or input nevermind, with the size of image. Obviusly the "background" of button element
overflows from the image, but if tou set the "position" of element with less px you'll set the arrow in the right position.
Sorry for my English..

img{
  width:400px;
  height:300px;
}

#next,
#prev{
  position:absolute;
  top:inherit;
}

#next{
  left:400px;
}

      <button id="prev" type="input" > < </button>
      <button id="next" type="input" > > </button>


text:
Q: Display characters with a delay between each in JAVA I want to make my text appear like its being typed..
like I want to print you ok then it must print like
y (delay) o (delay) u (delay) (delay) o (delay) k...
my this code works perfect but it always print in the new line
        String text = "you ok...:)";
        for(int i=1; i<=text.length();i++){

        System.out.print(text.substring(0, i));
        try {
            Thread.sleep(100);
            } catch (Exception e) {
            e.printStackTrace();
            }
        }

A: First problem is starting i from 1, it should start from 0. so charAt(0) is your first character.
secondly, you should only print the character by using text.charAt(i) not the whole substring.
hope this help:
   String text = "you ok...:)";
    for(int i=0; i<text.length();i++){

    System.out.print(text.charAt(i));
    try {
        Thread.sleep(100);
        } catch (Exception e) {
        e.printStackTrace();
        }
    }

A: Here is the working example which you wants ....
public class Stackoverflow {

public static void main(String[] args)
{
   String text = "you ok...:)";
   char[] charArr = text.toCharArray();

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

        System.out.print(charArr[i]);
        try
        {
            Thread.sleep(1000);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
}


text:
Q: C onefile program printing (on stdout) self complete source code I hear 3 years ago problem and apparently have infinity solutions.
I want to find one of this infinity set.
Problem: Write program (have only one file example "selfsource.c") who printing on stdout self source code and exits.
All techniques all alowed. Anyone can help me?

A: This is called a Quine.
Wikipedia has an example in C.

A: More examples than you could possibly need can be found at http://www.nyx.net/~gthompso/self_c.txt.

A: Google for quine programs.


text:
Q: bundling apollo useQuery hook with rollup I'm trying to create a package that exports functionality using useQuery
However I get the following error:
Could not find "client" in the context or passed in as an option. Wrap the root component in an <ApolloProvider>, or pass an ApolloClient instance in via options.

This is even with simplest possible example which just exports useQuery (obvs real code does more than this)
I know my code is ok otherwise as if I import useQuery using
import { useQuery } from '@apollo/react-hooks'

it works fine
simple example is here..
https://github.com/gilesbradshaw/use-query

A: The hook and the ApolloProvider used should be from the same module, otherwise the context used by the hook will be different than what is provided by the ApolloProvider. You should export ApolloProvider in your package in addition to the hook, and then make sure you import it from your package whereever you're using the hook.


text: Q: Failed to resolve play-service-places-placereport After adding com.google.android.gms:play-services-location:15.0.1 this dependencies i am getting failed to resolve play-service-places-placereport issue. And even if i add com.google.android.gms:play-service-places-placereport:15.0.1 also it is not resolve please help on this


text:
Q: Segfault in Cygwin but not VS, any ideas? It works with Visual Studio, but segfaults in Cygwin, which is weird because I'm compiling the same source, and both generate a Windows executable. GDB doesn't work very well for me in Cygwin for some reason, and the error doesn't appear in VS so I can't really debug it there.
Any ideas?
int main(void)
{
    Pair ***occurences = new Pair**[20];

    int i, j, k;
    for (i = 0; i < 20; i++)
    {
        occurences[i] = new Pair*[i+1];

        for (j = 0; j < i+1; j++)
        {
            occurences[i][j] = new Pair[26];

            for (k = 0; k < 26; k++)
            {
                Pair pair;
                pair.c = k + 'a';
                pair.occurs = 0;
                occurences[i][j][k] = pair;
            }
        }
    }

    std::fstream sin;
    sin.open("dictionary.txt");
    std::string word;

    while (std::getline(sin, word))
    {
        if (word.size() < 21)
        {
            for (i = 0; i < word.size(); i++)
            {
                // SEGFAULTING HERE
                occurences[word.size()-1][i][word[i] - 'a'].occurences++;
            }
        }
    }

    for (i = 0; i < 20; i++)
    {
        for (j = 0; j < i+1; j++)
        {
            delete [] occurences[i][j];
        }
        delete [] occurences[i];
    }
    delete [] occurences;

    return 0;
}

A: You marked this line as the critical point:
occurences[word.size()-1][i][word[i] - 97].occurs++;

All three array accesses might go wrong here, and you would have to check them all:
It seems like the first dimension of the array has the length 20, so the valid values for the index are [0..19]. word.size()-1 will be less than 0 if the size of the word is zero itself, and it will be larger than 19 if the size of the word is 21 or more.
Are you sure the length of the word is always in the range [1..20]?
The second dimension has variable length, depending on the index of the first dimension. Are you sure this never gets out of bound?
The third dimension strikes me as the most obvious. You subtract 97 from the character code, and use the result as index into an array with 26 entries. This assumes that all characters are in the range of [97..122], meaning ['a'..'z']. Are you sure that there will never be other characters in the input? For example, if there are any capital characters, the resulting index will be negative.

A: Just reformulating my comment as an answer:
occurences[word.size()-1][i][word[i] - 'a'].occurs++;
if word.size() is 100 (for example) this will crash (for i == 0) since occurences has only 20 elements.


text:
Q: New line after subsubsection with llncs class I get a new line after each chapter, section, and subsection, but not after anything lower than subsection, e.g. subsubsection or paragraph.
MWE:
\documentclass[runningheads]{llncs}

\usepackage[ngerman]{babel}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}

\begin{document}

\section{FooBar}
\dots
\subsection{BarFoo}
\dots
\subsubsection{Chakka}
\dots
\paragraph{Chu}
\dots

\end{document}

Do I have to use the titlesec package with the titleformat command or is there any other way?
(Off-topic: Is there a built-in function to include part of the compiled version as an image?)

A: This is how the class defines the sectional units:
\renewcommand\section{\@startsection{section}{1}{\z@}%
                       {-18\p@ \@plus -4\p@ \@minus -4\p@}%
                       {12\p@ \@plus 4\p@ \@minus 4\p@}%
                       {\normalfont\large\bfseries\boldmath
                        \rightskip=\z@ \@plus 8em\pretolerance=10000 }}
\renewcommand\subsection{\@startsection{subsection}{2}{\z@}%
                       {-18\p@ \@plus -4\p@ \@minus -4\p@}%
                       {8\p@ \@plus 4\p@ \@minus 4\p@}%
                       {\normalfont\normalsize\bfseries\boldmath
                        \rightskip=\z@ \@plus 8em\pretolerance=10000 }}
\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}%
                       {-18\p@ \@plus -4\p@ \@minus -4\p@}%
                       {-0.5em \@plus -0.22em \@minus -0.1em}%
                       {\normalfont\normalsize\bfseries\boldmath}}
\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}%
                       {-12\p@ \@plus -4\p@ \@minus -4\p@}%
                       {-0.5em \@plus -0.22em \@minus -0.1em}%
                       {\normalfont\normalsize\itshape}}

As you see, the fifth argument to \@startsection is negative for \subsubsection and \paragraph. Just make it positive. For instance:
\makeatletter
\renewcommand\subsubsection{\@startsection{subsubsection}{3}{\z@}%
                       {-18\p@ \@plus -4\p@ \@minus -4\p@}%
                       {4\p@ \@plus 2\p@ \@minus 2\p@}%
                       {\normalfont\normalsize\bfseries\boldmath
                        \rightskip=\z@ \@plus 8em\pretolerance=10000 }}
\renewcommand\paragraph{\@startsection{paragraph}{4}{\z@}%
                       {-12\p@ \@plus -4\p@ \@minus -4\p@}%
                       {2\p@ \@plus 1\p@ \@minus 1\p@}%
                       {\normalfont\normalsize\itshape
                        \rightskip=\z@ \@plus 8em\pretolerance=10000 }}
\makeatother

Negative values in that argument tell LaTeX to use a "runin" style.


text:
Q: Updates via TexLive Utility I have noticed that there has not been any updates to the distribution for a few weeks. I am wondering if this is as a result of there actually BEING no updates, or if there is something wrong with TexLive Utility? I have done several searches and have come up empty-handed.
Thanks,
DM

A: There will never again be updates to TeX Live 2015 or earlier. Soon, TeX Live 2016 will be available and that version will then get updates, so you will get updates if you install the new version.
There is an annual period during which the previous version of TeX Live is frozen and the new one is tested. Eventually, the new one is released and becomes the current version. At that point, users can install the new edition of TeX Live. That new version's tlmgr (the utility underlying TeX Live Utility) can then get updates for the new installation until it, in its turn, is frozen forever the following year.
Thus the cycle continues unto somewhere in the vicinity of eternity.


text:
Q: Как записать класс в std::vector Есть:
class Token {
    public:
        // DON'T DISTURB THE ORDER!!!
        lu  dist;
        hu length;
        BYTE character;
        // DON'T DISTURB THE ORDER!!!
    };

И указатель на пустой вектор: std::vector<BYTE>* block, где BYTE - unsigned char
Вопрос: Как записать Token в block и обратно

A: Поскольку Token является типом простой структуры данных, то объекты этого класса можно скопировать при помощи memcpy.
std::vector<BYTE>* block; // указывает на существующий вектор
Token token; // существующий объект

// Выделяем достаточно памяти чтобы поместить объект.
block->resize(sizeof(Token));

// Поскольку вектор изначально пустой мы можем писать в его начало.
std::memcpy(&block->at(0), &token, sizeof(Token));

А затем для чтения обратно можно опять использовать memcpy:
Token token2; // в него будет скопирован объект
std::memcpy(&token2, &block->at(0), sizeof(Token));

Пример можно посмотреть тут:
http://cpp.sh/5xm7u

Но это решение имеет свои ограничения. Одно из самых больших - данные не переносимые. То есть на системах с другими размерами базовых типов и другим порядком байтов значения не будут теми же.
Если цель - передача данных на другую систему, то стоит использовать системы сериализации. Например, protocol buffers, cereal или просто json.


text:
Q: SQL Repeat values where value is NULL I have created a summary view and using following query to get results
    SELECT captain.Name AS Name,
      rides.date AS date,
      rides.tr AS tr,
      rides.cr AS cr,
      rides.cg AS cg,
      rides.p AS p,
      rides.oe AS oe,
      (((rides.cr + rides.cg) - (rides.p +
      rides.oe)) - rides.tih) AS short,
     rides.tih AS tih,
     ct.tr AS tr,
     ct.ca AS ca
   FROM (rides
     JOIN captain ON captain.captainID = rides.captainID)
     JOIN ct ON captain.captainID = ct.captainID

output like this
date      tr    cr  cg  p   oe  short   tih tr  ca
---------------------------------------------------
12/6/2017 20    10  10  2   3    4      43  1   88
13/6/2017 10    9   9   2   3    1      56  1   88
14/6/2017 20    10  10  2   3    4      43  1   88
15/6/2017 10    9   9   2   3    1      56  1   88
16/6/2017 20    10  10  2   3    4      43  1   88
17/6/2017 10    9   9   2   3    1      56  1   88

But it should be
date      tr    cr  cg  p   oe  short   tih tr  ca
---------------------------------------------------
12/6/2017 20    10  10  2   3    4      43  0   0
13/6/2017 10    9   9   2   3    1      56  0   0
14/6/2017 20    10  10  2   3    4      43  0   0
15/6/2017 10    9   9   2   3    1      56  0   0
16/6/2017 20    10  10  2   3    4      43  1   88
17/6/2017 10    9   9   2   3    1      56  1   88

because in ct table I have only two records for 16 and 17 June.
How to force to show 0 when no records available.
Hope that I have explained properly what i need. Thanks in advance.

A: Use LEFT JOIN (left outer join) on the last line.
SELECT captain.Name AS Name,
  rides.date AS date,
  rides.tr AS tr,
  rides.cr AS cr,
  rides.cg AS cg,
  rides.p AS p,
  rides.oe AS oe,
  (((rides.cr + rides.cg) - (rides.p +
  rides.oe)) - rides.tih) AS short,
 rides.tih AS tih,
 ct.tr AS tr,
 ct.ca AS ca
 FROM (rides
 JOIN captain ON captain.captainID = rides.captainID)
 LEFT JOIN ct ON (captain.captainID = ct.captainID and rides.date=ct.date)

A: Join on date as well with ct table. Use case when to substitute blank values to 0
Try this:-
   SELECT captain.Name AS Name,
      rides.date AS date,
      rides.tr AS tr,
      rides.cr AS cr,
      rides.cg AS cg,
      rides.p AS p,
      rides.oe AS oe,
      (((rides.cr + rides.cg) - (rides.p +
      rides.oe)) - rides.tih) AS short,
     rides.tih AS tih,
     case when ct.tr is NULL and ct.tr=' ' then 0 else ct.tr END AS tr,
     case when ct.ca is NULL and ct.ca=' ' then 0 else ct.ca END AS ca,
   FROM (rides
     JOIN captain ON captain.captainID = rides.captainID)
    LEFT JOIN ct ON rides.captainID = ct.captainID and rides.date=ct.date


text:
Q: Evaluation of $\lim_{x\to 0} \frac{(1+x)^{1/x}-e+\frac{ex}{2}}{x^2}$ Evaluate the following limit:
$$L=\lim_{x\to 0} \frac{(1+x)^{1/x}-e+\frac{ex}{2}}{x^2}$$
Using $\ln(1+x)=x-x^2/2+x^3/3-\cdots$
I got $(1+x)^{1/x}=e^{1-x/2+x^2/3-\cdots}$
Could some tell me how to proceed further?

A: Indeed, the expansion of $(1+x)^{1/x}$ about $x=0$ is $e - \frac{ex}{2} + \frac{11e}{24} x^2 + O(x^3)$, so the limit is then $\dfrac{11e}{24}$.
--
To get this expansion, start with
$$(1+x)^{1/x} = \exp \left({1 - x/2 + x^2 / 3 - \dots}\right)$$
which you already found and put this into the power series of $\exp$ to get
$$\sum_{n=0}^{\infty} \frac{(1 - x/2 + x^2/3 - \dots)^n}{n!}$$
The coefficient of $x^0$ is
$$\sum_{n=0}^{\infty} \frac{1}{n!} = e$$
The coefficient of $x^1$ in $\dfrac{(1-x/2+x^2/3 - \dots)^n}{n!}$ is $-\frac{n/2}{n!}$, hence the coefficient in total is
$$\sum_{n=1}^{\infty}  -\frac{1}{2 (n-1)!} = -\frac{e}{2}$$
I'll leave the coefficient of $x^2$ to you. (It's the hardest, but not too bad).

A: You can proceed in the following manner
\begin{align}
L &= \lim_{x \to 0}\dfrac{(1 + x)^{1/x} - e + \dfrac{ex}{2}}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1\right) - 1 + \dfrac{x}{2}}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1\right) - \exp\left(\log\left(1 - \dfrac{x}{2}\right)\right)}{x^{2}}\notag\\
&= e\lim_{x \to 0}\exp\left(\log\left(1 - \dfrac{x}{2}\right)\right)\cdot\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)\right) - 1}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\exp\left(\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)\right) - 1}{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}\cdot\dfrac{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\dfrac{\log(1 + x)}{x} - 1 - \log\left(1 - \dfrac{x}{2}\right)}{x^{2}}\notag\\
&= e\lim_{x \to 0}\dfrac{\left(1 - \dfrac{x}{2} + \dfrac{x^{2}}{3} + o(x^{2})\right) - 1 + \left(\dfrac{x}{2} + \dfrac{x^{2}}{8} + o(x^{2})\right)}{x^{2}}\text{ (using Taylor series)}\notag\\
&= e\left(\frac{1}{3} + \frac{1}{8}\right)\notag\\
&= \frac{11e}{24}\notag
\end{align}
The above approach uses the standard limit $$\lim_{t \to 0}\frac{\exp(t) - 1}{t} = 1$$ Taylor series is used only when necessary and this approach avoids any multiplication/division of infinite series.

A: It's a well-known fact that $$\log(1+x)=x-\dfrac{x^2}2+\dfrac{x^3}3+\underset{x\to 0}{o}(x^3)$$
Hence we get $$\dfrac 1x\log(1+x)=1+u(x)$$ where $$u(x)=-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)$$
Notice that $$\lim_{x\to 0} u(x)=0$$
We can write $$(1+x)^{1/x}=ee^{u(x)}$$
But we know that $$e^u=1+u+\dfrac{u^2}2+\underset{u\to 0}o(u^2)$$
Now using the identity $$(a+b+c)^2=a^2+b^2+c^2+2ab+2bc+2ac$$
we quickly find, since we only need the terms whose degrees are less than three (the other terms are all some $\underset{x\to 0}o(x^2)$), that
$$(u(x))^2=\left(-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)\right)^2=\dfrac{x^2}4+\underset{x\to 0}o(x^2)$$
Hence, since $\displaystyle\lim_{x\to 0}u(x)=0$, we see than an $\underset{u\to 0}o(u^2)$ function is an $o(x^2)$ when $x$ tends to $0$.
This leads to
$$\begin{align*}(1+x)^{1/x} & = e\left(1+\left(-\dfrac x2+\dfrac{x^2}3+\underset{x\to 0}{o}(x^2)\right)+\dfrac 12\left(\dfrac{x^2}4+\underset{x\to 0}o(x^2)\right)+\underset{x\to 0}{o}(x^2)\right)\\ & = e-\dfrac{ex}2+\dfrac{11e}{24}x^2+\underset{x\to 0}o(x^2)\end{align*}$$
And so :
$$\dfrac{(1+x)^{1/x}-e+\dfrac{ex}2}{x^2}=\dfrac{11e}{24}+\underset{x\to 0}o(1)$$
which means exactly that $$\lim_{x\to 0}\dfrac{(1+x)^{1/x}-e+\dfrac{ex}2}{x^2}=\dfrac{11e}{24}$$


text:
Q: Can't declare number type in Julia According to http://julia.readthedocs.org/en/latest/manual/integers-and-floating-point-numbers/, one should be able to do this:
julia> Float32(-1.5)
-1.5f0

Instead, I get:
julia> Float32(-1.5)
ERROR: type cannot be constructed

This happens for all other attempts to use this syntax, e.g. x = Int16(1)
I'm on 0.3.10.

A: You are on 0.3.10 but reading the manual for 0.5. In the manual for 0.3 http://julia.readthedocs.org/en/release-0.3/manual/integers-and-floating-point-numbers/
Values can be converted to Float32 easily:

julia> float32(-1.5)
-1.5f0

julia> typeof(ans)
Float32


text:
Q: java.lang.ClassNotFoundException: com.opensymphony.xwork2.util.ValueStack Struts2 with JSP
I have a project with Struts2, JSP and Tomcat 6.0
I am new to Struts2
Getting error message in server trace when i try to check the message in JSP through Struts2 but i am not sure why i am getting this below error
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.ClassNotFoundException: com.opensymphony.xwork2.util.ValueStack
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at java.lang.Class.getDeclaredMethods0(Native Method)
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
    at java.lang.Class.privateGetPublicMethods(Class.java:2651)
    at java.lang.Class.getMethods(Class.java:1467)
    at java.beans.Introspector.getPublicDeclaredMethods(Introspector.java:1280)
    at java.beans.Introspector.getTargetMethodInfo(Introspector.java:1141)
    at java.beans.Introspector.getBeanInfo(Introspector.java:416)
    at java.beans.Introspector.getBeanInfo(Introspector.java:163)
    at java.beans.Introspector.getBeanInfo(Introspector.java:250)
    at java.beans.Introspector.<init>(Introspector.java:397)
    at java.beans.Introspector.getBeanInfo(Introspector.java:163)
    at org.apache.jasper.compiler.Generator$TagHandlerInfo.<init>(Generator.java:3924)
    at org.apache.jasper.compiler.Generator$GenerateVisitor.getTagHandlerInfo(Generator.java:2187)
    at org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1643)
    at org.apache.jasper.compiler.Node$CustomTag.accept(Node.java:1530)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
    at org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
    at org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
    at org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
    at org.apache.jasper.compiler.Generator.generate(Generator.java:3474)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:231)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:723)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:744)

Jars are listed below:
asm-3.3
asm-commons-3.3
asm-tree-3.3
struts2-api-2.0.1
struts2-convention-plugin-2.3.16.3
struts2-core-2.3.16.3

A: You have to add xwork.jar
PS:You should use maven for dependency management


text:
Q: Remark 16 in Chapter 2 from Brezis - Functional Analysis, Sobolev Spaces, and Partial Differential Equations. Let $E,F$ be two Banach Spaces and $A : D(A) \subset E \to F$ be a linear unbounded operator which is densely defined. Now, we would like to define $A^{*}$ as the adjoint of $A$. Let $A^{*} : D(A^{*}) \subset E^{*} \to F^{*}$ be unbounded operator. The domain of $A^{*}$ is defined as $D(A^{*}) = \{ v \in F^{*} \, | \, \exists c \geq 0 \forall u \in D(A) \ni |\langle v, Au \rangle_{F^{*},F} | \leq c ||u||\}$.
Here, $E^{*}$ and $F^{*}$ are the dual spaces of $E$ and $F$ respectively.

Remark 16
If A is a bounded operator, then $A^{*}$ is also a bounded operator.
So, to see Remark 16, the book says that it is clear that $D(A^{*}) = F^{*}$. My idea is since we know by default that $D(A^{*}) \subset F^{*}$. So I want to claim that $F^{*} \subset D(A^{*})$. This is my attempt :
Take $v \in F^{*}$. Since $A$ is bounded linear operator, then we have :
$\forall u \in D(A), |\langle v, Au \rangle|_{F^{*},F}\leq ||v||_{F^{*}}||Au||_{F}\leq ||v||_{F^{*}}||A||_{\mathcal{L}(E,F)}||u||_{E}$. Choose $c = ||v||_{F^{*}}||A||_{\mathcal{L}(E,F)} \geq 0$ and thus $v \in D(A^{*})$.
My question : Is my reasoning correct? Also, I use Cauchy-Schwarz to obtain $|\langle v, Au \rangle|_{F^{*},F}\leq ||v||_{F^{*}}||Au||_{F}$. Can I use Cauchy-Schwarz Inequality here for the dual pairing?
Any help will be much appreciated!


text:
Q: How to create LyX inset without text-box (input box)? I'm working on a custom layout file for LyX, I'd like to create a custom inset without the text/input box. I've seen other commands from the insert menu without it, such as "Page Break", but I haven't found where these are defined (attempted a grep search but came up empty).
At the moment this is what the code looks like:
InsetLayout MyInset
      LyxType       Custom
      LabelString   "My Inset"
      LatexType     Command
      LatexName     myLatexCommand
      Preamble
        \newcommand{\myLatexCommand}{
          Some output from command \\
        }
      EndPreamble
End

This produces the following in LyX:

And in the compiled document:

If I can't remove the input box, can I put a pre-filled text informing that it is not to be used and suppress its output in the compiled document?
Also is there any good exhaustive documentation/list of available style commands for LyX layouts? I've attempted to find any API-style list for creating layouts in LyX but come up short.


text:
Q: Copy input type="date" value to another input type="date" jquery Good day! I am creating a web based application where in, one of its function is to copy the selected date in the input type="date" form to another input type="date" input. How can I do this? I am trying to do this as I can, but still, I can't make it. Please response if someone knows it, thank you very much!

A: Using a id selector you can achieve.
<input type="date" id="date1" value="" />

<input type="date" id="date2" value="" />

Jquery code.
$(document).ready(function(){
$('#date1').blur( function(){
     $('#date2').val($(this).val());
});
});

Provided you can add unique id selectors in the html.


text:
Q: Add a free gift that has different sizes set via custom options? I am currently building a site and I am looking to give customers a free item of clothing with every purchase. I am using this extension below to try to achieve this:
http://www.magentocommerce.com/magento-connect/gift-rules-5571.html
When the customer orders anything from the site they should see a free pair of slippers appear in the basket. However the issue is that everyone needs to select the shoe size so they get the right ones.
I tried creating a product that had a required custom field of "Size" but when I added the rule to put that item as a free gift the system crashed and this was because the item was added with a required field that was empty.
Then I made that field not required and it worked thinking that the customer could edit the product in the basket and pick a different size, however when they do that a new pair of slippers is added to the cart at full price and the one set as gift isn't updated.
Has anyone got any ideas on how I can achieve this using either the extension I have installed or by another way?
Thanks

A: As @Sukeshini already mentioned in the comments above, what you are looking to do is adding configurables, not simples.
You are attempting to re-create the configurable product type and functionality  by using a simple product with option(s). Do-abble, yes, but you are going down a dark rabbit hole, with many days of frustration and issues ahead of you.
Noted on the extension page that you are using, it clearly states

only simple products are supported as gifts

(and most likely not simples with options  - ask the developer of that module about that ability)
thus I gather this is why you are trying the approach you are doing - attempting to stay within the capabilities of the module selected.
Do it right. Create configurables, and gift those. You will end up with way less hassles, bugs and sleepless nights of frustration.
You want to find a gifting module that supports the ability to gift configurables.
There are a few about, and there is one available on my own magento extension store, which comes with super support ;) (blatant self promotion - http://www.proxiblue.com.au/magento-gift-promotions.html)


text:
Q: Verifying connection pooling server side with CONTEXT_INFO on I'm working with a 3 tiered application, Microsoft Dynamics AX, where the middle tier maintains connections to a SQL Server. Several clients connect to this middle tier server.
The middle tier server typically has several connections open to the SQL Server, so I'm pretty sure they are being pooled, however there is no documentation available as to how this is implemented.
Normally we cannot relate SPIDs to users or client applications, but there is an option where we can set a registry key (specific to Microsoft Dynamics AX) which makes this information available in the context_info field of sys.dm_exec_sessions.
Again, there is no documentation about how this is implemented. The only information we have on this is a vague blog entry on MSDN.
The post mentions

Adding  this information has a small performance overhead.

So as we don't know any of the implementation details such as:

*

*Is the information somehow included in the connection string or is this done by SET CONTEXT_INFO?

*When are connections reused?

*What exact impact can be expected

Is there any way to determine server side how the connection pooling is working and what the impact of the context_info is?
update:
Using this query from here
SELECT des.program_name,
       des.login_name,
       des.host_name,
--       der.database_id,
       COUNT(des.session_id) AS [Connections]
FROM sys.dm_exec_sessions des
INNER JOIN sys.dm_exec_connections DEC
        ON des.session_id = DEC.session_id
WHERE des.is_user_process = 1
--AND des.status <> 'running'
GROUP BY des.program_name,
         des.login_name,
         des.host_name
--         ,der.database_id
HAVING COUNT(des.session_id) > 2
ORDER BY COUNT(des.session_id) DESC

I can see connection pooling is used.

A: First, CONTEXT_INFO is a property of the session, not the connection. It gets reset by sp_reset_connection when the same session is reused and the first batch is executed. It seems that CONTEXT_INFO was not reset in SQL Server 2000 and possibly earlier versions, but starting with SQL Server 2005 it is definitely reset to NULL.
Part of the confusion here is that the question is specific to "Microsoft Dynamics AX" since general .NET programming wouldn't have the registry key noted in that blog article. Also, the information that Microsoft Dynamics is then storing in CONTEXT_INFO is its application session details, which have nothing to do with SQL Server SPIDs and cannot be used to infer that connection pooling is occurring since the application session will naturally span multiple connections as well as SPIDs.
The mechanism being used to set CONTEXT_INFO pretty much has to be a separate, additional query executed prior to any other queries for that session. Something along the lines of:
SqlConnection _Connection = new SqlConnection("{connection-string}");
_Connection.Open();

if(_IsConnectionContextRegistryKeySet)
{
  SqlCommand _Command = _Connection.CreateCommand();
  _Command.CommandType = CommandType.Text;

  _Command.CommandText = @"DECLARE @BinaryInfo VARBINARY(128);
                           SET @BinaryInfo = CONVERT(VARBINARY(128), @StringInfo);
                           SET CONTEXT_INFO @BinaryInfo;";

  SqlParameter _ParamInfo = new SqlParameter("@StringInfo", SqlDbType.VarChar, 100);
  _ParamInfo.Value = String.Format("{0} {1} {2}...", AXuserID, AXsessionID, ...);
  _Command.Parameters.Add(_ParamInfo);

  _Command.ExecuteNonQuery();
  _Command.Dispose();
}

Hence, the small amount of additional overhead incurred for enabling this info to be set comes from the execution of this additional query.
Second, you can test for connection pooling by using SQL Server Profiler. Select the "RPC:Completed" event in the "Stored Procedures" category, make sure that "TextData", "ClientProcessID", and "SPID" are checked for that event (at the very least, you can select other columns if you like). Then, go to "Column Filters", select "TextData", and in the "Like" condition add the following condition: exec sp[_]reset[_]connection. Now run that trace. If you see instances of exec sp_reset_connection coming through, then that is due to connection pooling being used.
Additionally, there are two side-effects of connection pooling that may or may not show up in the DMVs depending on how many connections are being requested. The following query should capture many / most of the connections that are pooled (please note that it has nothing to do with CONTEXT_INFO):
SELECT sssn.login_time,
       DATEDIFF(MILLISECOND, conn.connect_time, sssn.login_time)
                  AS [MillisecondsBetweenConnectionAndSessionStart],
       conn.*
FROM sys.dm_exec_connections conn
INNER JOIN sys.dm_exec_sessions sssn
        ON sssn.session_id = conn.session_id
WHERE conn.session_id <> conn.most_recent_session_id
OR    DATEDIFF(MILLISECOND, conn.connect_time, sssn.login_time) > 50
ORDER BY conn.connect_time;

This query looks for the following indications of connection pooling being used:

*

*Current session_id is not the same as the prior session_id. If these two IDs are the same then it may or may not be a connection that is using pooling, since the same SPID can be reused. But, if they are different, then that can only be the result of connection pooling.

*Time between the connection being made and time that the session starts is over 50 milliseconds (though that threshold might vary by system). Usually the first session to get created upon a connection is less than 30 milliseconds after the connection, but it "generally" shouldn't be above 50, even if executing multiple SqlCommands.

Along similar lines, it should also be possible to test for connection pooling by creating a temp table, and every few seconds, capturing both [session_id] (INT) and [connection_id] (UNIQUEIDENTIFIER) from sys.dm_exec_connections. Then, just look for rows that have the same connection_id but different session_id.
Finally, the query posted in the question is not valid for indicating connection pooling with respect to most web applications. The issue here is that typically, the properties of "program_name", "login_name", and "host_name" would be the same for all connections made by web/app server (hence the need for the per-processor / per-core licensing models instead of just having the CAL model).

A: Regarding Connection Pooling, Thomas Stringer has posted: http://blogs.msdn.com/b/sql_pfe_blog/archive/2013/10/08/connection-pooling-for-the-sql-server-dba.aspx
The simple thing to know is: "The answer that enterprise DBAs need to be giving to these inquiries is that it is provider-specific. In other words, it is on the client/application side that connection pooling is handled."
The CONTEXT_INFO, which is stored in binary, needs to be set by the application.  CONTEXT_INFO is just a small bucket available to contain useful information such as the user's Name / ID / Login.  (Or whatever else you want to stuff in the small space available.)
The overhead is small, but it is an extra step to insert and extract the BINARY data in CONTEXT_INFO.  (But useful for systems that run under a service account, so that you can know whose connection this is at the moment.)
Thanks to srutzky for clarifying that a pooled connection is reset, but it is not dropped. At least not immediately.
A post by Nacho Alonso Portillo offers clarification: http://blogs.msdn.com/b/ialonso/archive/2012/06/04/how-to-determine-whether-a-connection-is-pooled-or-nonpooled.aspx
In part it says the "sp_reset_connection... does the following tasks: 1) cleans up the session context ... which includes ... resets the CONTEXT_INFO; ... 2) notifies them of the occurrence of a successful logout... 3) initiates the process of redoing the login."


text:
Q: MCU strange failure I am using a STM32F4 chip to build a control device product.
We received a report from our customer that our device does not work properly after having been work half an hour. Even reset does not help.
Then we take the controller back to our lab. We tried to reset the device. It failed to work. Then we thought the MCU could be destroyed and tried to re-burn program into it.
The device then works properly.
What could be the reasons for that phenomenon? Could it be caused by ESD or something?

A: Sounds like you are experiencing flash corruption. That can occur with micros that are capable of writing their own program memory, and that memory is not adequately protected.
The proximate cause might be ESD or EMI or a bad power-on reset/brownout causing the processor to run amuck, but the problem may be that your chip is not configured to protect its memory.
There is generally a power supply voltage range below which the chip is not guaranteed to operate correctly, but you cannot guarantee that it cannot write its own memory (EEPROM or flash). The chip must be forced into reset in that range, if necessary by an external circuit if the internal BOR isn't up to the task.
Usually, by using all the hardware features the microcontroller manufacturer provides (locking and BOR in particular), adding external circuits if necessary  and using a micro that has reset on invalid address and by robust EMI/ESD design (proper ground planes and keeping noise out in the first place) these problems can be minimized. You might still get a few if you have a million units in the field.

A: We used to have problems of this sort with other microcontrollers. The problem was tracked down to inadequate programming of the devices.
Depending on the memory type used in the microcontroller, it is possible to partially program the chip and have it work normally for some period of time. But some charge leaks off some of the cells because the proper programming procedure wasn't followed.
Again, depending on the flash memory used within the device, some devices use a program, then verify process where the cells are written incrementally. After the cell verifies, a specified number of programming cycles are performed to "over-progrsm" the cell.
This process is repeated until all of the cells are programmed.
The problem we had back then was an improper programming algorithm.

A: Two causes are likely:

*

*Brownout: Most modern µC have brownout detection, but it may not be enabled as default because it cosumes some power. A brownout is a
condition where the voltage rails go below the safe operating limits.
The effects would be random, damage to flash memory is possible.

*The customer connected a debugger to the µC and made a mistake trying to read the program out of flash memory. Some debugging setups erase the flash as first step.
ESD is not a likely cause, there should be some other damage to the chip.
Further analysis would require a readout of the original (not working) flash memory content.


text:
Q: How to merge nested arrays of varying lengths, given they share an element in Ruby? I have nested arrays made up of strings and ints, of which I want to consolidate according to the first element of each array. Let's say these are item ids. The nested arrays are of varying length but as long as the first element of each nested array are the same, I want to merge them together.
My data might look like this:
arr = [['00', 'apples', nil, nil, 8],
['00', 'apples', nil, 2],
['00', 'apples', nil, nil, nil, 3],
['01', 'bananas', 2],
['01', 'bananas', nil, nil, 3],
['01', 'bananas', nil, 5]]

So I would like to condense these arrays so they look like:
arr = [['00', 'apples', nil, 2, 8, 3],
['01', 'bananas', 2, 5, 3]]

There won't be an instance where the second element (in this case apples or bananas) will be different for the given first element (00 or 01). So as long as the first element is the same between any two of the nested arrays, I want to merge them together.
Also, the data guarantees no collisions between the numbers for arrays sharing the same first element. However, the numbers should maintain their index positions post-merge. This is crucial.
I'm not quite sure how to approach this. I was thinking of creating an empty array and then iterating through the nested arrays checking to see if the first element is contained in the new array. If not, push that array to the new array. If so, merge them. The code I have doesn't work (I get an empty array)...
    new_array = Array.new
    old_array.each do |o|
      new_array.each do |n|
        if o[0] == n[0]
          n = o | n
        else
          n.push(o)
        end
      end
    end

I looked into .reduce(:|) but it gives me undesired results:
arr = [["00", "apples", nil, nil, nil, 8],
 ["00", "apples", nil, nil, nil, nil, 1],
 ["00", "apples", nil, nil, 1]]
arr.reduce(:|)
=> ["00", "apples", nil, 8, 1]

I was expecting: => ["00", "apples", nil, nil, 1, 8, 1]

A: There are several ways to do this. One is to use Enumerable#group_by. Others may mention methods which merge hashes.
arr = [
  ['00', 'apples', nil, nil, 8],
  ['00', 'apples', nil, 2],
  ['00', 'apples', nil, nil, nil, 3],
  ['01', 'bananas', 2],
  ['01', 'bananas', nil, nil, 3],
  ['01', 'bananas', nil, 5]
]

arr.group_by(&:first).values.map { |a| a.reduce(:|) }
  #=> [["00", "apples", nil, 8, 2, 3], ["01", "bananas", 2, nil, 3, 5]]

These are the steps:
b = arr.group_by(&:first)
  #=> {"00"=>[["00", "apples", nil, nil, 8], ["00", "apples", nil, 2],
  #           ["00", "apples", nil, nil, nil, 3]],
  #    "01"=>[["01", "bananas", 2], ["01", "bananas", nil, nil, 3],
  #           ["01", "bananas", nil, 5]]}
c = b.values
  #=> [[["00", "apples", nil, nil, 8], ["00", "apples", nil, 2],
  #     ["00", "apples", nil, nil, nil, 3]],
  #    [["01", "bananas", 2], ["01", "bananas", nil, nil, 3],
  #     ["01", "bananas", nil, 5]]]
c.map { |a| a.reduce(:|) }
  #=> [["00", "apples", nil, 8, 2, 3], ["01", "bananas", 2, nil, 3, 5]]

The first element of c is passed to map's block and assigned to the block variable:
a = [["00", "apples", nil, nil, 8], ["00", "apples", nil, 2],
     ["00", "apples", nil, nil, nil, 3]]

a.reduce(:|) gives the same result as a.reduce { |d,e| d | e }, which is merely the union of the three elements (arrays) of a:
(["00", "apples", nil, nil, 8] | ["00", "apples", nil, 2]) |
["00", "apples", nil, nil, nil, 3]]
  #=> ["00", "apples", nil, 8, 2] | ["00", "apples", nil, nil, nil, 3]
  #=> ["00", "apples", nil, 8, 2, 3]

A similar calculation is performed for the second element of a passed to map's block.

A: You could use a hash and convert it to an array
new_hash = {}
old_array.each do |o|
  new_hash[o[0]] ||= []
  o.each_with_index do |n, i|
    new_hash[o[0]][i] ||= n
  end
end

puts new_hash.inspect
puts new_hash.map { |k,v| v }.inspect

This will result in
{"00"=>["00", "apples", nil, 2, 8, 3], "01"=>["01", "bananas", 2, 5, 3]}
[["00", "apples", nil, 2, 8, 3], ["01", "bananas", 2, 5, 3]]


text:
Q: Original iPad, CSS3 transforms, and limitations on imaging caused by RAM I've found some very weird quirks to the original iPad on iOS 5.0.1, and they seem to be effected by the amount of images loaded into the browser at a time.
I've found things rendered at half resolution or less.  (This does not happen on the iPad 2 and reducing images loaded in the background has reduce some of these glitches)
Are there any ways to prioritize elements for RAM storage or rendering?

A: Preloading images in javascript might do the trick, lookup:
http://elouai.com/javascript-preload-images.php


text:
Q: Chromedriver, Google Chrome, Linux, headless, using client (authentication) certificate I am running automated tests under Linux (CentOS) in headless mode.
I got a site where I need to provide an SSL certificate for HTTP SSL client authentication. The file is .p12 format, I installed it the same way on two machines (VM running CentOS with UI, the other is a normal headless server, again running CentOS).
Using pk12util I installed the certificate in the browser store, confirmed successful installation, then added the policy for Chrome to use the certificate automatically for the website in question.
Now the fun starts. In the VM where I have UI, I run the browser in headful mode, everything works perfectly. However, when on either machine I run the browser in headless mode, I need it to run headless for the server, I get the following errors in the driver log:
[DEBUG]: DevTools WebSocket Response: Page.navigate (id=18) 5944A53229353F1849E7D2D15FA4A11C {

"errorText": "net::ERR_SSL_PROTOCOL_ERROR",

"frameId": "5944A53229353F1849E7D2D15FA4A11C",

"loaderId": "4F3404B14470DD65090915C651B3D3EC"

}

...

[cf5020dd474256cce9c41538b1ffa0c2] RESPONSE Navigate ERROR unknown error: net::ERR_SSL_PROTOCOL_ERROR

While running in headless mode, I switched on the debug port, 9222, and I see in the Network tab that the request failed with the error "Failed to load response data: No resource with given identifier found".
Before installing the SSL certificate I had the same error in headful mode, but when I installed the certificate and added the policy, it went away, which makes me think that for whatever reason, the headless Chrome can't find the certificate.
Did I miss something? Can we provide SSL client certificates in headless mode? Does anybody have any suggestions?
Thanks!
PS: In headless mode the browser is started with the usual flags: acceptInsecureCerts=true, --ignore-certificate-errors, --ignore-urlfetcher-cert-requests.
I am running under CentOS 7.9, Chrome v.99

A: Well I actually found the answer.
Unfortunately, it does not work!!!
It is all explained in the following issue.
Issue 1310715: Headless Chrome not using installed client (authentication) certificates from the store.
This issue shows the steps to reproduce.
UserAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36
Steps to reproduce the problem:
Have a website behind a webserver that has browser client authentication with an SSL certificate.
Install the certificate in the certificate store of Chrome under $HOME/pki/nssdb folder. My certificate was in pk12 format, so I used pk12util to install it.
The installation must exit with: 'pk12util: PKCS12 IMPORT SUCCESSFUL' message.
Add a policy to your website under /etc/opt/chrome/policies/managed, so that Chrome provides the certificate automatically to the site's webserver.
Open the website.
What is the expected behavior? When the browser is started in headless or headful mode, the browser should provide the certificate to the webserver and proceed further.
What went wrong? Only in headful mode does the browser provide the certificate to the webserver. Headless mode does not. There's this error in the logs:
The issue response states the following:
Headless Chrome doesn't currently implement client certs. Switching this to a feature request that the headless folks can triage. Mechanically, client certs are come out of //content via CreateClientCertStore and SelectClientCertificate. Headless doesn't have a way to show UI, so it always continues without a client certificate.
https://bugs.chromium.org/p/chromium/issues/detail?id=1310715&q=component%3AInternals%3EHeadless&can=2


text:
Q: Use of "What" and third person singular form of verb
People know what they do; frequently they know why they do what they do; but what they don't know is what what they do does.

Quite unusually, in this sentence "what" occurs twice  and third person verb form "does" appears after the verb "do." Can you please help to understand what kind of sentence is it?

A: The OP's sentence:

People know what they do; frequently they know why they do what they do; but what they don't know is what what they do does.

It is always a lot easier to understand a long sentence if you break it into segments:

*

*People know what they do; frequently they know why they do [what they do]; but what they don't know is what [what they do] does.

The "what they do" acts as the object. You can understand it as one word "what-they-do" - something that they do. The last part means that "The people don't know what (what they do) does".


text:
Q: Fragment TextView Not Changed Back Locale I have very wierd problem when translate the app using translations editor.
So I did like the following( https://stackoverflow.com/a/66483251/14446860 ) and it work,I have 3 activies,when I press the button in the first activity it changes the language perfectly for all activities.
However when I change the language back to default,the first activity and the third activity are perfect restored,but the second activity(Map activity) textview is not changing,even if I re-install the app and doesn't press the change language button,the second activity is not in the default language..
This is app Manifest:
<activity android:name=".MainActivity"
    android:launchMode="singleTop"
    android:configChanges="locale"
    android:screenOrientation="portrait">

    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity>

<activity
    android:name=".MapsActivity"
    android:screenOrientation="portrait"
    android:launchMode="singleTop"
    />

The string file in default folder:
<string name="contact_name">Test:</string>
<string name="destination">Test:</string>
<string name="messageMaps">Test:</string>

The string file in the language folder:
<string name="contact_name">בדיקה:</string>
<string name="destination">בדיקה:</string>
<string name="messageMaps">בדיקה:</string>

The button:
    Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (LANG_CURRENT.equals("en")) {
                changeLang(getApplicationContext(), "iw");
                getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

            } else {
                changeLang(getApplicationContext(), "en");
            }
            finish();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));

        }
    });

Thank you !

A: So after few hours,I figure out what the problem was.
The problem was I extended FragmentActivity:
public class MapsActivity extends **FragmentActivity** implements OnMapReadyCallback {

And I should have declared AppCompatActivity:
public class MapsActivity extends **AppCompatActivity** implements OnMapReadyCallback {

I knew I would spend hours about something like that ..
Thank you anyway !