text:
Q: How would one Regex Match only the first few characters of a string in Python? Let's say I got these strings:
P 1 (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833
A1 AMBU 18177 Binnendams 3373AE Hardinxveld-Giessendam HARDGD bon 81505
Prio 4(DIA: ja) AMBU 17104 F. Bordewijkstraat 3069WB Rotterdam ROTTDM bon 29230
I've written the following regex to test on them:
^[ABP]\s?\d{1,3}|^PRIO\s?[1-5]|^\d{1,3}e?

How would I be able to only test the first 8 characters of this string? I've tried the following:
import re

str_to_test = "P 1 (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833"
expr = re.compile(r"^[ABP]\s?\d{1,3}|^PRIO\s?[1-5]|^\d{1,3}e?", re.IGNORECASE)
result = re.sub(expr, '', str_to_test);
print(result) #  (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833

But this does the entire string, which is not what I want. I've tried changing str_to_test to str_to_test[:8] to get the first 8 characters, but this removes the rest which I also need. Please help me out here.
The output I would like to see:
P 1 (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833 -> (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833
A1 AMBU 18177 Binnendams 3373AE Hardinxveld-Giessendam HARDGD bon 81505 -> AMBU 18177 Binnendams 3373AE Hardinxveld-Giessendam HARDGD bon 81505
Prio 4 (DIA: ja) AMBU 17104 F. Bordewijkstraat 3069WB Rotterdam ROTTDM bon 29230 -> (DIA: ja) AMBU 17104 F. Bordewijkstraat 3069WB Rotterdam ROTTDM bon 29230

A: You can use slices, change:
result = re.sub(expr, '', str_to_test);

To:
result = re.sub(expr, '', str_to_test[:8])+str_to_test[8:];

To get a better insight as to how the slices works:
a = '1234567890'

print(a[:8], a[8:])

Output:
12345678 90

A: There's no need to extract slices and reconstruct the string afterwards; you can extract whatever you want within a single regex match. You can enclose the part of the string you're interested in within a capturing group:
(?:^[ABP]\s?\d{1,3}|^PRIO\s?[1-5]|^\d{1,3}e?)\s*(?P<main>.*)

The first group, (?:^[ABP]\s?\d{1,3}|^PRIO\s?[1-5]|^\d{1,3}e?), which is the part that you want to discard, is non-capturing, while the part of the string that you're interested in, which is whatever comes after it, is enclosed in the named group (?P<main>.*).
Thus, to extract it, you match the above pattern to the whole string and then extract the group named main:
import re

str_to_test = "P 1 (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833"
pattern = re.compile(r"(?:^[ABP]\s?\d{1,3}|^PRIO\s?[1-5]|^\d{1,3}e?)\s*(?P<main>.*)", re.IGNORECASE)
match = pattern.match(str_to_test)
result = match.group("main")
print(result)

Output:
(BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833

A: If you need to quick replacement you can use re.sub(). Once you define the pattern, and create a list with all the strings you wish to work on, you can ue a list comprehension to address the issue:
import re
strings = ['P 1 (BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833',
           'A1 AMBU 18177 Binnendams 3373AE Hardinxveld-Giessendam HARDGD bon 81505',
           'Prio 4(DIA: ja) AMBU 17104 F. Bordewijkstraat 3069WB Rotterdam ROTTDM bon 29230']
pattern = re.compile(r'^[ABP]\s?\d{1,3}|^Prio\s?[1-5]|^\d{1,3}e?')
strings_clean = [re.sub(pattern,'',x).strip() for x in strings]

This outputs:
['(BNN-03) Voertuig te water Curacaostraat Groningen 011810 011871 013593 011833',
 'AMBU 18177 Binnendams 3373AE Hardinxveld-Giessendam HARDGD bon 81505',
 '(DIA: ja) AMBU 17104 F. Bordewijkstraat 3069WB Rotterdam ROTTDM bon 29230']

Edit: I changed the pattern a bit because it didn't capture the third item in the list to generate the expected output.


text:
Q: Set scroll mode conditionally with react-full-page I'm currently using react-full page module on my webpage. The thing is, I don't want a full-page scroll when on mobile phones or tablets, because it's weird and uncomfortable. The component, <FullPage> has a property called scrollMode, which can be either "normal" or "full-page".
How can I update that value dynamically? I know the property called window.innerWidth but I can't figure out how to use it, I tried using useEffect & useState but it doesn't work.
Here's the code:
import React, {useState, useEffect} from 'react';
import ScrollToTop from "react-scroll-to-top";
import {Helmet} from 'react-helmet';
import { FullPage, Slide } from 'react-full-page';

// Components //
import MainBanner from '../components/common/MainBanner';
import HomeProjects from '../components/common/HomeProjects';
import AboutMe from '../components/common/AboutMe';
import Skills from '../components/common/Skills';
import ContactCommon from '../components/common/Contact';
import Warning from '../components/common/Warning';

const Home = () => {

    let innerWidth;

    useEffect(() => {
        if(window.innerWidth <= 768) innerWidth = "normal";
        else innerWidth = "full-page";
    }, [innerWidth]);

    console.log(innerWidth);

    const [warningPage, setWarningPage] = useState(true);

    return (
        warningPage ? (<Warning setWarningPage={setWarningPage}/>) : (

        <Helmet>
            <title>Alejo Yanczuk - Home</title>
            <meta name="description" content="Home page | Web developer website" data-react-helmet="true"/>
        </Helmet>

            <FullPage scrollMode={innerWidth}>
                <Slide>
                    <MainBanner />
                </Slide>
                <Slide>
                    <AboutMe />
                </Slide>
                <Slide>
                    <Skills />
                </Slide>
                <Slide>
                    <HomeProjects />
                </Slide>
                <Slide>
                    <ContactCommon />
                </Slide>
            </FullPage>

            <ScrollToTop smooth/>

        )
    );
}

export default Home;

A: You use a useEffect with a variable as dependancy and not a state.
You need to use a state, and create a state for innerWidth.
You need too use a addEventListener to listen rezize event from window.
Here is a exemple:
const Home = () => {
  const [innerWidth, setInnerWidth] = useState(true);

  useEffect(() => {
    function onResize() {
      // here is a quick syntaxe to avoid if / else
      setInnerWidth(window.innerWidth <= 768 ? 'normal' : "full-page");
    }

    window.addEventListener("resize", onResize)
    return () => window.removeEventListener("resize", onResize)
  }, [innerWidth]);

  const [warningPage, setWarningPage] = useState(true);

  return warningPage ? (
    <Warning setWarningPage={setWarningPage} />
  )....

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use the information in XMLHttpRequest.send(string) I'm sending a POST request with a string in the .send() part which is "id=jeff&command=test".
How do I parse and use these values in Java via the HttpServletRequest object?
I've tried changing the content type to text/html and application/x-www-form-urlencoded.
My java server is embedded jetty btw.
var text = form.command.value;
var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange=function()
    {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
            xmlhttp.responseText
          }
        }

    xmlhttp.open("POST", 'go', true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("id=jeff&command=" + text);

here's my Java code
public class GoHandler extends HttpServlet
{
Commands c = Commands.getInstance();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
    BufferedReader reader = request.getReader();
    String str = "";
    while ((str = reader.readLine()) != null)
    {
        System.out.println(str);
    }

    String p = request.getParameter("id");
    String input = request.getParameter("command");
    System.out.print(p);

here is my output when I make the request from a browser
id=jeff&command=test (this is from the buffered reader)
null (this is from my String p which should be the id)
here's Chrome's toolkit thing..
Request URL:http://localhost:8080/go
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:20
Content-Type:application/xml
Host:localhost:8080
Origin:http://localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.4 (KHTML, like Gecko)     Chrome/22.0.1229.79 Safari/537.4
Request Payload
id=jeff&command=test
Response Headersview source
Content-Length:66
Content-Type:application/json;charset=utf-8
Server:Jetty(8.1.7.v20120910)

my response from the server
{"flavor":"You are in the goHandler"}

A: "That works. But is there no built in way of getting these values?"
Don't read input stream to get parameter because once you read input stream you reached at the end of input stream and native method getParameter() does not reset input stream  that's why it returns null.
use getParameter() directly to get values.
Use either InputStream or getParameter() don't use both
@Override
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException
{`    `

String p=request.getParameter("id");
String input=request.getParameter("command");
System.out.println(p);

A: You can get it as buffered reader. This will give full string. The you can parse it manually. If your separator is "\n" then,
BufferedReader reader = request.getReader();
while ((str = reader.readLine()) != null)
  jb.append(str);

Edit:
Can you try one/both of these http headers?! Here is your updated code.
var text = form.command.value;
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange=function()
{
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        alert(xmlhttp.responseText);
      }
    }
var params = "id=jeff&command=" + encodeURIComponent(text);
xmlhttp.open("POST", "go", true);
xmlhttp.send(params);

Using encodeURIComponent() to convert the URI into valid ASCII.
Updated the JavsScript since the default content-type is "application/x-www-form-urlencoded" so removed it. Now try to access all your parameters in the servlet.


text:
Q: ios split array into sections based on compare result I have an array of objects which I am currently sorting by date (the objects each have a date field on them).
I want to be able to split up this array into multiple sections, where each section contains the objects that have the same date. Is there already a supported mechanism for this?

A: There seems to be no mechanism for this, other than the way I suggested in my comment:
I create a nsmutabledict, then I iterate over my sorted list of objects. For each object, I check the date, and see if there exists a key in my dict pertaining to that date. If so, I retrieve that value from the dict and append this object to that array. If not, I create a new list and insert it into the dict with the key pertaining to the date.

A: - (NSArray *)filteredArrayUsingPredicate:(NSPredicate *)predicate

will be useful. Write a predicate to get the filtered array of all the elements matching the date of the first item in the array. Add that array to a new mutable array, which is the object holding all the filtered arrays with matching dates.
Record that date as having been used. Iterate over the original array until you find a different date and repeat the filteredArrayUsingPredicate operation. Keep doing this until you have covered all unique dates in the array.
I was going to suggest using NSSet to remove all the items that have been filtered already to reduce processing time but the number of items may be important, and depending on the objects NSSet could discard duplicates.
An optimisation could be to use NSSet to non-destructively create a set of unique dates from the original array and then iterate over that set, performing the filteredArrayUsingPredicate operation. But whether that is practical depends on your data.


text:
Q: How to profile an eclipse application in eclipse? I developed a plugin in Eclipse. But it has some performance problems.  I want to profile my plugin to find some hooks. I searched and found TPTP, but it doesn't work in Eclipse Indigo. Is there any other eclipse plugin available for profiling an Eclipse Application/Java Process? I am running my plugin using Run/Debug as eclipse application.
Thank You.

A: JProfiler has an eclipse plugin that can profile eclipse applications from within eclipse. See this screen cast to see the JProfiler eclipse plugin in action.
Disclaimer: My company develops JProfiler.

A: As an Eclipse program is still a Java program, you can use any normal Java profiler. After taking a measurement, you only need to filter the results for the package names of your plugin. I've done very good performance analysises of different Java programs (Swing, Eclipse plugins, ...) using the Yourkit Java Profiler. It has a full feature trial license for commercial use and you can get full licenses for free when working on open source projects.


text:
Q: Implement hash-table in C++ The following is the implementation of hashtable using C++. Can you please help me to understand what HashEntry **table is? Why it is declared as a double pointer? Is it a array and each value of the array is HashEntry?
  class HashEntry {
    private:
          int key;
          int value;
    public:
          HashEntry(int key, int value) {
                this->key = key;
                this->value = value;
          }

          int getKey() {
                return key;
          }

          int getValue() {
                return value;
          }
    };

    const int TABLE_SIZE = 128;

    class HashMap {
    private:
          HashEntry **table;
    public:
          HashMap() {
                table = new HashEntry*[TABLE_SIZE];
                for (int i = 0; i < TABLE_SIZE; i++)
                      table[i] = NULL;
          }

          int get(int key) {
                int hash = (key % TABLE_SIZE);
                while (table[hash] != NULL && table[hash]->getKey() != key)
                      hash = (hash + 1) % TABLE_SIZE;
                if (table[hash] == NULL)
                      return -1;
                else
                      return table[hash]->getValue();
          }

          void put(int key, int value) {
                int hash = (key % TABLE_SIZE);
                while (table[hash] != NULL && table[hash]->getKey() != key)
                      hash = (hash + 1) % TABLE_SIZE;
                if (table[hash] != NULL)
                      delete table[hash];
                table[hash] = new HashEntry(key, value);
          }

          ~HashMap() {
                for (int i = 0; i < TABLE_SIZE; i++)
                      if (table[i] != NULL)
                            delete table[i];
                delete[] table;
          }
    };

A: In this code, table is a pointer to a pointer to HashEntry
HashEntry **table;

The general rule is to start with the variable name and the basic type, go right as much as possible then go left, see this excellent description
http://unixwiz.net/techtips/reading-cdecl.html
So you start with the variable, table, and the basic type, HashEntry which is furthest to the left. Note that the article describes the rules for 'C' where a basic type can be a struct, think of your C++ class HashEntry as a 'C' struct.
table is ... HashEntry
There is nothing else to the right of table in the declaration, so go left, and you have "*" which stands for pointer to:
table is pointer to ... HashEntry
Again you must go left in the declaration and consume the next "*", you now have
table is pointer to pointer to HashEntry
... and you are done.
It is perhaps unfortunate that table was declared that way, because table implies array, and it is not declared as an array.  It turns out that in C++, as in C, an array "decays" into a pointer when it is passed to a function.  Here "decays" means you have lost information, namely the size of the array.
An equivalent declaration, which I think would give the reader more insight would be:
HashEntry * table[];

Using the rules about how to interpret variable declarations, this should be read as
table is undimensioned array of pointer to HashEntry
This is equivalent from the compiler's point of view to the previous declaration, because an undimensioned array is passed as a pointer to the type of the elements of the array (the value being the address of the first element, at offset 0).  A "dimensioned array" also decays to a pointer, with the loss of the dimension information.  See this SO answer for more information on decaying of arrays to pointers.
What is array decaying?


text: Q: How to first predict category then do regression based on which category it is predicted? How to first predict category then do regression based on which category it is predicted? Basically I have data that are't really that continuously distributed on its range, so it would be good if I can have some coarse predictions over which region the label likely to fall into and then do a more detailed regression to predict where exactly does the label equal to in that region.


text:
Q: Inequality regarding summation and exponentation I need your expertise in solving the following problem:
Given $x \in \mathbb{R}^d$ and let $A \in \mathbb{R}^{d \times d}$ a vector and and an inverse matrix respectively. Let $\alpha \in \mathbb{R}^+$.
Is there a way to prove that:
$$ e^{-\left\| A\right\|_2^2 + 2 \cdot \left\| A^{-1}x\right\|_1 - \left\| x\right\|_2^2 } \leq \alpha \cdot \sum\limits_{i=1}^d e^{-\left\| Ae_j\right\|_2^2 + 2\cdot \left| A^{-1}xe_j\right| - \left\| x\right\|_2^2 }$$
And if so how can we bound $\alpha$?
Please advise and Thanks in advance.


text:
Q: Year over Year growth of survey satisfaction with DAX power BI I have the data warehouse design as follows:

Explanation:
The data warehouse contains 4 tables, 3 dimensions (DATE, QUESTION_ANSWER, SURVEY_RESPONDENT) they are linked to each other using surrogate keys. and the data is the result of a survey questions.
The RESPONDENT has a set of questions, and the possible answers are from 1 to 5 (bad to great).
My question is related to the DIM_QUESTION_ANSWER table, I need to analyse the satisfaction of the RESPONDENTS on a survey.
The satisfaction is the (number of RESPONDENTS with an average response equal to or greater than four "4") divided by (the number of all the RESPONDENTS).
I calculated the survey satisfaction percentage using the DAX formula below:
AVRSCOREALLCOUNT =
VAR MTABLE = SUMMARIZE(FACT_SURVEY_RESPONSES,FACT_SURVEY_RESPONSES[RESPONDENT_SRGT])
VAR AVGTABLE = ADDCOLUMNS(MTABLE,"AVR",CALCULATE(AVERAGE(DIM_QUESTION_ANSWER[ANSWER_VALUE])))
VAR FILTERED = FILTER(AVGTABLE,[AVR]>= 4)

RETURN
IF(
    NOT ISBLANK(COUNTROWS(AVGTABLE)),
    DIVIDE(COUNTROWS(FILTERED),COUNTROWS(AVGTABLE))

)

What I want to calculate and what I achieve:
I want to calculate the Year over Year of the satisfaction; so I tried to calculate the last year satisfaction using SAMEPERIODLASTYEAR with this formula:
AVRSCOREALLCOUNT-LASTYEAR =
VAR MTABLE = SUMMARIZE(FACT_SURVEY_RESPONSES,FACT_SURVEY_RESPONSES[RESPONDENT_SRGT])
VAR AVGTABLE = ADDCOLUMNS(MTABLE,"AVR",CALCULATE(AVERAGE(DIM_QUESTION_ANSWER[ANSWER_VALUE]),SAMEPERIODLASTYEAR(DIM_DATE[Date])))
VAR FILTERED = FILTER(AVGTABLE,[AVR]>=4)

VAR AVRSCORELASTYEAR = DIVIDE(COUNTROWS(FILTERED),COUNTROWS(AVGTABLE))

RETURN AVRSCORELASTYEAR

The problem:
The result of last year's formula is wrong, it's just returning the result of the current year satisfaction, I don't know where the mistake is, is it because I am using the date from the DIM_DATE and its not a direct column in the DIM_QUESTION_ANSWER table?

A: Can you try to replace MTABLE and AVGTABLE as below?
VAR AVGTABLE =
CALCULATETABLE (
    ADDCOLUMNS (
        SUMMARIZE ( FACT_SURVEY_RESPONSES, FACT_SURVEY_RESPONSES[RESPONDENT_SRGT] ),
        "AVR", CALCULATE ( AVERAGE ( DIM_QUESTION_ANSWER[ANSWER_VALUE] ) )
    ),
    SAMEPERIODLASTYEAR ( DIM_DATE[Date] )
)

EDIT: Or better yet, if the original measure works, why not simply try
AVRSCOREALLCOUNT-LASTYEAR =
CALCULATE ( AVRSCOREALLCOUNT, SAMEPERIODLASTYEAR ( DimDate[Date] ) )


text:
Q: Is runat=server the correct way of running? I am a newcomer developer to ASP.NET.
I wonder that is running forms on server (namely runat=server) the right way of coding ? I feel that all of scripts, forms etc. must run on client side because server side runnings may cause bottleneck on server side.
So what kind of advantages/ disadvantages
-running on server side
-running on client side ?

A: I think this link will give you a good understanding of the difference. difference between server and client controls There are plenty of explanations out there if you just Google

A: Yes, that runat=server means that ASP.Net does some processing on the server side.
This processing means that

*

*You have an object model you can use in your code, to access properties of your controls and event handlers (such as an OnClick for the various Buttons)

*The (possibly complicated - see grids) HTML is generated to be sent to the client (=browser)

The real form/script etc does run on the client. Validations run both client-side and server-side.


text:
Q: Show that $f$ is continuously partially differentiable How do we show that a function is continuously partially differentiable?
For example if we consider the function $$f(x, y) =\begin{cases} xy\frac{x^2-y^2}{x^2+y^2}& \text{ if } (x, y) \neq (0.0) \\ 0 & \text{ if } (x, y) =(0, 0)\end{cases}$$ to show that it is partially differentiable do we just calculate the partial derivatives to show that these exist?
$$$$
EDIT:
To show that the partialderivative as for$x$ is continuous I have done the following:
\begin{align*}\left |\frac{\partial{f}}{\partial{x}}(x,y)\right |&=\left |\frac{y(x^4+4x^2y^2-y^4)}{(x^2+y^2)^2}\right |\\ & \leq \left |\frac{y(x^4+4x^2y^2+y^4)}{(x^2+y^2)^2}\right |\\ & =\left |\frac{y(x^4+2x^2y^2+y^4+2x^2y^2)}{(x^2+y^2)^2}\right |\\ & =\left |\frac{y((x^2+y^2)^2+2x^2y^2)}{(x^2+y^2)^2}\right |\\ & =\left |\frac{y((x^2+y^2)^2)}{(x^2+y^2)^2}+\frac{y(2x^2y^2)}{(x^2+y^2)^2}\right |\\ & =\left |y+\frac{y(2x^2y^2)}{(x^2+y^2)^2}\right |\end{align*}
How can we continue?

A: Note that
$$f'_x(0) = \lim_{x\to 0}xy\frac{x^2 - y^2}{x^2 + y^2} = 0$$
$$f'_y(0) = \lim_{y\to 0}xy\frac{x^2 - y^2}{x^2 + y^2} = 0$$


text:
Q: EditText and get chars How I can get number of charakters which I write in my editview? I want check this number because when I write more then 3 I want use alertdialog. How I can do this in simply way?

A: You need to use TextWatcher to for this.
    yourEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
        int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });

Use any of the method to keep track of quantity and show alert if applicable

A: use TextWatcher for counting char in EditText as:
private CharSequence temp;
    mEditText = (EditText)findViewById(R.id.ET);
        mEditText.addTextChangedListener(mTextWatcher);

        TextWatcher mTextWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                        int arg3) {
                    temp = s;
                }

                @Override
                public void onTextChanged(CharSequence s, int arg1, int arg2,
                        int arg3) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                   // check here length of text in EditText after change
           if (temp.length() > 3) {
                // your alertdialog
        }
                }
            };


text:
Q: Where can I see the definitions of native methods in java? Using eclipse, I see that methods like System.nanotime() or System.arraycopy() are native.
However I could not see the definitions of these methods.
Where are can I find the definitions , and more importantly what language are those methods written in ?

A: Install the Java SE Development Kit from http://java.sun.com/javase/downloads/index.jsp.
Once installed, you should find an archive called src.zip in the top of the JDK installation directory. The Java source code is in there.


text:
Q: Jenkins: build fixed notification I got an email with "Build # - fixed!". So does it mean that after failures the build was finally successfully built? Am I right? I am really new in Jenkins/ Hudson :(
Thank you

A: Yes, that's the default behaviour for Jenkins; it will email you for every build failure, but will only email about a successful build if it was preceded by a failed build.  See the doc for the Extended Email plugin, which is what most sites use.


text:
Q: jquery mobile page refresh or table refresh I've got a jquery mobile application with a page that contains a table. This table is database driven and it has some up/down buttons to control the order. Got the buttons to work, but the table doesn't reflect the changes that were made. The suggestion at this other question almost works. It refreshes the list correctly, but the buttons don't work. I see a page gets added to the DOM, and I know the tags in this page probably share the same IDs which could be causing an issue, but I can't think of a way to get around this.
ajax call here
$.mobile.changePage(
    window.location.href,
    {
        allowSamePageTransition : true,
        transition              : 'none',
        showLoadMsg             : false,
        reloadPage              : true
    }
);


text:
Q: Sort records into buckets with Rails I have a Game model that has a datetime, storing the date and time the game will be played. I'd like to put those records into an array of arrays of each date.
Example of a possible outcome array:
[
  [
    #<Game id: 7, datetime: "2014-03-03 05:30:00">,
    #<Game id: 12, datetime: "2014-03-03 11:30:00">,
    #<Game id: 14, datetime: "2014-03-03 12:30:00">,
    #<Game id: 17, datetime: "2014-03-03 12:45:00">
  ],
  [
    #<Game id: 1, datetime: "2014-04-06 05:30:00">,
    #<Game id: 2, datetime: "2014-04-06 11:30:00">,
    #<Game id: 4, datetime: "2014-04-06 12:30:00">,
    #<Game id: 7, datetime: "2014-04-06 12:45:00">
  ]
]

Here's what I'm trying so far
@games = Array.new
Game.all.each do |game|
  # in my model I have a function date that gets the date part of my datetime
  quit = false
  index = 0
  while !quit do
    if index < @games.length
      quit = true
      @games << [game]
    elsif @games[index].first.date == game.date
      quit = true
      @games[index] << game
    end
  end
end

But this seems not very ruby-like and probably not the most efficient way. Is there a better approach for this?

A: This is probably not the most efficient way to do this, but it is short and readable:
@games = {}
Game.all.each do |game|
  @games[game.date] = [] if !@games.has_key? game.date
  @games[game.date] << game
end
@games = @games.values

Note that it is idiomatic Ruby to use array and hash literals [] and {} instead of their respective Array.new and Hash.new constructors.
Update
Here's an even better way, using the group_by method of Enumerable, which collections can include as a module:
@games = Game.all.group_by { |game| game.date }

Note that this will return a hash using the dates as keys, but you can easily turn this into an array by calling the values method on a hash.


text:
Q: C++ cli access Form variables from class There is a form Form1 which contains int x; and a class MyClass with .h and .cpp files. How can I access the Form1 variable x from MyClass, without passing it using a method? I think something like Form1.x Maybe is it a bad style of programming?
I am just learning..

A: Well it breaks encapsulation, you should really have public getters and setters for the data you want to expose, allowing access like you suggested allows the caller to corrupt, reassign etc.. basically do whatever they like. You should add a method getX() for want of a better name.
C++/CLI supports properties which may be what you are after see msdn article: http://msdn.microsoft.com/en-us/library/ms379617%28v=vs.80%29.aspx#vs05cplus_topic10 and a codeproject post: http://www.codeproject.com/Articles/10352/C-CLI-Properties-Syntactic-sugar-for-accessor-meth


text:
Q: Angular getting access to $routeParams in a controller not connected to the route I have a SPA Angular app which has two main html divs. One of these changes frequently and the other less frequently. The frequently changing one uses $route in the app.config. The less frequently changing div also needs to be aware of url changes, so I want to listen for changes in $routeParamas and do stuff accordingly.
So in my controller I have:
 .controller('SecondaryCtrl', function ($scope, $routeParams, MyService) {

     $scope.$watch('routeParams', function () {
         console.log('routeParams: ', $routeParams);
         // I need $routeParams.projectId to compose an API call.
     });

     ...

 });

In the console, $routeParams is returned as an empty object. I know that if the Controller and route are defined in the app.config, the$routeParams are available, but the app.config already has definition for the given route which links to the PrimaryCtrl:
.config( function ($interpolateProvider, $routeProvider) {
   $routeProvider
    .when('/project/:projectId', {
        templateUrl : 'partials/_project_detail.html',
        controller: 'PrimaryCtrl',
        resolve: {
            project: function ($route, MyService) {
                return MyService.get('projects/', $route.current.params.projectId);
            },
        }
    })

So, how can I get access to the $routeParams in my SecondaryCtrl when $routeParams changes?

A: You can listen to the $routeChangeSuccess event inside of watching $routeParams, like this:
.controller('SecondaryCtrl', function ($scope, MyService) {

     $scope.$on('$routeChangeSuccess', function (event, current, previous) {
         // current is the current route
         // previous is the previous route
     });

     ...

 });

Angular Doc


text:
Q: Toggle div $this without toggling another with same class How would I toggle this divs .pane-content without toggling another with same class?
HTML:

Settings

         Loreum Ipsum

JS:
$('.pane-toggle').click(function () {
    $('.pane-content').toggle('fast');
    $("i", this).toggleClass("fa-chevron-down fa-chevron-up");
});

A: Try  -
$('.pane-content',$(this).closest('.pane')).toggle('fast');

Demo -----> http://jsfiddle.net/t5kM7/1/


text:
Q: Pass form values into another php class through javascript I have a MyAccount page for my website which is going to have a form to allow the users to upload an image.
<from action='javascript:uploadFile'>
     <input type='file' name='Upload'>
</form>

What I would like to do is have it call another .php file like:
<script type="text/javascript">
    function uploadFile()
    {
         addPhoto.php giving files $id and Upload (from the form)
    }

How can I achieve this without the user actually leaving the MyAccount page?

A: You can use include or require within a PHP file.

The include statement includes and evaluates the specified file.

You would need AJAX/jQuery to call it through JavaScript.
Documentation


text:
Q: Matrix $A\in M_{3}(\mathbb{Q})$ meet the equation $A^{8} = I$. Prove, that $A^4=I$ and answer, if this matrix can be diagonalized over $\mathbb{Q}$ Please help me in my second task, where I even don't know how to start
Matrix $A\in M_{3}(\mathbb{Q})$ meet the equation $A^{8} = I$. Prove, that $A^4=I$ and answer, if this matrix can be diagonalized over $\mathbb{Q}$
It's like every matrix to the k-power are always $I$ or $0$  when $k>n$?

A: If $A^8=I$, the minimal polynomial $\mu_A(t)$ of $A$ divides $t^8-1$. This last polynomial factors as $(t^4-1)(t^4+1)$. Now $\mu_A(t)$ has degree at most $3$, so it must be coprime with $t^4+1$, which is irreducible. It follows that it divides the other factor, $t^4-1$. This tells us, precisely, that $A^4=I$.
Now we know $\mu_A(t)$ divides $t^4-1=(t-1)(t+1)(t^2+1)$. It follows that $\mu_A(t)$ has all its roots simple, so $A$ is diagonalizable over $\mathbb C$. Over $\mathbb Q$, it is diagonalizable iff all its eigenvalues are rational, and this happens iff $\mu_A(t)$ divides $(t-1)(t+1)$. This is not always the case. For example, consider $A=\left(\begin{array}{ccc}0&1&0\\-1&0&0\\0&0&1\end{array}\right)$.


text:
Q: TwitterServer (Finch/Finagle) seems to block api call till it finishes its calculation I'm setting up a new rest server using TwitterServer, and it seems to block a new api call, till a previous one be finished.
Here is a simple modification of the basic code taken from the documentation at https://twitter.github.io/twitter-server :
import com.twitter.finagle.{Http, Service}
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.server.TwitterServer
import com.twitter.util.{Await, Future, FuturePool}

object BasicServer extends TwitterServer {
  val service = new Service[Request, Response] {
    def apply(request: Request): Future[Response] = {
      FuturePool.unboundedPool {
        Thread.sleep(10000)

        val response = Response(request.version, Status.Ok)
        response.contentString = "hello"

        response
      }
    }
  }

  def main(): Unit = {
    val server = Http.serve(":8888", service)
    onExit {
      server.close()
      ()
    }
    Await.ready(server)

    ()
  }
}

if i try to do multiple calls to http://localhost:8888, the first call blocks the second one, for some reason.
Any idea why is this happening ?

A: You should NOT use Thread.sleep with Finagle (nor with any other non-blocking solution) ... most of those solutions count with the fact that the threads are not blocked long.
Thread.sleep is using any local thread to sleep on it and that will block the poor server without further notice.
As a soluion for a sleep, please use the Future.sleep like in:
import com.twitter.conversions.DurationOps._ // for the 5.seconds part to work
import com.twitter.util._

implicit val twitterTimer = new ScheduledThreadPoolTimer // for the sleep time to work

Future.sleep(5.seconds) flatMap FuturePool.unboundedPool { ...(and remove the Thread.sleep inside) ... }


text:
Q: Redis storing and querying complex structures I want to store a complex structure as JSON object in a Redis Sorted Set.
ZADD "mysetkey" 100 [ {"A":"100"}, {"B":"50"}, {"C":"180"}, {"D":"200"} ]
ZADD "mysetkey" 101 [ {"A":"10"}, {"B":"50"}, {"C":"70"}, {"D":"200"} ]
ZADD "mysetkey" 88 [ {"A":"300"}, {"B":"50"}, {"C":"110"}, {"D":"200"} ]

Now is there an easy to perform operations or searches on the values stored ?
For example, if I want to get sumof(A) for all elements ? Or get all elements that have value of A < 20 AND value of C  > 100.
My understanding is that it's not possible because Redis stores everything as String. But wanted to confirm it anyway.
Also, it is possible to achieve this in Redis by using a combination of data structures supported by Redis.

A: You can implement the functionality that you need in a Lua script. When evaluating Lua script Redis loads cjson library among others and this library allows you to parse your JSON to extract values from it. See the EVAL command. http://redis.io/commands/eval
A code sample from http://www.kyne.com.au/~mark/software/lua-cjson-manual.html:
json_text = '[ true, { "foo": "bar" } ]'
value = cjson.decode(json_text)
-- Returns: { true, { foo = "bar" } }

Mind that Redis evaluates scripts one at a time, and no other clients can run their commands while a script is running, so this might now be suitable for you.


text:
Q: Document Information Panel (Infopath 2007 .xsn) crashes Word 2010 when creating an instance of the content type, any idea why? My problem seems to be that whenever I create an instance of a document content type it seems to crash Word 2010, I've tested it on another PC with Word 2007 installed and it opens the document just fine with the document information panel (DIP) fully working.
For compatibility reasons I will need to use it in Word 2007, but in case there's ever an upgrade I would like to know I won't have to redo everything.
I'm using Infopath .xsn 2007 format to create the DIP but in Infopath 2010 (don't know if this is part of the issue?), as .xsn 2010 format does not work on Word 2007.
I'm using SharePoint Enterprise Server 2010, the site this is used on is a team site, and the document content types' template is a .docx which opens absolutely fine with quick parts in place.
Any ideas are greatly appreciated.


text:
Q: How do people manage leftover or stranded resources in Chef? Is there a clean way to manage stranded resources through cookbook modifications? For instance, let's say I have a recipe resource that writes a file from a template like so:
template 'C:\dir\somefile.txt' do
    source 'somefile.erb'
end

And then I update the cookbook to write that file to a different place like so:
template 'C:\some_different_dir\new_file_location.txt' do
    source 'sample.erb'
end

The file from the original recipe doesn't get cleaned up automatically does it? So at that point C:\dir\somefile.txt is just stranded out there not being used.
The reason I care is because our app demands a lot of resources and I don't want a lot of disk drive space taken up over time with cookbook updates. I also don't like stranded files placed about the server because I don't want something to accidentally get picked up by one of our applications and get executed. The app I'm working on has a bunch of different services running all over the place and plus we have contracts with partners and other organizations concerning left over files and source code.
Also we can't easily move into a direction where we spin up fresh new servers when our app updates using something like Vagrant or Terraform. Once our servers are spun up, they are there for a long time. Some of them aren't even VMs.
Thanks for any help.

A: You would have to add a new resource to clean up the old file:
file 'C:\\dir\\somefile.txt' do
  action :delete
end

Once you are sure every server has cleaned up the file you can remove that from the recipe, or just leave it. You can also check out the zap cookbook, which attempts to do automated cleanups but this is really hard to do in a stable way, so it comes with some "gotchas", mostly related to nested execution contexts and custom resources.


text:
Q: SyntaxError: Unexpected token 'export' when using CrafterCMS with typescript I'm trying to create a crafterCMS project with typescript. I install the latest packages:
"@craftercms/content": "^2.0.7",
"@craftercms/experience-builder": "^1.0.0-rc.3",
"@craftercms/ice": "^2.0.7",

But when i run the project i get this error:

By checking the logs its coming from a file belonging to @craftercms/experience-builder in node_modules:

If i don't use typescript i dont get any errors so my guess its because of these typescript files in node_modules:

Any solution?

A: I manage to solve the problem using next transpile modules.
I added
const withTM = require('next-transpile-modules')(['@craftercms/experience-builder','@craftercms/studio-ui']);

to next.config.js and then export using that
module.exports = withTM({...});


text:
Q: Twilio how to add a PAUSE within a switch statement I have five menus that a user can choose from when they dial a number from their phone. Each menu has 4 to 6 options. Using the .say in Twilio all options are spoken very fast and I would like to slow that down. A comma after each sentence does not slow it down enough so I have been trying to use .pause without any luck. My thought was to use use 4 to 6 .say within a case and a .pause for 2 seconds between each .say
Any help with this would be greatly appreciated
I have tried
// Test Menu
     case '6':
     twiml.gather({numDigits: 1})
     .say('I will pause 5 seconds starting now!')
     .pause(5)
     .say('Now for the second sentence.');
    twiml.redirect('');
      break;

but I get the following error in my debugging
Error - 82002
Error on Twilio Function response
Your Function invocation resulted in StatusCode 5xx.
Possible Causes
Your Function timed out before responding
Your Function returned an error response

Possible Solutions
Your Function must contain a callback.
Make sure you place the Function callback callback(err, response) is placed correctly in your Function code.
If you are using a JavaScript promise, make sure the callback is called in both success and catch blocks.
Your Function responded with an error.

{
    "message": "twiml.gather(...).say(...).pause is not a function",
    "name": "TypeError",
    "stack": "TypeError: twiml.gather(...).say(...).pause is not a function\n    at Object.exports.handler (/var/task/handlers/ZF38fa6cf6d9f5d40cd5983794f7f70df3.js:57:7)\n    at Object.exports.handler (/var/task/node_modules/enigma-lambda/index.js:306:10)\n    at exports.handler (/var/task/enigma.js:17:9)"
}

The following code works as is, but plays the options to fast in each case. I am trying to use .say and .pause in the Test Menu (Case 6) but have been unsuccessful in every idea I have tried.
exports.handler = function(context, event, callback)
{
  let finishOnKey = '0';
  let twiml = new Twilio.twiml.VoiceResponse();
  switch (event.Digits)
  {
// Case 1
case '1':
      twiml.gather({numDigits: 1})
      .say('Message.');
      twiml.redirect('');
      break;

// Case 2
 case '2':
      twiml.gather({numDigits: 1})
      .say('Message.');
      twiml.redirect('');
      break;

//Case 3
case '3':
      twiml.gather({numDigits: 1})
      .say('Message.');
      twiml.redirect('');
      break;

//Case 4
case '4':
      twiml.gather({numDigits: 1})
      .say('Message. ');
      twiml.redirect('');
      break;

//Case 5
  case '5':
      twiml.gather({numDigits: 1})
      .say('Message.');
      twiml.redirect('');
      break;

// Test Menu
     case '6':
     twiml.gather({numDigits: 1})
     .say('I will pause 5 seconds starting now!')
     .pause(5);
     .say('Now for the second sentence.');
    twiml.redirect('');
      break;

// Pressing * repeats the current menu
     case '*':
      twiml.gather({numDigits: 1,action:'/XXX_General_Info'})
      .say('Message.');
      break;

// Main menu
    default:
        twiml.gather({numDigits: 1,action:'/XXX'})
        .say('Message. To repeat these options press star. To go back
        to the main menu press zero. To end this call just hang up,
        or press pound.');
  }
  callback(null, twiml);
};

A: My recommendation is to use Polly's Speech Synthesis Markup Language (SSML), as Devin suggested. Make sure your Twilio Function Twilio helper library is up to date (under Configure). If it says 3.6.3, you are using an older library and must enter a newer version. The latest version of the Twilio Node helper library can be found [HERE][1], (3.36.0 as of today).
Example Twilio Function Node.js code to get you started in the right direction is below. Have Fun!
    exports.handler = function(context, event, callback) {

    let twiml = new Twilio.twiml.VoiceResponse();

    let gather = twiml.gather({numDigits: 1});
    gather.say({voice: 'Polly.Joanna'}, 'Hi')
        .ssmlBreak({strength: 'x-weak',time: '2000ms'});
        gather.say({voice: 'Polly.Joanna'}, 'How are you?');
    callback(null, twiml);
};


text:
Q: Error-weighted fit using uncertainties in LMFIT I am trying to fit a model using LMFIT, I can easily do the following:
def loss_function(params):
  residuals = []
  for x, measured in ...:
     y = predict(x, params)
     residuals.append(y - measured)
  return residuals

params = Parameters()
params.add(...)

model = Minimizer(loss_function, params)
result = model.minimize(method='leastsq')

And get very reasonable results
Now I have also some uncertainties associated with my measured variable (e.g. measurement errors) so I would like to weight the points in my residuals by the standard error associated to it (suppose it is constantly 20% of the measured value). The code now becomes something like this:
def loss_function(params):
  residuals = []
  for x, measured in ...:
     y = predict(x, params)
     residuals.append((y - measured) / (measured * 0.2))
  return residuals

params = Parameters()
params.add(...)

model = Minimizer(loss_function, params)
result = model.minimize(method='leastsq')

The problem is that now I get totally unreliable fitting results. Why? How can I fix this?

A: What is the nature of "totally unreliable"?  You would probably want the uncertainties in the data to be strictly positive -- using measured* 0.2 could allow negative values or zeros.   Note that if there are NaNs or Infs in the residual, the fit will not work well, and almost certainly leave the parameter values at their starting values.
FWIW, you can pass on arguments to the objective function (for measurements, uncertainties, etc) using the fcn_args argument to Minimizer.


text:
Q: How to change vlc-qt media display widget? I am using vlc-qt to build a simple media player. And at first I connect the player to a widget, and it works, but when I tried to use the setVideoWidget member function again to change the display widget, it seems doesn't work,  so what should i do? Is this member function setVideoWidget can only be called once?

I have call setVideoWidget in my constructor _player->setVideoWidget(ui->video); to                    set the video widget(the black one you can see in the image above) as the default widget to play media and it works.
But when I tried to change the display widget to another one (named as anotherWidget,  the green one you can see in the image above)
void SimplePlayer::on_changeButton_clicked()
{
    _player->pause();
    _player->setVideoWidget(ui->anotherWidget);
    _player->play();
}

When I clicked the button named changeButton it changes nothing.The media was still displayed on the default video widget(the black one).
My constructor:
SimplePlayer::SimplePlayer(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::SimplePlayer),
      _media(0),
      _equalizerDialog(new EqualizerDialog(this))
{
//  init ui
    ui->setupUi(this);

    _instance = new VlcInstance(VlcCommon::args(), this);
    _player = new VlcMediaPlayer(_instance);
    _player->setVideoWidget(ui->video);

    signals & slots......

}


text:
Q: How to restore .bak file from AWS S3 to AWS RDS using command line We need to restore a .bak file to AWS RDS SQL Server in an automated way, say we have a Lambda (Docker Lambda or Lambda with custom runtime) and we need the capability for Lambda to be able to get restore .bak file from S3 to RDS by using command line command (AWS CLI would be more helpful).
I couldn't find much help to be able to achieve this, as most of the help online is by restoring using console and SSMS, which couldn't be used for automation.
If any of you have achieved this and or aware, would help and would be very much appreciated. Thank you.


text:
Q: Update Merchant Order ID in Amazon Marketplace I need to update MerchantOrderID in Amazon Marketplace via Amazon MWS API using C#.
So, first I created XML file like:
<?xml version="1.0"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
  <Header>
    <DocumentVersion>1.01</DocumentVersion>
    <MerchantIdentifier>M_STORE_3918753</MerchantIdentifier>
  </Header>
  <MessageType>OrderAcknowledgement</MessageType>
  <Message>
    <MessageID>1</MessageID>
    <OrderAcknowledgement>
      <AmazonOrderID>104-9209939-0469021</AmazonOrderID>
      <MerchantOrderID>100828163</MerchantOrderID>
      <StatusCode>Success</StatusCode>
      <Item>
        <AmazonOrderItemCode>11111111111111</AmazonOrderItemCode>
        <MerchantOrderItemID>111111</MerchantOrderItemID>
        <AmazonOrderItemCode>22222222222222</AmazonOrderItemCode>
        <MerchantOrderItemID>222222222</MerchantOrderItemID>
      </Item>
    </OrderAcknowledgement>
  </Message>
</AmazonEnvelope>

then I try to call Amazon MWS SubmitFeed:
SubmitFeedRequest request = new SubmitFeedRequest();
        request.Merchant = merchantId;
        request.MarketplaceIdList = new IdList();
        request.MarketplaceIdList.Id = new List<string>(new string[] { marketplaceId });

        request.FeedContent = File.Open(path, FileMode.Open, FileAccess.Read);

        request.ContentMD5 = MarketplaceWebServiceClient.CalculateContentMD5(request.FeedContent);
        request.FeedContent.Position = 0;

        request.FeedType = "_POST_ORDER_ACKNOWLEDGEMENT_DATA_";

        MarketplaceWebService.MarketplaceWebService serviceFeed = new MarketplaceWebServiceClient(
                accessKeyId,
                secretAccessKey,
                applicationName,
                applicationVersion,
                configFeed);

        SubmitFeedResponse response = serviceFeed.SubmitFeed(request);

it succesfully submits but when I open my order in Amazon (sellercentral.amazon.com) it says "none saved":
Your Merchant Order ID: #        none saved
Who can help me, what is wrong or what should I do?
Thanks!

A: For those who want to update merchant order id in multiple orders at once, here is example (also works in amazon mws scratchpad):
<?xml version="1.0"?>
<AmazonEnvelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="amzn-envelope.xsd">
  <Header>
    <DocumentVersion>1.01</DocumentVersion>
    <MerchantIdentifier>ALVH0CYWPBFNA</MerchantIdentifier>
  </Header>
  <MessageType>OrderAcknowledgement</MessageType>
    <Message>
        <MessageID>1</MessageID>
        <OrderAcknowledgement>
        <AmazonOrderID>000-0000000-0000000</AmazonOrderID>
        <MerchantOrderID>YOUR_MERCHANT_ORDER_ID</MerchantOrderID>
        <StatusCode>Success</StatusCode>
        </OrderAcknowledgement>
    </Message>
    <Message>
        <MessageID>2</MessageID>
        <OrderAcknowledgement>
        <AmazonOrderID>000-0000000-0000000</AmazonOrderID>
        <MerchantOrderID>YOUR_MERCHANT_ORDER_ID</MerchantOrderID>
        <StatusCode>Success</StatusCode>
        </OrderAcknowledgement>
    </Message>
</AmazonEnvelope>

A: It's actually right code. Somehow amazon doesn't mark some special orders or marks them later.


text:
Q: Cosmos db stored procedure filter doesn't work I have stored procedure in Cosmos db.
To the stored procedure I pass json and want to retreive some fields from this json.
This is my json:
    [
        {
            "DataStructs": [
                {
                    "DataStructCells": [
                        {
                            "RowName": "Default",
                            "ColumnName": "Perfect",
                            "CellValue": "0"
                        },
                        {
                            "RowName": "Default",
                            "ColumnName": "percent100",
                            "CellValue": "0"
                        },
                        {
                            "RowName": "Default",
                            "ColumnName": "percent95_99",
                            "CellValue": "0.3"
                        }
                    ],
                    "DataStructName": "GRIDS",
                    "DataStructType": "table",
                    "RowNameIdentifier": "GRID Meaning"
                }
            ]
        },
        "id": "c2665ce6554c4d0ebd715fcc1facf608",
        "pk": "VCT"
    }
]

This line of the code retreive value:
var val = result[0]["DataStructs"][0]["DataStructCells"][0]["CellValue"];

But when I use filter it doesn't work:
var testFilter1 = result[0]["DataStructs"][0]["DataStructCells"].filter(function (s) {
                   return s.columnName === "percent95_99";
               });
console.log(JSON.stringify(testFilter1));

it returns empty array: []

A: JSON is case sensitive. Try changing case in your filter from:
return s.columnName

to
return s.ColumnName


text:
Q: Why I can still do gradle build inside android studio without jdk installed? First time installed Android Studio on a Mac, checked no JDK,
MacBook-Pro:~/sh$ java --version
No Java runtime present, requesting install.

MacBook-Pro:/Applications/Android Studio.app/Contents$ ls
Info.plist  Resources   bin     jre     license
MacOS       _CodeSignature  gradle      lib     plugins

And then I opened Android Studio and wrote the universal simple program "hello" and built it, I expected error, but none ... (see the build console highlight part)

Again, I expected error like "jdk not installed" "no found jdk" "java not found" etc ...
I tried use command line to do build, then again
MacBook-Pro:~/.gradle/wrapper/dists/gradle-3.3-all/55gk2rcmfc6p2dg9u9ohc3hw9/gradle-3.3/bin$ ./gradle -v
No Java runtime present, requesting install.

I felt mutual exclusive here, unless Android Studio built project not using Gradle.
So how on earth to understand Gradle role in Android Studio correctly?

Put the location in case someone need it,
MacBook-Pro:/Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin$ ls
appletviewer    javah       jjs     keytool     schemagen
extcheck    javap       jmap        native2ascii    serialver
idlj        jcmd        jps     orbd        servertool
jar     jconsole    jrunscript  pack200     tnameserv
jarsigner   jdb     jsadebugd   policytool  unpack200
java        jdeps       jstack      rmic        wsgen
javac       jhat        jstat       rmid        wsimport
javadoc     jinfo       jstatd      rmiregistry xjc

A: Since Android Studio 2.2 the OpenJDK is embedded. If you want to use a different version you can do so. See here
By using the gradle wrapper it will use your environment path to the JDK which you did not set up. That's why it's working in Android Studio but not from the OS command line.


text:
Q: Approximating mean daily and hourly temperature beyond Fourier series Summary: What "well-known" and short parametrized mathematical
function describes daily and hourly temperature for a given location?
If you look at the mean daily temperature graph for a given location,
it looks like a sine wave with a period of one year.
Similarly, the hourly temperature for a given day for a given location
also looks like a sine wave with a period of one day.
However, closer inspection (Fourier analysis) shows that they're
not. There are fairly strong components of frequency 2/year and 3/year
for the daily temperature, and the hourly temperature also has strong
non-single-period terms.
Is there a parametrized function that reasonably describes the daily
mean temperature and (a separate function) the hourly mean
temperature? The parameters would be location-based.
I realize I can keep taking more Fourier terms to increase accuracy,
but I was hoping for something more elegant. For example, maybe the
graph is a parametrized version of sin^2(x) or some other
"well-known" function.

A: There's no simple and surely no analytic function describing the daily cycles of the temperature. It's not hard to see why: while you could add some higher harmonics etc., the actual process clearly contains many unsmooth points. During the day, when the Sun is visible, the temperature typically increases, and the rate of increase is maximum around the noon.  The maximum temperature during the day is reached around 2 p.m. in average.
However, after the sunset, the Sun's warming effect goes pretty much strictly to zero. So the second derivative of the temperature is discontinuous after the sunset. Moreover, the time of the sunrise and sunset depend on the seasons and latitude. You can't get any universal answer for what you're looking for, and even a function that would be OK would have to depend on several parameters and contain unsmooth functions such as the absolute value.

A: Even a very simple model, say an infinetly thick conductive slab in space so that you only have to deal with radiative effects (solar absorption, and thermal heat loss) gets messy, the solar input is zero at night but follows a curve during the day (easily computable via geometry), but solar input at sunrise and sunset will be discontuous in the first time derivative, which should introduce high order harmonics. Also the Stefan Boltzmann equation is nonlinear in temperature. Then add an atmosphere, it heats the surface until the thermal structure supports convection, so different transport mechanisms are important during different times of day. Then add clouds and variable weather systems....
If you just want to reasonably reproduce the curves, I'd use only a couple of annual and daily harmonics, otherwise you are probably going to overfit the data. But the statisticians would be the best people to consult about it.


text:
Q: Find string from a list I have a list with several ingredients:
List<string> vegList = new List<string>();

where there are several strings like: "cherry", "butter", "bread".
My idea was to have a dictionary or something like that having a recipe string, the name of that recipe is returned if it had one or more elements from the list.
I tried to make a dictionary, and array too, but I didn't get what I wanted.
can anyone help?
i tried this but i don't know what to do anymore
myString = "receit pineapple cake, cherry, bread ..."
foreach(string item in vegList )
{
    if(item.Contains(myString))
       return item;
}

A: If each recipe has a vegList, or more specifically, you have a Recipe class with a List<string> vegList field, and let's say you have a List<Recipe> recipes somewhere:
var ingredient = "cherry";

var matches = recipes.FindAll(r => r.vegList.contains(ingredient));

matches will be a List<Recipe> with recipes containing "cherry" as an ingredient.

With the new scenario as the question was updated, first make sure your string has ingredients separated all by a space (let's not make it harder).
myIngredients = myString.split(" ");

Then to find the recipes:
var matches = recipes.FindAll(r => r.vegList.Any(l => myIngredients.contains(l)));

In this case a recipe is selected if its vegList contains at least one of the ingredients in myIngredients.

A: Try Linq Any:
List<string> vegList = new List<string>()
{ "cherry", "butter", "bread"};

string recipe = "butterbread";

bool showRecipe = vegList.Any(s => recipe.Contains(s));

ShowRecipe returns true.
Edit 1:
The following code searches for recipes in recipes list and returns a matchedRecipes list with recipes that match the the words from vegList.
List<string> vegList = new List<string>()
{ "cherry", "butter", "bread"};

List<string> recipes = new List<string>()
{ "steak", "butterbread", "cherrycake"};

List<string> matchedRecipes = recipes.Where(x => vegList.Any(s => x.Contains(s))).ToList();

matchedRecipes list contains "butterbread" and "cherrycake"
Edit 2: It would also be helpful to ignore case of letters.
List<string> vegList = new List<string>()
{ "cherry", "butter", "bread"};

List<string> recipes = new List<string>()
{ "steak", "Butterbread", "Cherrycake"};

List<string> matchedRecipes = recipes.Where(x => vegList
                                     .Any(s => x.ToLower().Contains(s.ToLower())))
                                     .ToList();


text:
Q: jQuery load() keeping previous elements in memory? I have an element, into which I load...
$("#pending").load("/pages/tipping/add-tips.php?pending=1&tip_comp=1");

Whenever a radio button is checked, that is re-loaded...
$(".comp_id").on("click",function(){
    var compID=$(this).val();
    $("#pending").load("/pages/tipping/add-tips.php?pending=1&tip_comp="+compID);
});

Inside this loaded content are inputs, which upon clicking a link I cycle through these inputs...
$("#submit").click(function(){
    $("input.stake").each(function(){
        alert("TEST");
    });
});

However, every time the content is re-loaded, it seems to "remember" the previous loads. For example, say there is 1 input to cycle through, upon loading the page the first time, I get 1 alert.
If I then change the input, and submit, I get 2 alerts, then 3 etc etc. Despite there only actually being one input there the whole time.
What's causing this, and what's the solution? It's dricving me a little crazy.
EDIT:
So if I cycle through the inputs from outside the file, it knows that there is only 1. It's ONLY when the cycle is done from within the loaded content, that it thinks there is more than 1.
Thanks

A: .load just adds content to the target element.  You could use .get if you want to replace it:
$.get("/pages/tipping/add-tips.php?pending=1&tip_comp="+compID, function(data) {
     $("#pending").replaceWith(data);
});

A: $(".comp_id").on("click",function(){
    var compID=$(this).val();
    $("#pending").load("/pages/tipping/add-tips.php?pending=1&tip_comp="+compID);
});

This will get executed on each click. One workaround might be, remove existing inputs and load again
 $(".comp_id").on("click",function(){
            var compID=$(this).val();

            $("input.stake").each(function(){
                $(this).remove();
               });

            $("#pending").load("/pages/tipping/add-tips.php?pending=1&tip_comp="+compID);
        });


text:
Q: filesystemwatcher chrome cache in Visual basic I'm trying to monitor all the folders in my pc except for the cache folder created by web browser such as chrome, firefox and IE. Basically those web browser create a new folder every time user click on it. So is there a way to ignore this folder since it's messing up the filesystem watcher.
This is basically the code that I tried out to monitor the changes
Dim watchfolder As String = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"))
    Dim attributes As FileAttribute

    attributes = File.GetAttributes(watchfolder)

    Dim fsw As New FileSystemWatcher(watchfolder)
    fsw.SynchronizingObject = Me
    fsw.IncludeSubdirectories = True
    fsw.NotifyFilter = NotifyFilters.Attributes Or
                       NotifyFilters.CreationTime Or
                       NotifyFilters.FileName Or
                       NotifyFilters.DirectoryName Or
                       NotifyFilters.Size

    AddHandler fsw.Changed, AddressOf logchange
    AddHandler fsw.Deleted, AddressOf logchange
    AddHandler fsw.Created, AddressOf logchange
    AddHandler fsw.Renamed, AddressOf logrename

    fsw.EnableRaisingEvents = True

I only have 1 partition so monitoring all file is easier. Just that when chrome is open, every click creates a temporary file and all the handlers basically triggered like always. Can I create a specific path not to monitor while monitoring the rest of the pc?


text:
Q: script moved to subdirectory post creating a venv, unable to find pip package originally installed I created myscript.py file which was added to the same directory as was my main.py file. Then I created venv and then installed all packages using pip3, including a package named xyz. I can see these packages installed at /usr/local/lib/python3.5/dist-packages/xyz. Note that myscript.py file is refering to a function in xyz package.
When myscript.py was in the same directory as main.py everything worked just fine. Then I created a subdirectory called 'proto' and moved myscript.py under that subdirectory and also I created an empty init.py file inside that subdirectory. When I try to execute main.py it gives following error.
ImportError: No Module named 'xyz'
Is it because subdirectory was created after the venv?
How can I fix this?
Here is my new file structure
c:\project\code
            |__main__.py
            |some other files
            \proto
                  |__init__.py
                  |myscript.py

A: locate the file pyvenv.cfg file in your env folder.
edit the following setting:
include-system-site-packages = true


text:
Q: Export GDB Schema to XML Workspace Document Using ArcGIS 10.2 Basic, the functions to export and import XML workspace documents (gdb schema) are greyed out.
I have seen the previous discussions here, but the suggestions didn't help. It shouldn't depend on the ArcGIS version or license level, right?

A: The Licensing Information for Import XML Workspace says:

*

*ArcGIS Desktop Basic: No

*ArcGIS Desktop Standard: Yes

*ArcGIS Desktop Advanced: Yes

so it looks like you need Standard or Advanced to unlock that functionality.


text:
Q: Rascal MPL dynamically get properties / fields of variable I often find myself testing using typeOf whenever I'm lost. Is there a similar way to print all properties or fields of a variable, similar to Object.keys (JavaScript) or vars (Python)?

A: To print all the current keyword fields of a constructor:
import Node;
iprintln(getKeywordParameters(myInput));

I use that a lot to print the fields of an M3 model, for example. However, that does not print the fields that have not been set. Rascal is a statically typed language, and there is information which can be retrieved which is not present in the value (default fields for example).
If I want to know the general signature of a function or constructor, I type the name in the console, then click on its source location:
rascal>println
value: choice(
  [
    function(|file:///Users/jurgenv/git/rascal/src/org/rascalmpl/library/IO.rsc|(11118,784,<418,0>,<455,36>)),
    function(|file:///Users/jurgenv/git/rascal/src/org/rascalmpl/library/IO.rsc|(11904,69,<457,0>,<458,27>))
  ],
  [])

That works for constructors are well, so you can see which positional fields they have or keyword fields.
To find out the name of the current constructor:
import Node;
getName(myValue);


text:
Q: Select groups where all values are larger than x I have a data frame which is grouped by 'subject'. I want filter those 'subject' where all 'values' are above a certain value, values > 0.5
Example df:
df1 <- data.frame(subject = c(1, 2, 3, 4, 5, 1, 2, 3, 4, 5),
                   values = c(.4, .6, .6, .6, .6, .6, .6, .6, .6, .4))
df1
   subject values
1        1    0.4
2        2    0.6
3        3    0.6
4        4    0.6
5        5    0.6
6        1    0.6
7        2    0.6
8        3    0.6
9        4    0.6
10       5    0.4

Desired output:
> df1
  subject values
1       2    0.6
2       3    0.6
3       4    0.6
4       2    0.6
5       3    0.6
6       4    0.6

A: a data.table approach
library(data.table_)
setDT(df1)[, .SD[all(values == 0.6) == TRUE], by = .(subject)][]
#    subject values
# 1:       2    0.6
# 2:       2    0.6
# 3:       3    0.6
# 4:       3    0.6
# 5:       4    0.6
# 6:       4    0.6

A: You can use all() inside a grouped filter using dplyr:
library(dplyr)

df1 %>%
  group_by(subject) %>%
  filter(all(values > .5)) %>%
  ungroup()

Output:
# A tibble: 6 x 2
  subject values
    <dbl>  <dbl>
1       2    0.6
2       3    0.6
3       4    0.6
4       2    0.6
5       3    0.6
6       4    0.6

A: Using min in ave.
df1[with(df1, ave(values, subject, FUN=min)) > .5, ]
#   subject values
# 2       2    0.6
# 3       3    0.6
# 4       4    0.6
# 7       2    0.6
# 8       3    0.6
# 9       4    0.6


text:
Q: How to revert repository to commit I pushed a commit to the repo, and now the master repo is messed up
and I want to revert master to commit a) which happened a while ago.
I can't modify the master repo directly so I have to create a pr to modify it.
How can I revert master to the old commit a)?
I've tried
git checkout -b revertbranch
git reset HEAD --hard a
git add .
git commit -m "revert"
git push

However, when I try to open a pull request,
I get a message on github that says no files are changed.
Can someone help?

A: Answer:
git checkout branch_x
git reset --soft master
git commit -m "commit message"
git push -f "message"


text:
Q: What is a ToD server, "Time of Day" (Not NTP) I got a simple task: Setup a ToD server... It is not NTP. It runs on port 37. It seems to  be bundled with inetd or xinetd.
Shall be installed on Debian or CentOS. Alternatively FreeBSD (pfsense router).
Any hint on how to proceed? Two starter links where after I got stuck:

*

*http://www.linuxquestions.org/questions/linux-server-73/tod-server-641674/

*http://en.wikipedia.org/wiki/Time_Protocol
Also very much apreciated if if a way to test if the ToD-server is running allready. I have quite a few servers running but are not aware if any of them allready have the ToD-service running
Reason:
I am about to setup a solution with broadband over COAX cables using a CMTS and cable modems using a standard called DOCSIS 3. To do so the cable modems needs to receive a time from a ToD-server (Time of day).
UPDATE / Solution
The Time is RFC 868 and hardly used any more since NTP and others are better. But the old RFC 868 Time over port 37 is needed for some systems - e.g. Internet over COAX using CMTS and cable modems need a working time server (in DOCSIS documentation called Time of Day server = ToD server). The xinetd that can be installed for Debian includes a time server. It just has to be enabled in etc/xinetd.d/time (disable=no for TCP and/or UDP)

A: Time.nist.gov supports the old time and daytime protocols. Note that as far as I remember, those protocols presume there are no network issues.

A: If you're using Debian, xinetd comes with a ToD daemon. If you change the "disable = yes" like in /etc/xinetd.d/time to "disable = no" and then restart xinetd, you should be able to telnet to the server on port 37 and check that you get something returned. You can use something like:
nc $IP 37 | hexdump

and you'll see that the hex value increases every second.

A: A "Time of Day" server is a pretty vague term - I'm not clear if that is referring to an an actual service named "ToD", or is just poor documentation. The Time protocol (RFC 868) is so old that very few things use it, except for a small number of embedded firmwares (such as OpenWRT), devices and appliances with little memory. NTP requires more memory than the Time protocol.
Nearly all modern appliances can use the Network Time Protocol (NTP) which has replaced the older Time protocol, which is better and probably more secure than the ancient time protocol. So spend some time now to see if your device uses NTP support.
Believe it or not, the Wikipedia article for xinetd contains a single configuration example, and it's for an RFC 868 time server.
See http://en.wikipedia.org/wiki/Xinetd#Configuration

An example configuration file for the RFC 868 time server:
# default: off
# description: An RFC 868 time server. This protocol provides a
# site-independent, machine readable date and time. The Time service sends back
# to the originating source the time in seconds since midnight on January first
# 1900.
# This is the tcp version.
service time
{
        disable         = yes
        type            = INTERNAL
        id              = time-stream
        socket_type     = stream
        protocol        = tcp
        user            = root
        wait            = no
}

# This is the udp version.
service time
{
        disable         = yes
        type            = INTERNAL
        id              = time-dgram
        socket_type     = dgram
        protocol        = udp
        user            = root
        wait            = yes
}


text:
Q: cannot change title text color in jquery fullcalendar How can I change the color of the title in fullcalendar ?
I can change the background color in css:
.fc-header-title {
    background-color:#CCCCCC;
}

but setting the color has no effect.
.fc-header-title {
    color:#CCCCCC;
}

Any suggestions ?

A: Changing the element style in Chrome does change the color, so it is likely another css selector is more specific.
Try
.fc-header-title h2 {
    color:#CCCCCC;
}

I cannot find any CSS on the full calendar sample site that actually sets the h2 color, so it appears to be using the browser default. If that is the case you must have your own h2 style set somewhere, which is more specific than using the class selector .fc-header-title. in any case the more specific selector .fc-header-title h2 should do the trick.

A: You can try
.fc-header-title {
    color:#CCCCCC !important;
}


text:
Q: How do I get a module installed as a service - Android I'm attempting to add the rtsp server portion of libstreaming to my application and run it as a service, but even though my application builds and runs fine, the service part isn't being installed and I would appreciate any help figuring out why.  I think I'm missing a step.
I added libstreaming to my existing application as a module, and libstreaming is listed as a dependency.  It all compiles and starts fine, but context.startService() returns null for a ComponentName. According to the docs, this means the service "does not exist", so I think I'm missing something, but I don't know what.  I'm building in Android Studio, then using shift+F9 to install my app and start debugging, this must install the application but not the service part?  Any help would be greatly appreciated!
Here's how I'm configured:

Dependency:

My code to start the service:
ComponentName cName = null;
try
{
    // Start the RTSP server.  Returns name of the component that is started, or is already running
    cName = this.startService(new Intent(this, RtspServer.class));
}
catch(Exception e)
{
    postUIMessage("onCreate() startService() exception: " + e.toString());
}
if(cName != null)
{
    postUIMessage("Service started:  " + cName.toString());
}
else
{
    postUIMessage("Service NOT started:  " + cName.toString());
}

My AndroidManifest.xml file:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.matt.mattvideoreceiver" >
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS"></uses-permission>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <service android:name="net.majorkernelpanic.streaming.rtsp.RtspServer"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

A: I found the problem, here's the solution in case it helps someone else.  In my AndroidManifest.xml file, the line:
<service android:name="net.majorkernelpanic.streaming.rtsp.RtspServer"/>

MUST go inside the
<Application>

section.  Once I moved that line inside the application section context.startService() now returns the service name, indicating that the service is running.
The service isn't sending video as I expected, BUT that's a different problem and at least it's now running and that answers this question. :)
Here's the working AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.matt.mattvideoreceiver" >
    <uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.RECORD_AUDIO"></uses-permission>
    <uses-permission android:name="android.permission.CAMERA"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS"></uses-permission>

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.CAMERA" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <service android:name="net.majorkernelpanic.streaming.rtsp.RtspServer"/>

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


text:
Q: bind input to object array in angular If I have a JSON input like this:
$scope.managers =
[
    {
        managerName : "Sam",
        employeesList: [
        { employeeName: 'Joe', employeeCategory: 'Developer' },
        { employeeName: 'Bob', employeeCategory: 'Developer' }
        ]
    }
]

I want to bind all the employeeNames for that manager to one comma separated input something like this:
<div ng-repeat="manager in managers">
    <input type="text" ng-model="manager.employeesList.employeeName" ng-list />
</div>

So that I can just enter

John, Bob

in the input field.
What is the best way to do this?
(I cannot change the structure of the JSON object)

A: I would create a button that on ng-click="storeNames(nameInput, manager).
.split() takes a string and separates it into elements of an array every time it sees a selector (which in this case is ', ')
http://www.w3schools.com/jsref/jsref_split.asp
    $scope.nameInput = '';
    $scope.managers = [
            {
            managerName: 'Billy Joe',
            employeesList: [
                { employeeName: 'Joe', employeeCategory: 'Developer' },
                { employeeName: 'Bob', employeeCategory: 'Developer' }
                ]
            }
        ];

    $scope.storeNames = function(names, manager) {
        if(names.length > 0) {
            names.split(", ");
            for(var x = 0; x < names.length; x++) {
                manager.employeesList.employeeName[x] = names[x];
            }
        }
    }


text:
Q: FBX Model not displaying properly in XNA 4.0 I have a problem that XNA 4.0 is not displaying a 3D FBX model correctly.
A friend created a model and when I open this in FBX Viewer it displays it correctly
https://docs.google.com/open?id=0B54ow8GRluDUYTBubTQ4bjBramM
But when I load it into XNA and click run, it displays as
https://docs.google.com/open?id=0B54ow8GRluDUSE14TWMxcnBJWWc
The code that i have for the drawing is
foreach (ModelMesh mesh in model.Meshes)
{
    foreach (BasicEffect effect in mesh.Effects)
    {
         effect.Projection = projection;
         effect.View = view;
         effect.World = Matrix.CreateScale(1.0f) * Matrix.CreateRotationX(90) * Matrix.CreateTranslation(position);
         effect.EnableDefaultLighting();
     }
     mesh.Draw();
 }

Any help to fix this will be very much appreciated.
Thanks.

A: Each mesh has a bone... and you should use it to position the mesh in the right place... this code is from Microsoft
private void DrawModel(Model m)
{
    Matrix[] transforms = new Matrix[m.Bones.Count];
    float aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
    m.CopyAbsoluteBoneTransformsTo(transforms);
    Matrix projection =
        Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
        aspectRatio, 1.0f, 10000.0f);
    Matrix view = Matrix.CreateLookAt(new Vector3(0.0f, 50.0f, Zoom),
        Vector3.Zero, Vector3.Up);

    foreach (ModelMesh mesh in m.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.EnableDefaultLighting();

            effect.View = view;
            effect.Projection = projection;
            effect.World = gameWorldRotation *
                transforms[mesh.ParentBone.Index] *
                Matrix.CreateTranslation(Position);
        }
        mesh.Draw();
    }
}

You can found it at http://msdn.microsoft.com/en-us/library/bb203933(v=xnagamestudio.40).aspx


text:
Q: Unable to apply method "read" to TdmsFile from nptdms I have been using the nptdms module to do analysis of TDMS files without issue for several years. Recently, I got an error when trying to read a TDMS file for the first time. I import TdmsFile from nptdms:
from nptdms import TdmsFile
I try to read it:
tdms_file = TdmsFile.read(path_to_my_tdms_file)
and then get the following error:
type object 'TdmsFile' has no attribute 'read'
I am using  python v3.6.10, with Anaconda and the nptdms v0.12.0.

A: The method you are referring to exists in the current documentation so it would make sense to

*

*Restart the virtual environment (close cmd line; start again; conda activate <name of your env>).

If this does not help...

*Reinstall the package:
conda remove nptdms
conda install nptdms
(the exact commands may differ depending on your environment).
If this does not help, create a fresh conda environment and install from scratch and check again.

A: Yes, this issue is recent and real. A re-install of nptdms via pip does appear to solve it. (even though pip claimed it was up to date as of version 0.17.1)


text:
Q: is there a way to shorten this change handler that uses hooks in React? With class based components you could use the computed properties to in order to use one single handler for several inputs with the help of an id attribute like this:
function handleChange(evt) {
  const value = evt.target.value;
  setState({
    ...state,
    [evt.target.name]: value
  });
}

This is thebest I caome up with but im sure there must be a shorter way:
  const handleChange = (e) => {
    if (e.target.id === 'name') setName(e.target.value)
    if (e.target.id === 'genre') setGenre(e.target.value)
    if (e.target.id === 'description') setDescription(e.target.value)
  }

Any ideas?
Thanks.

A: You could have create an object in the useState and update just like the first example.
// Declare the state with a object default value
const [state, setState] = useState({})

const handleChange = (e) => {
    setState(prev => ({
        ...prev,
        [e.target.id]: e.target.value
    }))
}

If you can't change the useState and have a very strong reason to have these 3 separeted useStates, you could create an object that returns the 3 functions based on the e.target.id
const updater = {
    name: setName,
    genre: setGenre,
    description: setDescription,
}

And when updating you do
const handleChange = (e) => {
    const updateValue = updater[e.target.id]

    if (updateValue) {
        updateValue(e.target.value)
    }
    else {
        // No function to update found
        // Do something else
    }
}


text:
Q: Android: Tracking opening/closing of word,pdf,excel etc files in my app In my app, I want to track opening & closing of word/pdf/excel files. Please suggest me how to do this?

A: Fortunately, you cannot "track opening & closing of word/pdf/excel files" from an ordinary SDK application, as this would be a privacy violation.


text:
Q: Multiple conditions in 'for' loop in C I am trying to find a substring in a string. While doing this, I understood that to check for multiple conditions in a for loop if we write
for(i=0; condition1, condition2; i++)

the value of condition1 is found and then discarded. Then, the value of condition2 is found and returned. To get around this, we need to use && in case of multiple conditions to be checked by a for loop in here.
for(i=0; condition1 && condition2; i++)

So far I believe I understood right, but the following for loop is not working.
for(i=0; (a[i] != '\0') && (a[i] == b[0]); i++)
{
    j = i + 1;
    k = 1;
    while(a[j] == b[k] && a[j] != '\0' && b[k] != '\0')
    {
        j++;
        k++;
    }
    if(b[k] == '\0')
    {
        return i;
    }
}
return -1;

When I wrote the above for loop, the control is entering the loop and performing the operations, whereas in the following code, control is not even entering the for loop, and it is working correctly.
for(i=0; a[i] != '\0'; i++)
{
  if(a[i] == b[0])
  {
      j = i + 1;
      k = 1;
      while(a[j] == b[k] && a[j] != '\0' && b[k] != '\0')
      {
          j++;
          k++;
      }
      if(b[k] == '\0')
      {
          return i;
      }
  }
}

Is there something I am missing about internal processing in for loops? I believe the way they both should work is the same.

A: These blocks of code don't do the same thing. In the first one, if either condition isn't met then the for loop will stop iterating. In the second block, if the first condition isn't met, then the for loop will stop iterating, whereas if the second one isn't met the internal code isn't executed, but the for loop will continue.
As for the && operator.... It will evaluate all of the conditions in order and it will stop and evaluate to false as soon as it hits an individual component that evaluates to false. If it doesn't run into any false condition then it will evaluate to true.

A: In the first code snippet your for loop has two conditions. Remember when one of them is not true, the loop will terminate immediately.
In the second code snippet, you just have one condition in the for loop. The second condition is inside an if case. So if condition2 is wrong the if case won't be executed, but the for loop will still continue.


text:
Q: Returning a value to another class and storing Suppose given a class Die and it contains a random value for a six sided die.
Another class PairOfDice needs to access getvalue in Die and store two die values.

An error: cannot find symbol occurs when PairOfDice is executed.

How can this problem be fixed? And are there any other suggestions for the java code?
public class Die {
public static Random rand = new Random();
private int sides; // Number of sides
private int value; // Die's value
public Die() {
    sides = 6;
    roll();
}
public void roll() {
    value = rand.nextInt(sides) + 1;
}
public int getSides() {
    return sides;
}
public int getValue() {
    return value;
}

The second class given is:
public class PairOfDice {
private int dieOne;
private int dieTwo;
public void main(String[] args){
    Die die;
    die = new Die();
}
private void dieOne(int value){
    dieOne = die.getValue();
}
private void dieTwo(int value){
    dieTwo = die.getValue();
}
public int getDieOneValue(){
    return dieOne;
}
public int getDieTwoValue(){
    return dieTwo;
}
}

A: This quest should be generalized:
I wrote the Die class with two public constructors. If the constructor is without the parameter, default size of die is six, else you can have any number of sides.
Then, I wrote the Dices class with two constructors. First one have the number of dices (with 6 sides), and second one have the List of dices with preferred sides.
If you want to learn how to generalize the problem (any problem) you can check my code. (Of course, it can be done more efficiently and with more elegance, but here is the simple code):
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class Die {
    private Random RAND = new Random();
    private int noOfSides;
    private int value;

    // Default constructor without the parameter of sides gives the six sized die
    public Die() {
        this.noOfSides = 6;
    }

    // The constructor WITH number of sides
    public Die(int noOfSides) {
        this.noOfSides = noOfSides;
    }

    // rolling the die
    public void roll() {
        this.value = RAND.nextInt(noOfSides) + 1;
    }

    public int getValue() {
        if (value == 0) roll(); // if the die is never rolled -> roll it!
        // else return the rolled value
        return value;
    }

    // just for curiosities
    public int getNoOfSides() {
        return noOfSides;
    }

    public String toString() {
        return "Die has the " + noOfSides + " sides, and the last roll value was " + getValue();
    }
}

class Dices {

    private int noOfDices;
    private List<Die> myDices = new ArrayList<Die>();

    // NO constructor without the number of dices
    private Dices() {
    }

    public Dices(int noOfDices) {
        this.noOfDices = noOfDices;

        // example is for 6 sided dices
        for (int i = 0; i < noOfDices; i++) {
            getMyDices().add(new Die());
        }
    }

    // example with the list of dices with predefined sizes
    public Dices(List<Die> myDices){
        this.myDices = myDices;
    }

    public List<Die> getMyDices() {
        return myDices;
    }

    public String toString() {
        String s = "";
        for (Die die : getMyDices()) {
            s = s + die + "\n";
        }
        return s;
    }
}

public class Answer {

    public static void main(String[] args) {

        //test with two dices (6 size):
        Dices twoDices = new Dices(2);
        System.out.println(twoDices);

        //test with 4 dices size 3, 7, 9, 22
        Dices fourDices = new Dices
                (List.of(new Die(3),
                        new Die(7),
                        new Die(9),
                        new Die(22)));
        System.out.println(fourDices);
    }
}

You can see, if the die is never rolled, getValue first roll the die, then return the value. Otherwise you can roll the die and the value will be stored into the private field value...

A: We will presume that the Die class works as expected.
So, one could think of these changes to PairOfDice that likely resolve the immediate issue.
public class PairOfDice {
  private Die dieOne = new Die();
  private Die dieTwo = new Die();

  public static void main(String[] args) {
    PairOfDice pair = new PairOfDice();
    System.out.printf("Pair: %d - %d%n", pair.getDieOneValue(), pair.getDieTwoValue());
  }

  public int getDieOneValue() {
     dieOne.roll();
    return dieOne.getValue();
  }

  public int getDieTwoValue() {
    dieTwo.roll();
    return dieTwo.getValue();
  }
}

The PairOfDice class should hold references to two dice (in the private Die instance variables).
The getDieXValue() methods work with the instance variables, and return a value, after generating a roll().
Now, the question is whether the requirement is to store the values of two dice, or just access to the ability to get the values. If truly the need is to store the values, then one could do:
public class PairOfDice {
  private int dieOneValue;
  private int dieTwoValue;

  public PairOfDice {
    Die die = new Die();

    // get a value for the first die
    die.roll();
    dieOneValue = die.getValue();

    // get a value for the 2nd die
    die.roll();
    dieTwoValue = die.getValue();
  }

  public int getDieOneValue() {
    return dieOneValue;
  }

  ...

Personally, if one is going to create objects, then store and use the objects.


text:
Q: Getting container to be full viewport width and height, static (with inner scroll on div) I'm not concerned about mobile, but my issue here is on laptop screens, monitors, etc. using bootstrap (though I'm open to using flex if it will be better overall)
This will hold a map in the large column and a list of locations in the small column, but the key I'm trying to achieve right now is a static container that is 100% width and height of the viewport (minus 60px for the header) and no scrolling outside of it. The idea is that the list of locations is an inner/hidden scroll (if that makes sense).
How can I get this container overall to sit full width and height without the ability to scroll outside of it? Even if there are 150 listings, I don't want it to push the height of the stores-list div, I want it to be only an inner scroll

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet"/>

Home

About

          <form id="mapSR" class="home-form" method="post">
          <input id="ss" type="text" name="locationSearch" placeholder="search" style="border-radius:18px; padding:4px; width: 100%;" />
          </form>


text:
Q: Can I do Fine-Gray regression on a split survival dataset? This is my first question here, so if I need to share more information please let me know.
I have done a Cox regression analysis in R in which I am interested in the effect of implant surface on reoperation over 36 months. Here's a reproducible example:
library(survival)

n <- 100
df <- data.frame(id=1:n,
                 time=sample(1:36, n, replace=TRUE),
                 event=sample(0:2, n, replace=TRUE),
                 implantsurface=sample(0:1, n, replace=TRUE),
                 covariate1=sample(0:1, n, replace=TRUE),
                 covariate2=sample(0:1, n, replace=TRUE))
df$time <- as.numeric(df$time)

I adjusted for a number of covariates, which showed that the proportional hazards assumption was violated for covariate1. I split my dataset into 0-4 mo and 4-36 mo as follows (simplified code), so that the PH assumption was no longer violated:
fit1 <- survSplit(Surv(time, event == 1) ~
implantsurface + covariate1 + covariate2,
data = df, cut=c(4),
episode= "tgroup")

fit2 <- coxph(Surv(tstart, time, event) ~
implantsurface + strata(tgroup):covariate1 + covariate2,
data = fit1)

Now I would also like to adjust for competing risks with Fine-Gray regression, but I am unable to do this for the split dataset. I have tried the following:
FG <- finegray(Surv(time = time, event = event.competing, type = "mstate") ~
implantsurface + strata(tgroup):covariate1 + covariate2,
data = fit1, etype = "event_of_interest")

FGfit <- coxph(Surv(fgstart, fgstop, fgstatus) ~
implantsurface + strata(tgroup):covariate1 + covariate2,
weights = fgwt, data = FG)

Error in strata(tgroup) : object 'tgroup' not found

Does anyone know how/if Fine-Gray can be applied to a split survival dataset? Many thanks in advance for thinking along!


text:
Q: Boot script terminates and gives error (no error logger present)  I made an Erlang application, that shall be started on booting of the operating system. The boot script is stored in /etc/init.d. It looks like this:
#!/bin/sh
cd $ROOT/lib/di
INET_ADDR=$(ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
NODE_NAME=$(echo di@$INET_ADDR)
erl -pa $PWD/ebin -pa $PWD/deps/*/ebin -name $NODE_NAME -boot di $1 -setcookie agfeo

The script tries to determine the IP address of the machine, in order to give the node an unique name. When the machine boots, the script gets executed automatically. On the terminal I get the following output:
(no error logger present) error: "Error in process <0.1.0> with exit value:
{badarg,[{erlang,list_to_atom,[[<<2 bytes>>,<<5 bytes>>,46,98,111,111,116]]},
{init,get_boot,2},{init,do_boot,3}]}"
{"init terminating in do_boot",{badarg,[{erlang,list_to_atom,[[<<2 bytes>>,<<5 bytes>>,46,98,111,111,116]]},
{init,get_boot,2},{init,do_boot,3}]}}
init terminating in do_boot ()

This is what the shell prints out, when the script is loaded automatically.
When I call the script manually, my application gets started normally, without any problems.
Could anybody please explain, what the error message above means?

A: If we look at the stack trace the last function executed is init:get_boot/2 and the last instruction is erlang:list_to_atom([<<2 bytes>>, <<5 bytes>>, ".boot"]). In the init:get_boot/2 there are three lines with list_to_atom, so error should be one of the following:

*

*'cannot get bootfile';

*'bootfile format error';

I believe the error is 'cannot get bootfile'.


text:
Q: how to count arrays within an array in ruby and return this value I am trying to count the arrays themselves not the elements. so say i had the following
  arrays = [["1 2"],["3 4"],["5 6"],["6 7"]]

i am then trying to find a way to return only one of these arrays as a set of instructions if asked for?

A: Your example showed a multi-dimensional array, which is an array of arrays.
To count the number of arrays in this 2 dimensional array, in other words the number of elements, you could use the following methods.
arrays = [["1 2"],["3 4"],["5 6"],["6 7"]]
arrays.length
arrays.size
arrays.count

If you would like to return one of them you simply reference the element
arrays[0]
=> Returns ["1 2"]

If you want to return a random element,
arrays.sample
=> Returns a random array