text:
Q: MongoDB Query to find the list of customers who has SELL and PURCHASE Both I am using mongoDB as NoSql Database. I have two collections One is CUSTOMER(CID,CNAME) and Other one is SHOP(Bill_No, Type, Amount,CID)
In SHOP Collection, CID is referenced with Customer(CID).Also Type can be either "SELL" or "PURCHASE".
db.CUSTOMER.insertOne({"CID":1,"CNAME":"Mark"});
db.CUSTOMER.insertOne({"CID":2,"CNAME":"Chris"});
db.CUSTOMER.insertOne({"CID":3,"CNAME":"James"});

db.SHOP.insertOne({"Bill_No":1,"TYPE":"SELL","Amount":1000,"CID":1});
db.SHOP.insertOne({"Bill_No":2,"TYPE":"SELL","Amount":350,"CID":2});
db.SHOP.insertOne({"Bill_No":3,"TYPE":"PURCHASE","Amount":450,"CID":1});
db.SHOP.insertOne({"Bill_No":4,"TYPE":"PURCHASE","Amount":360,"CID":3});
db.SHOP.insertOne({"Bill_No":5,"TYPE":"SELL","Amount":800,"CID":3});

What should be query to find the list of customers who has SELL and PURCHASE Both.
So according to given data the output should be like
"CID":1, "NAME":"MARK"
"CID":3, "NAME":"JAMES"
Thanks in advance..

A: You can use $lookup for aggregation, click here for reference.
Syntax
{
   $lookup:
     {
       from: <collection to join>,
       localField: <field from the input documents>,
       foreignField: <field from the documents of the "from" collection>,
       as: <output array field>
     }
}

In your case the query would be
db.CUSTOMER.aggregate([
   {
     $lookup:
       {
         from: "SHOP",
         localField: "CID",
         foreignField: "CID",
         as: "SELL_PURCHASE"
       }
  }
])

A: Demo - https://mongoplayground.net/p/ZXylHb2g7Dm

*

*Get all details linked to CUSTOMER from SHOP using $
lookup

*Use $group combine all types into 1 document

*To match both types "PURCHASE", "SELL" use $all

db.CUSTOMER.aggregate([
  {
    $lookup: {
      from: "SHOP",
      let: { c_id: "$CID" },
      pipeline: [
        { $match: { $expr: {$eq: [ "$CID", "$$c_id" ] } } },
        { $group: { _id: null, types: { "$addToSet": "$TYPE" } } },
        { $match: { types: { $all: [ "PURCHASE", "SELL" ] } } }
      ],
      as: "trades"
    }
  },
  { $match: { "trades.types.0": { $exists: true } } },
  { $project: { _id: 0, CID: 1, CNAME: 1 } }
])


text:
Q: Submit onclick not working I am trying to code a post form which sends the form to another window and then reloads the window in which the form was submitted in.
page2 is not on the same domain as page1 and i can't access the code of page2.
My current form on page1 looks like this:

<form target="_blank" method="post" action="https://www.page2.com">
<input type="hidden" name="input1" value="input1value">
<input type="submit" value="Submit" onclick="function1();window.location.refresh()">
</form>

The form is being send successfully and the function is being executed but the tab won't refresh.

A: Try this..
<form target="_blank" method="post" action="https://www.page2.com">
 <input type="hidden" name="input1" value="input1value">
 <input type="submit" value="Submit"onclick="window.location.reload();">
</form>

A: While your use case is not obvious at the moment, this might be useful.
Handle submit using script, prevent the default action, post the form and then reload the page.
<form id="myForm" target="_blank">
 <input type="submit" value="Submit" onclick="wait(event);" >
</form>

script
function wait(e)
{
 e.preventDefault();
 document.getElementById('myForm').submit();
 console.log('done!')
 window.location.reload();
}

A: try this code this will refresh you page 1.

     function function_one(){
      $.ajax({
       url: 'show.php',
       type: 'POST',
       data: {'value': $("#input1").val()},

       success: function(data){

        window.location.refresh();
       }
      });
     }

  <form target="_blank">
    <input type="text" name="input1" value="input1value" id="input1">
    <input type="submit" value="Submit" onclick="function_one()">

    </form>

redpajama_set_name: RedPajamaStackExchange


text:
Q: using a new component with react js I have created a LogOut button component over my react app.
This is how it looks like:
 import React, { Component } from 'react';
 import PropTypes from 'prop-types';

 export class LogOutButton extends Component {
  static contextTypes = {
    store: PropTypes.object.isRequired,
  };

  handleClick = () => {
    this.context.store.dispatch();
  };

  render() {
    return <button type="button" onClick={this.handleClick}>Logout</button>;
  }
}

All I want to do is to use this component inside index.js such that when the user clicks the LogOut button, he will be directed to www.google.com.

*

*How should I change the LogOutButton component so it will redirect the user to google.com ?

*How should I use the component inside index.js ?
This is my index.js:
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { LogOutButton } from './components/LogOutButton.js';

class Home extends React.Component {
  displayName = Home.name;

  state = {
    result: 0,
    val1: 0,
    val2: 0,
  };

  handleChangeOne = event => {
    this.setState({ val1: event.target.value });
  };

  handleChangeTwo = event => {
    this.setState({ val2: event.target.value });
  };

  add = () => {
    this.setState({
      result: parseInt(this.state.val1) + parseInt(this.state.val2)
    });
  };

  render() {
    return (

Hello world! The result is: {this.state.result}

        <input type="text" onChange={this.handleChangeOne} />
        +
        <input type="text" onChange={this.handleChangeTwo} />
        =

        <button onClick={this.add}>Add</button>

        <button onClick={LogOutButton}>Log Out</button>

    );
  }
}

I know that it is wrong to write this line inside render()
<button onClick={LogOutButton}>Log Out</button>

However I don't know how to make the LogOutButton component work.
Thanks in advance.

A: Add onLogout prop to your Logout component and call it when button is clicked.
export class LogOutButton extends Component {
  static contextTypes = {
    store: PropTypes.object.isRequired,
  };

  handleClick = () => {
    this.context.store.dispatch();
    this.props.onLogout();
  };

  render() {
    return <button type="button" onClick={this.handleClick}>Logout</button>;
  }
}

Then in your index.js, pass a function to onLogout prop so that the passed function will be called on button click.
onLogoutClick = ()=>{
    window.location.href = 'https://www.google.com';
  }

  render() {
    return (

Hello world! The result is: {this.state.result}

        <input type="text" onChange={this.handleChangeOne} />
        +
        <input type="text" onChange={this.handleChangeTwo} />
        =

        <button onClick={this.add}>Add</button>

        <LogOutButton onLogout={this.onLogoutClick} />>

    );
  }


text:
Q: How to compare results of factor analysis done on two groups? I have two groups, healthy and patients with schizophrenia. I used fa in psych package in R to compute the factor structure in each group. The factor structures appear different. How do I do a statistical test to tell if they are significantly different? Can I identify which factor is the most different?

A: This test is best carried out using confirmatory factor analysis. I recommend the lavaan package, since you are using R. Check the author's tutorial for the how-to.
The idea is to fit the same model to each population, allowing different values of the parameters but the same structure. Then compare, using ANOVA (basically a likelihood ratio test), to a model that fits the two populations forcing corresponding coefficients to be the same.
There are several choices here: you might posit that the factor loadings are the same, but the error variances are different; or you might posit that the measurement models are the same but that intercepts differ ... so that schizophrenics obtain, overall, higher scores on the measure, but the covariance structure of the measure if the same. All of these options are available through lavaan. You need to give some thought to how you believe the models will differ between "normal" and schizophrenics.
If there is a significant difference between the models, you could look at how they differ. You might want to look at modification indices for the "equality" model and see which elements of the model are causing lack of fit.


text:
Q: Loop of promises. How to detect which promise returns the result now? I think it's a common question, but for concreteness the situation is:
I use the mammoth module to convert docx files to html. The module returns a promise.
I have an array of files and when I use a loop to create a promise for every file I need to know what promise returns me a result (to know what file was processed).
for(var i=0;i<filesPaths.length;i++){
    mammoth.convertToHtml( {path: filesPaths[i]} )
        .then(function(result){
            filesHtml.push(result.value);
            //here I need to know the value of filesPaths[i]
        })
}

A: While writing the question, the answer became obvious (as is often the case :) ).
You can wrap the promise with a self invoked function and store any related info in local variable.
for(var i=0;i<filesPaths.length;i++){
   (function(){
     var fileName = filesPaths[i]; //or any other information related to promise
     mammoth.convertToHtml( {path: filesPaths[i]} )
        .then(function(result){
            filesHtml.push({
                text:result.value,
                fileName:fileName
                         });

        })
    })()
}

A: You can use .map() array method (which is much like your solution in terms of function calls, but a bit cleaner):
filesPaths.map(function(fileName, i){
  mammoth.convertToHtml({path: fileName})
    .then(/* ... */)
  ;
});
// Here filesHtml is empty and you don't know when will be filled!!

...which is dirty (see the comment at the end).
Or you can simply use Promise.all() to collect the results:
var P = Promise.all(
  filesPaths.map(function(fileName){
    return mammoth.convertToHtml({path: fileName});
  })
).then(function(resultArr){
  return Promise.all(resultArr.map(function(result, i){
    return {
      text: text.value,
      fileName: filesPaths[i],
    };
  }));
}).then(function(filesHtml){
  /* Here you know filesHtml is fully filled */
});

P.then(function(filesHtml){
  /* ...and here too */
});

This way, you also aren't messing things with global (or higher scope) variables.

A: To respond to your own answer with an alternative:
Creating functions in loops is not a great idea, it's a pretty good way to an unknown number of functions created. If you used a forEach loop you would get the same encapsulation in its callback function.
var arr = ['a', 'b', 'c'];

function prom(thing) {
    return Promise.resolve(thing);
}

for (var i = 0; i < arr.length; i++) {
    prom(arr[i]).then(function(val){
        console.log(`for: got val ${val} with arr[${i}]`);
    });
}
// Logs:
// "for: got val a with arr[3]"
// "for: got val b with arr[3]"
// "for: got val c with arr[3]"

arr.forEach(function(val, index) {
    prom(val).then(function(val){
        console.log(`forEach: got val ${val} with arr[${index}]`);
    });
});
// Logs:
// "forEach: got val a with arr[0]"
// "forEach: got val b with arr[1]"
// "forEach: got val c with arr[2]"


text:
Q: Custom feature extraction class in scikit-learn I am very beginner to the scikit-learn .I am working on some classification problem for which I have to build some custom feature extraction class or method to find the features for the training data.
I have made my custom feature extraction class as explain in this link. When i run my code it shows me this error :-
Traceback (most recent call last):
  File "test.py", line 248, in <module>
    pred = pipe.predict(X_test)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/utils/metaestimators.py", line 54, in <lambda>
    out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/pipeline.py", line 327, in predict
    return self.steps[-1][-1].predict(Xt)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/linear_model/base.py", line 336, in predict
    scores = self.decision_function(X)
  File "/usr/local/lib/python2.7/dist-packages/sklearn/linear_model/base.py", line 317, in decision_function
    % (X.shape[1], n_features))
ValueError: X has 174 features per sample; expecting 443

Below is my code snippet , also i have given my full code. Please tell me where i am doing wrong and why , along with the suggestions so that my code will run without any error.
Code snippet :-
Here "y" is a list of all categories or labelled group ."corpus" is the list of all documents (data) , where each doc. is represented like a string."tfidf" and "lda" are my two functions from which i am generating my feature vector
y = [d[0] for d in doc_info_with_label] #length is no:ofsamples
corpus = [d[1] for d in doc_info_with_label]

class feature_extractor(TransformerMixin):
    def __init__(self,*featurizers):
        self.featurizers = featurizers
    def fit(self,X,y=None):
        return self
    def transform(self,X):
        collection_features=[]
        for f in self.featurizers:
            collection_features.append(f(X))
        feature_vect=np.array(collection_features[0])
        if len(collection_features)>1:
            for i in range(1,len(collection_features)):
                feature_vect=np.concatenate((feature_vect,np.array(collection_features[i])),axis=1)
        #print feature_vect.shape
        return feature_vect

my_featurizer = feature_extractor(tfidf,lda)
X = my_featurizer.transform(corpus)
X_train , X_test , y_train , y_test = train_test_split(corpus,y,test_size=0.2,random_state=42)
pipe = make_pipeline(my_featurizer,svm.LinearSVC())
pipe.fit(X_train,y_train)
pred = pipe.predict(X_test)
print "Expected output\n"
print y_test
print "\n"
print "Output\n"
print pred
print "\n"
score = pipe.score(X_test,y_test)
print score
print "\n"
print metrics.confusion_matrix(pred,y_test)

full code :-
# -*- coding: utf-8 -*-
#! /usr/bin/env python3
from gensim import corpora, models
import gensim
from operator import itemgetter
import numpy as np
import sys
import os
import re
import codecs
import io
import math
from scipy import sparse
from sklearn.cross_validation import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.base import TransformerMixin
from sklearn import svm
from sklearn import metrics
from sklearn.pipeline import make_pipeline , Pipeline

reload(sys)
sys.setdefaultencoding('utf8')
np.set_printoptions(threshold='nan')

suffixes = {
    1: ["ो", "े", "ू", "ु", "ी", "ि", "ा"],
    2: ["कर", "ाओ", "िए", "ाई", "ाए", "ने", "नी", "ना", "ते", "ीं", "ती", "ता", "ाँ", "ां", "ों", "ें"],
    3: ["ाकर", "ाइए", "ाईं", "ाया", "ेगी", "ेगा", "ोगी", "ोगे", "ाने", "ाना", "ाते", "ाती", "ाता", "तीं", "ाओं", "ाएं", "ुओं", "ुएं", "ुआं"],
    4: ["ाएगी", "ाएगा", "ाओगी", "ाओगे", "एंगी", "ेंगी", "एंगे", "ेंगे", "ूंगी", "ूंगा", "ातीं", "नाओं", "नाएं", "ताओं", "ताएं", "ियाँ", "ियों", "ियां"],
    5: ["ाएंगी", "ाएंगे", "ाऊंगी", "ाऊंगा", "ाइयाँ", "ाइयों", "ाइयां"],
}

categories=['A','C','D','E']
mappings={}
mappings['A']=1
mappings['C']=3
mappings['D']=4
mappings['E']=5

path='/home/priyansh/Downloads/ltrc/1055/'
train_data_path='/home/priyansh/Downloads/ltrc/extractor/clustering/four_class_devanagari/'
path1=train_data_path+"A/"
path2=train_data_path+"C/"
path3=train_data_path+"D/"
path4=train_data_path+"E/"
documents=[] #contains all doc filenames along with class labels
doc_info_with_label=[] #two tuple storage of doc info along with their respective labels

def hi_stem(word):
    for L in 5, 4, 3, 2, 1:
        if len(word) > L + 1:
            for suf in suffixes[L]:
                if word.endswith(suf):
                    return word[:-L]
    return word

def store_data(dir_path_list):
    for dir_path in dir_path_list:
        class_name = dir_path.split("/")[8]
        for filename in os.listdir(dir_path):
            if filename not in documents:
                documents.append(filename+"+"+str(mappings[class_name]))
            infilename=os.path.join(dir_path,filename)
            with codecs.open(infilename,'r','utf-8') as fl:
                string=''
                for line in fl:
                    for word in line.split():
                        if word!=" " or word!="\n":
                            string+=word+" "
            fl.close()
            temp=[]
            temp.append(class_name)
            temp.append(string)
            doc_info_with_label.append(tuple(temp))

path_list=[]
path_list.append(path1)
path_list.append(path2)
path_list.append(path3)
path_list.append(path4)
store_data(path_list)

y = [d[0] for d in doc_info_with_label] #length is no:ofsamples
corpus = [d[1] for d in doc_info_with_label]

class feature_extractor(TransformerMixin):
    def __init__(self,*featurizers):
        self.featurizers = featurizers
    def fit(self,X,y=None):
        return self
    def transform(self,X):
        collection_features=[]
        for f in self.featurizers:
            collection_features.append(f(X))
        feature_vect=np.array(collection_features[0])
        if len(collection_features)>1:
            for i in range(1,len(collection_features)):
                feature_vect=np.concatenate((feature_vect,np.array(collection_features[i])),axis=1)
        #print feature_vect.shape
        return feature_vect

def tfidf_score(word,document_no,corpus_data):
    #print word
    my_word=word
    stopwords_path='/home/priyansh/Downloads/ltrc/extractor/'
    stop_words_filename='stopwords.txt'
    stopwords=[] #contain all stopwords
    with codecs.open(stopwords_path+stop_words_filename,'r','utf-8') as fl:
            for line in fl:
            for word in line.split():
                    stopwords.append(word)
    fl.close()
    document=corpus_data[document_no]
    #print document
    wordcount=0
    total=0
    temp = document.split()
    for i in temp:
        #print i
        if i not in stopwords:
            total+=1
            if i==my_word:
                #print my_word
                #print word
                wordcount+=1
    #print wordcount
    #print total
    tf = float(wordcount)/total
    #print tf
    #return tf(word,document)*idf(word,corpus_data)
    total_docs = len(corpus_data)
    count=0
    for doc in corpus_data:
        temp=[]
        temp = doc.split()
        for i in temp:
            if i==word:
                count+=1
                break
    total_docs_which_contains_the_words=count
    idf = math.log(total_docs/(1+total_docs_which_contains_the_words))
    return tf*idf

def tfidf(corpus_data):
    word_id_mapping={}
    cnt=0
    stopwords_path='/home/priyansh/Downloads/ltrc/extractor/'
    stop_words_filename='stopwords.txt'
    stopwords=[] #contain all stopwords
    with codecs.open(stopwords_path+stop_words_filename,'r','utf-8') as fl:
            for line in fl:
            for word in line.split():
                    stopwords.append(word)
    fl.close()
    unique_words_in_corpus={}
    count=0
    for data in corpus_data:
        corpus_id=count
        temp=[]
        temp=data.split()
        for word in temp:
            if word not in unique_words_in_corpus:
                unique_words_in_corpus[word]=corpus_id

        count+=1
    stopped_unique_words_in_corpus={}
    for word in unique_words_in_corpus:
        if word not in stopwords:
            stopped_unique_words_in_corpus[word]=unique_words_in_corpus[word]
            word_id_mapping[word]=cnt
            cnt+=1
    #print unique_words_in_corpus
    #print stopped_unique_words_in_corpus
    #print word_id_mapping
    feature_vect=[None]*len(corpus_data)
    #score_vect=[None]*cnt
    for i in range(0,len(corpus_data)):
        score_vect=[0]*cnt
        for word in stopped_unique_words_in_corpus:
            if i==stopped_unique_words_in_corpus[word]:
                #print word
                score=tfidf_score(word,i,corpus_data)
                #print score
                score_vect[word_id_mapping[word]]=score
        feature_vect[i]=score_vect
        return feature_vect

def lda(corpus_data):
    stopwords_path='/home/priyansh/Downloads/ltrc/extractor/'
    stop_words_filename='stopwords.txt'
    stopwords=[] #contain all stopwords
    with codecs.open(stopwords_path+stop_words_filename,'r','utf-8') as fl:
            for line in fl:
            for word in line.split():
                    stopwords.append(word)
    fl.close()
    texts=[]
    for data in corpus_data:
        #print data
        tokens=[]
        temp=[]
        stopped_tokens=[]
        temp = data.split()
        for word in temp:
            tokens.append(word)
        #print tokens
        for i in tokens:
            if i not in stopwords:
                stopped_tokens.append(i)
        stemmed_tokens=[]
        for token in stopped_tokens:
            stemmed_token = hi_stem(token)
            stemmed_tokens.append(stemmed_token)
        texts.append(stemmed_tokens)

    dictionary = corpora.Dictionary(texts)
    corpus = [dictionary.doc2bow(text) for text in texts]
    num_topics=5
    ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=num_topics, id2word = dictionary, passes=10)
    doc_topics=[]
    for doc_vector in corpus:
            doc_topics.append(ldamodel[doc_vector])

    for i in range(0,len(doc_topics)):
            doc_topics[i] = sorted(doc_topics[i],key=itemgetter(1),reverse=True)

    feature_vect=[]
    for i in doc_topics:
        prob_vect=[0]*num_topics
        #print i
        topic_num = i[0][0]
        topic_prob = i[0][1]
        prob_vect[topic_num]=topic_prob
        feature_vect.append(prob_vect)
        #print i
        #print feature_vect
        return feature_vect

my_featurizer = feature_extractor(tfidf,lda)
X = my_featurizer.transform(corpus)
X_train , X_test , y_train , y_test = train_test_split(corpus,y,test_size=0.2,random_state=42)
pipe = make_pipeline(my_featurizer,svm.LinearSVC())
pipe.fit(X_train,y_train)
pred = pipe.predict(X_test)
print "Expected output\n"
print y_test
print "\n"
print "Output\n"
print pred
print "\n"
score = pipe.score(X_test,y_test)
print score
print "\n"
print metrics.confusion_matrix(pred,y_test)


text:
Q: Windows batch file: GOTO, DELAYEDEXPANSION issue See my batch below!

Expected output: Success
Current output: Success
            Error

Any idea, why could be the problem? Without GOTO works as expected.
@ECHO OFF

SETLOCAL ENABLEDELAYEDEXPANSION

SET doIt=1

SET callMeAgain=1

if !doIt! == 1 (

    :loop
    if !callMeAgain! == 1 (
        SET callMeAgain=0
        GOTO :loop
    )

    ECHO Success

) ELSE (

    ECHO Error
)

ECHO.

ENDLOCAL

PAUSE

A: A GOTO breaks any parenthesis block.
A minimal example
if 1==1 (
   echo success
   goto :dummy
   :dummy
) ELSE (
   echo ERROR
)

After the jump to :dummy the batch parser looks at:
) ELSE (
   echo ERROR
)

The IF part is ignored at this point.
The ) ELSE ( part is simply ignored, because a single opening ) works like a line comment here.


text:
Q: Weird result from R regarding structural break test I'm trying to detect structural breaks in time series of NAV using 'strucchange' in R.
I have created the NAV by using a simple annualized return of 5% and 10% (no random term). However, after using 'breakpoints' test in R the result is that the break point is not on the point I have changed return from 5% to 10%.

My code is like:
library(readr)
test <- read_csv("D:/Temp/Test/nav.csv")
View(test)
library(strucchange)
testnav = ts(test$NAV)
bp.test = breakpoints(testnav ~ 1)
plot(testnav)
lines(bp.test, breaks = 1)

The data I use is Here
Did I do something wrong? Why isn't it break on time ~500 where the return changed from 5% to 10%?

A: The weird breakpoint is found because you just look for changes in a piecewise-constant mean (i.e., a step function). However, you clearly need a piecewise-linear function with changes in the trend slope (and intercept). So instead of ~ 1 you can regress on ~ time(testnav) for example:
bptrend <- breakpoints(testnav ~ time(testnav))

The resulting visualization for the 1-break solution is:
plot(testnav)
lines(bptrend, breaks = 1)
lines(fitted(bptrend, breaks = 1), col = 4)
legend("topleft", c("observed", "fitted"),
  col = c(1, 4), lwd = 1, bty = "n")


text:
Q: Joomla 3.2 autocomplete I want an autocomplete field in my page, and my code is right, but it doesn't work. When I used Joomla 2.5 then it worked but I had to change to Joomla 3.2 and it isn't working now. I use these js files:
$doc->addScript(JURI::root().'media/com_szakdolgozat/js/jquery.min.1.4.2.js');
$doc->addScript(JURI::root().'media/com_szakdolgozat/js/typeahead.bundle.js');
$doc->addScript(JURI::root().'media/com_szakdolgozat/js/jquery-ui.min.1.8.1.js');

There is a problem with jquery 1.8.1, because I get error under Joomla 3.2:
Uncaught ReferenceError: jQuery is not defined -->  jquery-ui.min.1.8.1.js:10
Which version shall be right for me?

A: Joomla 3.x comes packed with jQuery by default, therefore you do not need to import your own copy of it. The following code will import it in noConflict mode if it doesn't already detect it:
JHtml::_('jquery.framework');

I think the issue you're having mentioned in your question is that you have 2 instances of jQuery being loaded and therefore it causes conflicts.
Joomla 3.x also has jQueryUI packed with it. So your final code will look like this:
JHtml::_('jquery.framework');
JHtml::_('jquery.ui');
JHtml::_('script', 'media/com_szakdolgozat/js/typeahead.bundle.js');


text:
Q: Angulars $httpBackend not pure unit testing? Angular advocates the use of $httpBackend to test your service. Doesn't that break the principle of unit testing since it also tests angular internals?
Shouldn't we rather test with a mocked $resource (or $http if that's what you use)?
Is this just for convenience?


text:
Q: Significant terms aggregations in Kibana-4 I have been trying to do an aggregation using Kibana-4 and in the aggregations dropdown there is a new type of aggregation saying "siginificant trems" . Would someone explain what it is and what is the best way to visualise it?.

A: Significant aggregations is a type of aggregation which will return unusual or interesting occurrence of terms in a set of data. This is an experimental functionality as of now in elasticsearch,and this has been included in Kibana 4.0 too.
To make things clear,let us do an area graph visualization on an index "comics". Here I have set the Y-axis to the count of occurrences,then an "split area",where I applied a range aggregation(ranges are from 0-10 and 10-30) and  the X axis to have a sub-aggregation of "significant terms",with a size value equal to 4. And the resulting visualization is given below:

You can see in the graph,that there are two area graphs and in the X axis,the hashtag values of our aggregations. Here for eg:,the term "australia" is listed as one of the unusual terms.This may be because of the rise in the tweets with hashtag Australia,as they have won the cricket world cup as recent as 2 days before.
So,this aggregation helps in detecting anomalies or unusual patterns in the data set as illustrated above.


text:
Q: Qt and Arduino serial communication (Read and Write) I am stuck with a very simple problem.
I am trying to make a Qt GUI application to control my Arduino from the GUI (instead of controlling it from the serial monitor of Arduino IDE). I am able to successfully Write to Arduino with QSerialPort write() method, but I am unable to read anything from the Arduino. The only way I can read from the serial port is by using waitForReadyRead(5000) after the write() function in waitForBytesWritten() in my Qt code. But I have to use a 5000 ms time interval to read successfully, which is time taking. Please let me know if there is any faster way of reading Arduino serial port in my Qt GUI application.
I am posting my Qt and Arduino code.
Qt Code
#include "GuiApp.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
#include <QMessageBox>

GuiApp::GuiApp(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
    ui.lcdNumber_temp->display("--------");
    arduino = new QSerialPort(this);

    bool arduino_available = false;
    QString arduino_portName;

    foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
        if (serialPortInfo.hasVendorIdentifier() && serialPortInfo.hasProductIdentifier()) {
            if ((serialPortInfo.productIdentifier() == arduino_pid) && (serialPortInfo.vendorIdentifier() == arduino_vid)) {
                arduino_available = true;
                arduino_portName = serialPortInfo.portName();
            }
        }
    }

    //qDebug() << "Number of ports" << QSerialPortInfo::availablePorts().length() << "\n";
    //foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
    //  qDebug() << "Description" << serialPortInfo.description() << "\n";
    //  qDebug() << "Has Vendor Id?" << serialPortInfo.hasVendorIdentifier() << "\n";
    //  qDebug() << "Vendor Id" << serialPortInfo.vendorIdentifier() << "\n";
    //  qDebug() << "Has Product Id?" << serialPortInfo.hasProductIdentifier() << "\n";
    //  qDebug() << "Product Id" << serialPortInfo.productIdentifier() << "\n";
    //}

    if (arduino_available) {
        arduino->setPortName(arduino_portName);
        arduino->setBaudRate(QSerialPort::Baud9600);
        arduino->setDataBits(QSerialPort::Data8);
        arduino->setParity(QSerialPort::NoParity);
        arduino->setStopBits(QSerialPort::OneStop);
        arduino->setFlowControl(QSerialPort::NoFlowControl);
        arduino->open(QIODevice::ReadWrite);
        if (!arduino->isOpen()) {
            qDebug() << "Arduino Not Opening";
        }
        QObject::connect(ui.pushButton_connect,SIGNAL(clicked()),this,SLOT(button_pressed()));
        QObject::connect(arduino,SIGNAL(readyRead()),this,SLOT(readSerial()));
        //serial.write("OK ---");
    } else {
        qDebug() << "Couldn't find correct arduino port.\n";
        QMessageBox::information(this,"Serial Port Error","Couldn't open serial port to arduino.");
    }
}

GuiApp::~GuiApp()
{
    //serial.close();
    if (arduino->isOpen()) {
        qDebug() << "Arduino Closed!\n";
        arduino->close();
    }
}

void GuiApp::button_pressed() {
    if (arduino->isWritable()) {
        arduino->write("255");
        arduino->waitForBytesWritten(5000);

        //QByteArray s = arduino->readAll();
        //arduino->waitForReadyRead(1000);
        //std::string str = s.toStdString();
        //qDebug("My String %s", str);

    }
    else {
        QMessageBox::information(this, "Serial Port Error", "Couldn't write to Serial port.");
    }
}

void GuiApp::readSerial() {
    qDebug() << "Serial Port Works!!\n";
    QMessageBox::information(this, "Serial Port Works", "Opened serial port to arduino.");
    QByteArray serialData = arduino->readAll();
    QString temp = QString::fromStdString(serialData.toStdString());
    qDebug() << temp;
}

Arduino Code
#include <SPI.h>
#include <Controllino.h>

int led = CONTROLLINO_D1;
int led2 = CONTROLLINO_D2;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(led2,OUTPUT);
  digitalWrite(led,LOW);
  digitalWrite(led2,LOW);

}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available()) {
     const int val = Serial.parseInt();

     if(val == 255) {
        digitalWrite(led,HIGH);
        delay(1000);
        Serial.write("Ok");
     } else {
        digitalWrite(led2,HIGH);
        Serial.write("Not Ok");
     }

  }

}

A: Try connecting the QIODevice::readyRead signal:
    QObject::connect(&serialPort, &QSerialPort::readyRead, [&]() {
        standardOutput << "Recieved: " << serialPort.readAll() << endl;
    });


text:
Q: How to prevent mail from going spam? below is my header to sent the mail to the user -
$to='example@example.com';
$recipient='example@example.com';
$headers = "From: noreply@xxx.com" . "\r\n";
$headers .= "X-Sender: <" . "$to" . ">\r\n";
$headers .= "Return-Path: <" . "$to" . ">\r\n";
$headers .= "Error-To: <" . "$to" . ">\r\n";
$headers .= "Content-Type: text/html\r\n";

mail("$recipient", "$subj", "$body", "$headers")

But the problem occurs when my go in spam (in gmail)
gmail said:-
X-AntiAbuse: This header was added to track abuse, please include it with any abuse report
X-AntiAbuse: Primary Hostname - myexoticfriends.myexoticfriends.com
X-AntiAbuse: Original Domain - gmail.com
X-AntiAbuse: Originator/Caller UID/GID - [510 32003] / [47 12]
X-AntiAbuse: Sender Address Domain - myexoticfriends.myexoticfriends.com
X-Source: /usr/bin/php
X-Source-Args: /usr/bin/php /home/exotic/public_html/test/test.php
X-Source-Dir: myexoticfriends.com:/public_html/test

A: Try using a different STMP server, if you have a Gmail account you can try using SwiftMailer. http://swiftmailer.org/. Also, keep in mind your server's IP address might be listed in some DNS or SMTP blacklists, try looking up your IP in http://www.dnsbl.info/
If you're sending lots of emails, though, I'd recommend you use a mailing service. We've used http://postmarkapp.com/ and it works beautifully.

A: Gmail: keeps on searching and tracking the list of the mails that are send/receive.
If you keep on sending the mails with same subject and content then it will automatically put mails in spam, plus, if the CTR ratio means the click ratio of your mail is less, then too Gmail send them in spam, don't send the mails in bulk.

A: If you're able to share headers from one of the messages that was received but went to spam, someone from the Postmark team would be able to share some insight into what's likely going on.

A: You need to send your mail via a different SMTP as your domain has been flagged as spammy. You can contact gmail if you feel this is an error.


text:
Q: How would I add up each individual average created from a method? I have this program that calculates each persons test score average and it counts each student. I need to print the class average and I know that I just need to add up the averages and then divide by the number of students, my issue is I'm not sure how to actually add up the averages and I'm just a little stuck - any help would be appreciated!
Here's my code:
public class GradeAnalyzer {
public static void main(String[] args) throws FileNotFoundException, IOException {

    Student students[] = new Student[30];
    Scanner scan = new Scanner(new File("student_grades.txt"));
    int studentCount = 0;
    String name;
    double average = 0;

    while(scan.hasNext()){
        int score[]= new int[5];
        name=scan.next();
        for(int i=0;i<score.length;i++) {
            score[i]=scan.nextInt();

        }
        students[studentCount++]=new Student(name, score);
    }

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

        //I assume I would put it here, but I'm pretty sure I could also put it in the for loop above as well

    }

    double classAverage = average/studentCount;

and my calculateAverage method:
public class Student {
private String name;
private char grade;
private double average;
private int score[] = new int[5];

public Student(String name, int[] score) {
    this.name = name;
    this.score = score;
    calculateAverage();
    calculateGrade();
}

public double calculateAverage() {
    double sum = 0;
    for(int i = 0; i < score.length; i++) {
        sum+=score[i];
    }
        average = sum/score.length;
        return average;
}

A: You are calculating the average of each student but you are not retrieving it. You can keep calculating it through the constructor and just add a getter for the average of each student.
public double getAverage() {
    return average;
}

I would try something like this:
 while(scan.hasNext()){
        int score[]= new int[5];
        name=scan.next();
        for(int i=0;i<score.length;i++) {
            score[i]=scan.nextInt();
        }
        students[studentCount]=new Student(name, score);
        average += students[studentCount].getAverage();
        studentCount++;
    }
  double classAverage = average/studentCount;

Also you won't need to let the method Calculate Average to return anything so you can leave it as a void method like so:
public void calculateAverage() {
    double sum = 0;
    for(int i = 0; i < score.length; i++) {
        sum+=score[i];
    }
        average = sum/score.length;
}


text:
Q: Tensor product of Hilbert Spaces I am following this link under "definitions"
I need to see why the suggested inner product on the pre-Hilbert space $H_1$ tensor $H_2$ is well defined.  Recall that the fundamental tensors are a spanning set, but not a linearly independent one, hence not free in the category of vector spaces.  How do I know that this definition is consistent no matter what representation of an element of the tensor space I give?

A: As was pointed out in a comment, probably the simplest way to handle the technical details is to do everything in terms of chosen orthonormal bases for $H_1$ and $H_2$ (to lessen the number of subscripts, I will write $H$ and $K$ instead of $H_1$ and $H_2$ from now on).
But there are other ways to do it, as there are other ways to handle the details of the purely algebraic vector space tensor product (which I will denote by $\otimes_a$, to distinguish it from the Hilbert space tensor product).
One construction of $H \otimes_a K$ is as a quotient $V/W$, where $V$ is the free vector space with basis $H \times K$ and the subspace $W$ the span of an explicit set of vectors (including, e.g. all vectors of the form $(h_1 + h_2, k) - (h_1, k) - (h_2, k)$ with $h_1$ and $h_2$ in $H$ and $k$ in $K$).  In this realization, the "elementary tensor" $h \otimes k$ is simply the image of $(h,k)$ in the quotient $V/W$, and the problem of defining an inner product on $H \otimes_a K$ is a special case of the problem of defining a positive definite Hermitian sesquilinear form on a quotient vector space $V/W$ in terms of something on $V$.  So one can do this as a special case of a more general  algebraic problem.
Suppose $S: V \times V \to \mathbb{C}$ is a positive (not necessarily positive definite) Hermitian sesquilinear form on a complex vector space $V$.  Define
$$
N = \{x \in V: S(x,y) = 0 \text{ for all } y \in V\}.
$$
Note that $N$ is obviously a subspace of $V$.
Fix any subspace $W$ of $V$, and let $q: V \to V/W$ denote the quotient map.  It is easy to verify that

*

*Then there is a positive Hermitian sesquilinear form $S'$ on $V/W$ satisfying
$$
S'(q(x), q(y)) = S(x,y), \qquad x, y \in V,
$$
if and only if $W \subseteq N$.

*In the case that $W \subseteq N$, the form $S'$ on $V/W$ from part 1. is positive definite if and only if $W = N$.
[In proving 2. it helps to recall that the Cauchy-Schwarz inequality for $S$ (which requires only positivity, not definiteness, of $S$) gives the alternate description $N = \{x \in V: S(x,x) = 0\}$ of $N$.]
So we have a general program to follow in the application of interest.
We take $V$ to be the free vector space on $H \times K$ and $W$ the subspace spanned by the elements representing the relations one wants in the tensor product.

*

*It is clear (from freeness) that the recipe
$$
S((\xi_1,\eta_1), (\xi_2,\eta_2)) = \langle\xi_1,\xi_2\rangle_H \langle\eta_1,\eta_2\rangle_K, \qquad \xi_1, \xi_2 \in H, \quad \eta_1, \eta_2 \in K,
$$
gives rise to a well-defined sesquilinear form on all of $V$.

*To know that $S$ is positive on $V$, one must know that for all $n$ and all $\xi_1, \dots, \xi_n \in H$ and $\eta_1, \dots, \eta_n$ the number
$$
\sum_{i,j=1}^n \langle\xi_i,\xi_j\rangle_H \langle\eta_i,\eta_j\rangle_K
$$
is nonnegative.  One way to do this is to recall that the "Gram matrix" $m = (\langle\xi_i,\xi_j\rangle_H)_{i,j=1}^n \in M_n(\mathbb{C})$ of any finite sequence of $n$ vectors in a Hilbert space is positive semidefinite.  So there is $b = (b_{kl})_{k,l=1}^n \in M_n(\mathbb{C})$ with $b^* b = m$, and hence
$$
\sum_{i,j=1}^n \langle\xi_i,\xi_j\rangle_H \langle\eta_i,\eta_j\rangle_K = \sum_{i,j,p=1}^n \overline{b_{pi}} b_{pj} \langle\eta_i, \eta_j\rangle_K = \sum_{p=1}^n \left\|\sum_{k=1}^n \overline{b_{pk}} \eta_k\right\|_K^2 \geq 0.
$$

*It clear that the subspace $W$ one quotients with to get $H \otimes_a K$ is contained in the space "$N$" of the form (just check that each generator of $W$ is in $N$, which is immediate from the sesquilinearity of the inner products on $H$ and $K$).
So the recipe does give, for rather general reasons, a well defined positive sesquilinear form $S'$ on $H \otimes_a K$.
The detail that is not immediately clear in this realization is why the form $S'$ is definite--- ie, why if $x \in V$ satisfies $S(x,x) = 0$, then $x \in W$.  There are several ways to verify this.  One is to note that (since any fixed $x \in V$ is a finite sum $\sum_{j=1}^n (s_j, t_j)$) it suffices to prove this assertion for $H$ and $K$ finite dimensional.  In this case, letting $h = \dim H$ and $k = \dim K$ one can use orthonormal bases of $H$ and $K$ to observe that the quotient $V/N$ contains $hk$ mutually orthogonal vectors and hence has dimension at least $hk$.  Since for purely linear algebraic reasons one knows that $V/W = H \otimes_a K$ has dimension $hk$, it follows that $\dim(N) \leq \dim(W)$, and hence $N = W$ as desired.  (I think you can also tweak the above proof of positivity of $S$ into a proof of definiteness, if you understand the matrix algebraic consequences of an element of $V$ being $0$ in the tensor product.)


text:
Q: why fail to change the factor into date time timestamp Used read.csv file into R, below columns are in factor format by using class() , but need to  calculate the lead time, which is the time difference, so need to transfer to date format, right? but when using library lubridate to change the format from factor to Date, the data all become NA, why is this happening and how to solve? thanks!
A
2017-06-12 13:38:00
NA
test<-dmy(mydata$package_receiving_at)
class(test)

>[1] "Date"
test
>NA


text:
Q: Inaccuracy in SVG? below you can see a picture of a path in Indesign over a screenshot of the svg in the browser. It's a little hard to see, the lines are completely okay, but the curves are sadly not accurate enough.
XML:
<svg xmlns="http://www.w3.org/2000/svg" width="760" height="660"
  xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
    <style type="text/css">
    <![CDATA[
      path {fill:white;stroke:black;}
    ]]>
    </style>
  </defs>
  <path d="M 50.298496904808,177.328388888889  L 164.625988193151,177.328388888889 L 160.222564219419,236.513813861091 Q 108.169653133389,206.464234496512  87.2093550184256,206.99425322761 Q 66.2490569034619,207.524271958709 53.6597040551078,235.630449309736  L 54.9807312472273,200.737549511935 Z" />

</svg>

Does anyone know if there is something I can do in order to make it 100% accurate?


text:
Q: Cutting 1D list into two parts in python I have two one-dimensional lists x and y (unknown huge length) taken from a data table.
I want to take the values of x < 5 and corresponding y values into one set of lists, say {x1, y1}.
Also I want the values of x > 6 and corresponding y values into another set of lists, say {x2, y2}.
How can I do it?

A: Here's one option
z = zip(x,y)  #z = [(x[0],y[0]), ...]

smaller = [(xval,yval) for (xval,yval) in z if xval<= 5]  #those with x<=5
larger = [(xval,yval) for (xval,yval) in z if xval>=6]    #those with x>=6

x1,y1 = map(list,zip(*smaller))   #break them apart and make the results lists, not tuples.

x2,y2 = map(list,zip(*larger))

It's kind of cool how zip(*list) undoes list = zip(.,.) .   Note that there is a bug in this code if x=5.5 is an option.  It would be better to put it as xval>5 for the larger case, but I haven't done that since it's not clear from your question what the criterion should be for 5.5.


text:
Q: How to append types in tuple type in typescript I would like to applend types in following tuple. by using spread syntax, I would like to achieve this.
type A = [a:number,b:string]
type B = [...A,c:boolean]

my desired result is like type B = [a:number,b:string,c:boolean]
But it returned following error.
Tuple members must all have names or all not have names.ts(5084)

What is the root cause of this?  if someone has opinion, will you please let me know

A: See microsoft/TypeScript#43516 for an authoritative answer to this question.
You are using labeled tuple elements; the a, b, and c in your tuples are labels that may help with documentation but don't affect assignability.
According to the TypeScript release notes, one of the rules of labeled tuple elements is either all elements of a tuple should be labeled, or none of them should be labeled.  In the type
type B = [...A, c: boolean];

the initial variadic tuple spread of type A is not labeled, but the last element of type boolean is labeled, so it's an illegal type.
According to microsoft/TypeScript#43516, you need to give a name to that initial rest element:
type B = [...args: A, c: boolean];
// --------> ^^^^^^ <----- give this a label
// type B = [a: number, b: string, c: boolean]

Of course this is a bit weird because the labels from A overrode the args label from B, so you're basically forced to provide something that is immediately ignored.
But according to microsoft/TypeScript#39941 (see this comment) and the discussion in microsoft/TypeScript#43744, the rule is in place because there are cases where the label is necessary and it's apparently hard to tell the difference syntactically.
For example, if A were a regular array type, then you get an output tuple with a leading rest element, and that rest element would get the provided label:
type AA = number[];
type BB = [...args: AA, c: boolean];
// type BB = [...args: number[], c: boolean]

There are some comments in the issues linked about possibly relaxing the rule to allow cases like your code.  But so far it's not part of the language.
So there you go.  If you want to give one element in a tuple a label, you must do so for all elements, even on elements spread from other tuple types.
Playground link to code

A: Apparently you have to write it like
type A = [a: number, b: string]
type B = [...unused_but_required_label: A, c: boolean]

I have no idea why. Editor suggested an autofix when I tried
type B = [label: ...A, c: boolean] // error: label should be before rest dots

A: create a new type as an array, spreading the above tuple types in the new type in the array.
You can just do this:
type A = [a:number,b:string]
type B = [c:boolean]

type C = [...A, ...B]

Typescript Playground


text:
Q: Filter a dataframe with "state" that can take both characters and numeric as input to columns I have a dataframe like this
        id <- c(5738180,51845,167774,517814,1344920,517833,51844)
        state_code <- c("AZ","CA","AZ","WA","MO","CA","AZ")
        state_rank <- c(1,2,1,3,4,2,1)
        df.sample <- data.frame(id,state_code,state_rank, stringsAsFactors=FALSE)

df.sample
       id state_code state_rank
  5738180         AZ          1
    51845         CA          2
   167774         AZ          1
   517814         WA          3
  1344920         MO          4
   517833         CA          2
    51844         AZ          1

I am trying to create a function that takes a df and state as inputs and returns a df based on the filtered state
The state variable should be able to take both state_code and state_rank as inputs
Desired outputs
If I pass in
state = "AZ", return rows filtered for state_code = "AZ"
       id state_code state_rank
  5738180         AZ          1
   167774         AZ          1
    51844         AZ          1

state = "WA,MO", return rows filtered for state_code = c("WA","MO")
       id state_code state_rank
   517814         WA          3
  1344920         MO          4

state = 2, return top 2 ranked states state_rank <= 2
       id state_code state_rank
  5738180         AZ          1
    51845         CA          2
   167774         AZ          1
   517833         CA          2
    51844         AZ          1

I am trying to do it this way but not getting what I wanted
func <- function(df, state){
    df %>% filter(state_code == state)
}

func(df.sample,state = c("AZ"))

I'd really appreciate it if someone can point me in the right direction.

A: I find polymorphic arguments to be cool at times, but they have bitten me too many times to be really useful, especially when the two types/variables have no real connection. I suggest being explicit about the variables,
func <- function(x, codes, rank) {
  if (!missing(codes)) {
    codes <- unlist(strsplit(codes, ",", fixed = TRUE), use.names = FALSE)
    x <- subset(x, state_code %in% codes)
  }
  if (!missing(rank)) {
    x <- subset(x, state_rank <= rank)
  }
  x
}

func(df.sample, codes="WA,MO")   # since your example included the literal "WA,MO"
#        id state_code state_rank
# 4  517814         WA          3
# 5 1344920         MO          4
func(df.sample, codes=c("WA","MO"))
#        id state_code state_rank
# 4  517814         WA          3
# 5 1344920         MO          4

func(df.sample, rank=2)
#        id state_code state_rank
# 1 5738180         AZ          1
# 2   51845         CA          2
# 3  167774         AZ          1
# 6  517833         CA          2
# 7   51844         AZ          1

A: You could just tunnel your filter condition directly to dplyr::filter using {{}}:
library(dplyr)

f <- function(df, cond){
  df %>%
    filter({{ cond }})
}

Output
f(df.sample, state_rank <= 2)
       id state_code state_rank
1 5738180         AZ          1
2   51845         CA          2
3  167774         AZ          1
4  517833         CA          2
5   51844         AZ          1

f(df.sample, state_code %in% c("WA", "MO"))
       id state_code state_rank
1  517814         WA          3
2 1344920         MO          4

A: You could have two different input arguments, one for state and another for state_rank, but if you'd like to keep it as a single argument, you'll need an if-statement to differentiate whether you are filtering by state or state_rank.
func <- function(df, state){
    if(is.numeric(state) {
        df %>% filter(state_rank >= state)
    } else {
        df %>% filter(state_code %in% state)
    }
}

You may want to handle things like "what if you pass state=NA", but hopefully this helps you get started.

A: Using subset
 f1 <- function(dat, state_codes) {
      subset(dat, state_code %in% state_codes)
}

-testing
> f1(df.sample, c("AZ"))
       id state_code state_rank
1 5738180         AZ          1
3  167774         AZ          1
7   51844         AZ          1
> f1(df.sample, c("WA", "MO"))
       id state_code state_rank
4  517814         WA          3
5 1344920         MO          4


text:
Q: Use Arrays within the check Box How can I pass a Array values to check box
I have an Array say loan["1","2","3"] and in my view
 <%= check_box_tag "loan[]" ,c.id , true %>

For the first time i select the ids and Ill save. But at the second time only selected ids(which i have selected for the first time)  should be displayed and rest should be unchecked.
Thanks in advance

A: You must pass two arrays into view - all loans and checked loans.
And in 3rd check_box_tag parameter check their interseption, something like this:

<% @loans.each do |loan| %>
    <%= check_box_tag "loans[]", loan.id, @checked_loans.any? { |checked_loan| checked_loan.loan_id == loan.id } %>
<% end %>


text:
Q: Cross compiling with Clang - `crtbeginS.o: No such file or directory` I'm trying to cross compile a C file to an aarch64 ELF on x86 linux. I've set up a cross build environment on Gentoo but when I run the following command:
clang -target aarch64-unknown-linux-gnu --sysroot=/usr/aarch64-unknown-linux-gnu/ input.c -I /usr/lib/gcc/aarch64-unknown-linux-gnu/11.3.0/ -L /usr/lib/gcc/aarch64-unknown-linux-gnu/11.3.0/

I get the following error:
/usr/bin/aarch64-unknown-linux-gnu-ld: cannot find crtbeginS.o: No such file or directory

However, in the directory /usr/lib/gcc/aarch64-unknown-linux-gnu/11.3.0/, there is a file called crtbeginS.o. My question then is what additional compiler flags am I missing to get the linker to find this file?


text:
Q: Battery drain and over heating I recently switched from Windows 7 to Ubuntu and I have started to see a dramatic decrease in battery life. About 2 hours battery life on Ubuntu, as opposed to when I had Windows (about 5 hours).
What could I do to end this overheating and lengthen battery life?
I have a Samsung Series 7 Chronos i7 2.2ghz 1TB 6GB ram

A: First of all, which version of Ubuntu are you using?
Second, if you have an AMD video card, which drivers are you using? I have many experiences of AMD GPUs overheating when used with the open source drivers or the restricted drivers provided by Ubuntu. You may want to try out the drivers from the AMD website.
Also, check this question out. It is about the HD76xx series, but may apply to others as well.
Finally, search askubuntu for "overheating", you may get many hits.
Regards,
Errikos

A: Install hardware drivers, if using 12.04 LTS download latest one as it comes with 3.8 kernel and lastly install TLP from www.linrunner.de for power savings. My ASUS K55VM laptop matches Windows 8 consumption using Ubuntu 12.04.3


text:
Q: How to apply Lagrange interpolation to mod P polynomials? I understand how to apply Lagrange interpolation to polynomials whose coefficients are rational numbers, but I always confuse myself when it comes to mod P polynomials. For example, say we have the following polynomial:
$$
2x^2 \mod 7
$$
And the points:
$$
(1, 2), (2, 1), (3, 4)
$$
As I begin the product, should I take the modulus of each denominator? Should I then take the modulus of each product? As I sum, should I take the modulus of the final result?
For instance, for the first product, I would normally do:
$$
\frac{(x-2)(x-3)}{(1-2)(1-3)}
$$
Where does the modulus feature here? Do I take the modulus of the coefficients after expanding them? Do I do that each time or only at the end? Do I take the modulus of the denominator? When multiplying it by f(x), do I take the modulus again?
Would anyone be able to show me a step-by-step? I know how to do each modular arithmetic operation separately, but I don't understand where exactly they are used in this case.
Thank you very much!


text:
Q: How to fit different recommendation models into a system I am trying to build a recommendation engine with different sets of models. Is their any way i can keep these models as plug and play type or make these models depend on the other. I am looking an algorithm.
I recently read about the "gradient boosted decision trees", will it be useful in my case and if so, they how should i implement it?
Making a recommendation engine is making my brain go blur. :-). Help.

A: Gradient tree boosting could be plug and play. But you would have to have a fixed tree structure and remember classifiers' performance for each branch. Otherwise you would have to retrain your ensemble each time you add or remove a classifier.
For plug and play ensemble I would just go with bagging.


text:
Q: Make 2 toolbar/footer buttons with 50% width with Swift/Storyboard I'm trying to display a title bar, image, and then two buttons almost like below. The main differences are that I want to two item buttons to be 50% width and each a solid color (taking up the entire bottom of the screen). I'm not using a tab bar because the buttons are just to change the image out, not the entire view controller.

So far using the storyboard, I'm just stuck on the buttons. I have them in a toolbar as bar button items. I then tried to set their width's in the controller:
@IBOutlet weak var firstButton: UIBarButtonItem!
@IBOutlet weak var secondButton: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()
    self.firstButton.width = self.view.bounds.width / 2
    self.secondButton.width = self.view.bounds.width / 2
}

I believe they're being set properly, but the toolbar is forcing some space to be in front of the first button. I haven't even made it to changing their background colors yet, but I'm hoping that will be simple once I finish the spacing.
I'm pretty new to iOS development, so any tips are appreciated. I'm aiming for having it work universally but I'd settle for getting it working on iPhone locked portrait.

A: Using Autolayout is relative easy, You need to set the width of the button equals to the SuperView and set the Multiplier constant to 0.5
Or set the Toolbar width equals to Superview with Multiplier 1.0 and then the UIButtons equals the toolbar's width but with Multiplier 0.5
Something like this

A: Previous answers didn't solve the problem, it looks like there's some internal padding with using a toolbar. That and you might not be able to add constraints to Bar Buttons.
My actual solution is:
Remove Bar Buttons and Toolbar. Add two UIButtons to the bottom. Add the following constraints
First Button

*

*Leading Space to Superview

Second Button

*

*Leading Space to Superview

First Botton and Second Button

*

*Bottom Space to Superview

*Proportional Width to ImageView with a 0.5 multiplier

A: If you're using auto layout, you need to set your toolbar's width equal to the container view with a width constraints. Then set width of two items equal to each other, set those spacings to zero.
There's no need to set their width manually.
BTW, do not forget to do the same thing to your UIImageView if you want it to be full width.
Helpful links:
http://www.raywenderlich.com/83129/beginning-auto-layout-tutorial-swift-part-1
http://www.raywenderlich.com/50317/beginning-auto-layout-tutorial-in-ios-7-part-1
http://www.raywenderlich.com/64392/video-tutorial-beginning-auto-layout

A: Swift 5 using Storyboard:
You can add Flexible Space Bar Button Item to your Toolbar, which will allow equal spacing of your icons. Place them in between your Bar Button Items, and they will automatically fill out the space in your Toolbar.
See below:


text:
Q: Where i need to authentication logic in my mvc project? I have a MVC application where i have used jquery for service calls and displaying in the views. I am planning to add call to authentication  in the layout page, but if user directly calls the partial view page, authentication will not call at all.

A: I am not totally understanding what you are trying to do with the Layout file, but you can decorate your Action methods with [ChildActionOnly] to prevent the user from being able to navigate to them directly.  See:  Using ChildActionOnly in MVC


text:
Q: Pointer type vs result of address of Why does
RECT r;
...
GetClientRect(hwnd,&r);

work, but
LPRECT r =NULL; //must initialize
...
GetClientRect(hwnd,r);

does not work?
I think it has to be initialized

A: You don't have to initialize anything, but you do have provide a pointer to an existing RECT struct.  That's where GetClientRect() will store the returned client rectangle coordinates. Your LPRECT pointer is the right type, but it doesn't point to anything.  If you really want to use a pointer variable, this should work:
RECT r;
LPRECT rp = &r;
GetClientRect(hwnd, rp);

A: Apply the general case to your question.  It doesn't matter if we're talking about a RECT *, an int *, or a Widget *.
The bottom line is that there is absolutely no way you can pass an uninitialized pointer to a function, and have that function initialize the pointer for you.  It is an impossibility in C++.
Take a simple case of passing an int* and attempt to change the pointer to point to an int on return:
void foo(int *x)
{
  // put some code here to attempt to initialize the passed-in pointer
}

int main()
{
   int *p = 0;
   foo(p);  // can you make foo turn p into a non-NULL pointer?  You can't.
}

No matter how hard you will try, there is no code in foo that you can write that will change the int* value passed from main.  It can't be done due to the fact that the pointer is passed by value, and passing by value creates a temporary that is destroyed on return of the function.
To actually change the value of a pointer, you either pass a reference to the pointer, or a pointer to the pointer.  However, the function signature has to change to take an int ** or int *&
So to be clear, a function that requires a pointer to T must be given a pointer to T that points somewhere valid (with the exception being pointers set to NULL as indicators to the function that the pointer is not to be used).


text:
Q: Question on work, energy and power
The engine of a train is working at a constant rate. The maximum speed of the train up a certain incline is $V_{1}$ and the maximum speed down the same incline is $V_{2}$. Then if the train moves on a level track, its maximum speed will be?

The answer given is:
$P = V_{1}(F+F_{g})$
$P = V_{2}(F-F_{g})$
So we get,
$P = V_{3}F$
Where P is the constant power exerted by the engine, $F_{g}$ is the force of gravity on the train and $F$ is the frictional force on the train. So through this the answer I'm getting is $V_{3} = \frac{2V_{1}V_{2}}{V_{1}+V_{2}}$ which matches with the answer given.
But what I'm concerned about is that won't the value of $F$ be different when the train is level? The $θ$ would also play a role here and hence the question would be incomplete.

A: The frictional force and the gravity force here are most probably the projection of the (vector) force along the velocity. Therefore the angular dependence is already taken into account, albeit hidden in the poor notations. And because the slope is the same up and down (up to a minus sign to the angle), the projections have the same absolute value.
I hope it makes sense to you now ?

A: Really, the question should state: "assuming the frictional force on the train (i.e. $F$) is constant", as the answer they give depends on that.
In reality, F will be composed of two main components:

*

*Mechanical friction from the weight of the train acting on the wheel bearings (typically denoted as $\mu R$, where R is the reaction force from the weight), and

*air resistance.

In the case of 1), in reality this will vary with the angle of the incline, since $R = mg \cos\theta$. So, $\mu R$ will be a maximum when the train is on level ground.
In the case of 2), the air resistance is typically modeled as a function depending on $V$ or $V^2$, so this will also vary for each case, if the velocities are different.
In summary, the question is using a simplification that the frictional force is constant, which it should have made clear. Good job to be questioning it though :-)

A: Hint: Up and down have no distinction when the train moves on a level surface. What does this say about the relation between $V_1$ and $V_2$?


text:
Q: View interpretKeyEvents: but pass unwanted ones up the responder chain? I'd really like my custom view to work with -moveLeft:, -deleteForward:, -selectAll:, etc., but I'd also like to pass any keys I didn't care about onward up the responder chain. Right now I'm overriding -keyDown: to call [self interpretKeyEvents:[NSArray arrayWithObject:event]];, but this seems to hog all the key events, even ones my view doesn't respond to.
Is there any way to pass unwanted events up the chain, but still respond to -moveLeft:, etc.? Or do I need to implement all my own actions in -keyDown: so that I know what I did and did not respond to?

A: Came across this trying to find a solution to this same problem. Never found anything online, but I came up with something that seems to work well so far. Here's what I'm doing:
Subclass your NSTextView (or whatever you're using) and create an instance variable to temporarily store the key down event . . .
@interface MyTextView : NSTextView {
    NSEvent* _keyDownEvent;
}

@end

Then define your view's methods like so (take out the retain/release junk if you're using automatic reference counting):
@implementation MyTextView

- (id)initWithFrame:(NSRect)frame {
    if (self = [super initWithFrame:frame]) {
        _keyDownEvent = nil;
    }

    return self;
}

- (void)keyDown:(NSEvent*)event {
    [_keyDownEvent release];
    _keyDownEvent = [event retain];
    [super keyDown:event];
}

- (void)doCommandBySelector:(SEL)selector {
    if (_keyDownEvent && selector == @selector(noop:)) {
        if ([self nextResponder]) {
            [[self nextResponder] keyDown:[_keyDownEvent autorelease]];
        } else {
            [_keyDownEvent release];
        }
        _keyDownEvent = nil;
    } else {
        [super doCommandBySelector:selector];
    }
}

- (void)dealloc {
    [_keyDownEvent release];

    [super dealloc];
}

@end

Here's how I arrived at this.  When a key press isn't handled, you hear a beeping tone.  So, I set a breakpoint on NSBeep(), and when the program broke, I spit out a stack trace in GDB:
#0  0x00007fff96eb1c2d in NSBeep ()
#1  0x00007fff96e6d739 in -[NSResponder doCommandBySelector:] ()
#2  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#3  0x00007fff96fda826 in -[NSWindow doCommandBySelector:] ()
#4  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#5  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#6  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#7  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#8  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#9  0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#10 0x00007fff96e6d72b in -[NSResponder doCommandBySelector:] ()
#11 0x00007fff96f486ce in -[NSTextView doCommandBySelector:] ()
#12 0x00007fff96da1c93 in -[NSKeyBindingManager(NSKeyBindingManager_MultiClients) interpretEventAsCommand:forClient:] ()
#13 0x00007fff970f5382 in -[NSTextInputContext handleEvent:] ()
#14 0x00007fff96fbfd2a in -[NSView interpretKeyEvents:] ()
#15 0x00007fff96f38a25 in -[NSTextView keyDown:] ()
#16 0x0000000100012889 in -[MyTextView keyDown:] (self=0x1004763a0, _cmd=0x7fff972b0234, event=0x100197320) at /path/MyTextView.m:24
#17 0x00007fff96a16b44 in -[NSWindow sendEvent:] ()
#18 0x00007fff969af16d in -[NSApplication sendEvent:] ()
#19 0x00007fff969451f2 in -[NSApplication run] ()
#20 0x00007fff96bc3b88 in NSApplicationMain ()
#21 0x00000001000015e2 in main (argc=3, argv=0x7fff5fbff8f0) at /path/main.m:12

What's happening is this: When the key down event isn't used for text input, a "noop" command is sent up the response chain. By default this triggers a beep when it falls off the response chain. In my solution, the NSTextView subclass catches the noop command and instead throws the original keyDown event down the response chain. Then your NSWindow or other views will get any unused keyDown events as normal.

A: This is my swift implementation of @daxnitro's answer, and seems to work:
import Cocoa

class EditorTextView: NSTextView {

    private var keyDownEvent: NSEvent?

    required init?(coder aCoder: NSCoder) {
        super.init(coder: aCoder)
    }

    override init() {
        super.init()
    }

    override init(frame frameRect: NSRect, textContainer aTextContainer: NSTextContainer!) {
        super.init(frame: frameRect, textContainer: aTextContainer)
    }

    override func keyDown(event: NSEvent) {
        keyDownEvent = event
        super.keyDown(event)
    }

    override func doCommandBySelector(aSelector: Selector) {
        if aSelector != NSSelectorFromString("noop:") {
            super.doCommandBySelector(aSelector)
        } else if  keyDownEvent != nil {
            self.nextResponder?.keyDown(keyDownEvent!)
        }
        keyDownEvent = nil
    }

}

A: I had a closely related issue with a custom NSTextView in an NSTableView. I wanted to be able to shift-select text in the NSTextView, but when all the text was selected, pass the shift-select up the responder chain to the NSTableView.
My solution was simply to override responds(to:) on my NSTextView and decide whether I wanted to handle it there.
override func responds(to aSelector: Selector!) -> Bool  {
  if aSelector == #selector(moveUpAndModifySelection(_:)) {
    return selectedRange().location != 0
  }

  return super.responds(to: aSelector)
}


text:
Q: Hide/Expand-type container in Java I need an expand/hideable component such as show in IntellijIdea's "Edit Configuration" menu:

When clicking on a triangle to the left of "Before launch", it expands/hides the activities therein. I tried this: https://github.com/oliverwatkins/swing_library/blob/master/src/main/java/com/gg/slider/SliderTester.java
Somehow, my speculation is that it expects some sort of a list, since when I tried to put a JPanel with my custom activities, it somehow failed to show. Do you think JetBrains built this thing in a custom way, or is this actually easy? I tried to follow Occam's Razor and not to reinvent the wheel, so I searched around, and posting here since it didn't work for me.


text:
Q: Configure subdomain shinyproxy First things first, I'm quite a beginner at hosting shiny apps on docker and shinyproxy. The terms I use might be a bit layman and incorrect.
I have my application running well on shinyproxy and can be accessed through serveripaddress:8080/app/01_hello.
The problem comes when I try to use a link ie. theapp.company.com instead of the ip address. This is what it shows when I go to the link:

Here is the necessary part of 01_hello nginx configuration file:
   location / {
       proxy_pass          http://localhost:8080/app/01_hello;

       proxy_http_version 1.1;
       proxy_set_header Upgrade $http_upgrade;
       proxy_set_header Connection "upgrade";
       proxy_read_timeout 600s;

       proxy_redirect    off;
       proxy_set_header  Host              $http_host;
       proxy_set_header  X-Real-IP         $remote_addr;
       proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
       proxy_set_header  X-Forwarded-Proto $scheme;
   }

But when I change the proxy_pass to:
proxy_pass          http://localhost:8080;

then go to theapp.company.com it shows the landing page of all apps on shinyproxy and then I can go to theapp.company.com/app/01_hello which works, but not what I want.
I just want it to be theapp.company.com. How do I achieve this?

A: I have a very similar setup and it works for me. I believe the problem is that you are using "app" instead of "app_direct" in proxy_pass. This is my nginx proxy config (localhost instead of 127.0.0.1 or 0.0.0.0 should be fine):
location / {
   proxy_pass          http://127.0.0.1:8080/app_direct/mimosa/;

   proxy_http_version 1.1;
   proxy_set_header Upgrade $http_upgrade;
   proxy_set_header Connection "upgrade";
   proxy_read_timeout 600s;

   proxy_redirect    off;
   proxy_set_header  Host              $http_host;
   proxy_set_header  X-Real-IP         $remote_addr;
   proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
   proxy_set_header  X-Forwarded-Proto $scheme;

 }

Using the /app/ path seems to confuse shinyproxy. If you run shinyproxy via java directly (with your setup) you will see requests that do not match the correct URI. You can also check the console (F12 in chromium), which shows failed loading of resources.
Not sure if this can be fixed easily with the nginx config.
Usually, the navbar at the top is not needed, so app_direct is a simple solution. Hope it helps. If not, can you post your entire nginx config and application.yml? (you can remove sensitive parts)


text:
Q: Firebase functions - how to set type to FirebaseFirestore.QueryDocumentSnapshot This is probably stupid question, but how can I set type for for collection().get() in firestore functions?
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as WineModel from '../../src/app/tasting/wine/wine.model';

admin.initializeApp();

export const countGlogStat = functions.https.onRequest(async (req, res) => {
    const wines: WineModel.WineModel[] = [];
    try {
        const winesSnapshots = await admin.firestore().collection('wines').get();
        winesSnapshots.forEach(wineSnapshot => wines.push(wineSnapshot.data()));
    }
    catch(err) {
        console.log('Error while getting wines', err);
        res.status(500).json({
            custName: 'Error while getting wines',
            err
        });
    }
});

I am getting error:
Argument of type 'DocumentData' is not assignable to parameter of type 'WineModel'.
Property 'wineRating' is missing in type 'DocumentData' but required in type 'WineModel'.
Thank you very much help!!!! :-)


text:
Q: Can't update text of UITextView in a custom UITableViewCell I've been running into an issue that seems to keep coming up on the web, but have been unable to resolve the issue... I'm trying to set the text of a UITextView that's inside of a custom UITableViewCell in a load function that's called on the cell when it's contents are being rendered in its table view.

These are my current settings on my textview that's inside my custom tableviewcell. Note that UserInteraction is NOT enabled, but Editable and Selectable ARE.

This is the controller for my custom UITableViewCell, which contains the function 'loadCell'

This is the cellForRowAtIndexPath that puts the custom tableViewCell into the tableView, and it calls the loadCell() function when it's initialized.

This is the result, with the textView obviously not being updated correctly.
Another note I'd like to add is that if I update the textView during the awakeFromNib function in the custom UITableViewCell controller, it successfully is able to change the text in the textField.
If anyone can help me out, that would be super duper awesome, as I'd love to be able to use textViews instead of labels :) Thanks!

A: So, it turns out that the problem was in the cellForRowAtIndexPath function, in which I was attempting to dequeueReusableCell twice (once at the functions start, and once if the index was 0). I'm not entirely sure why this is causing a problem, though I can make an assumption that it was attempting to dequeue the same cell twice, and was causing problems.
Either way, getting rid of
let cell = tableView.dequeueReusableCellWithIdentifier("MenuItemDescriptionCell")
did the trick.
Hope this helps someone in the future! Happy coding :)


text:
Q: Is there a "startswith" method in pyparsing Hey I have written a very simple parser with pyparsing which detects some tokens in a text and then replaces them with a different string. The problem is that right now my code only works with exact matches. What I'd like to do is detect partial matches too. For example if the token is "foobar" I'd like to match a word like "foobarfoo". Is there a way to do that with pyparsing? I have looked at the examples and did some research but I came up with nothing.
Thanks
EDIT:
I have a list of tokens to match and a list of words in the text. So I want a solution which takes into account this fact. The list of tokens can be quite big.

A: Literal('foobar')+Word(pyp.alphas) defines a pyparsing ParseExpression which requires the text to startwith 'foobar' followed by any alphacharacter. For example:
import pyparsing as pyp
ident = pyp.Combine(pyp.Literal('foobar')+pyp.Word(pyp.alphas))('foo')
for match in ident.searchString('bar foobarfoo bar foobarbafoo'):
    print(match.foo)

yields
foobarfoo
foobarbafoo

A: Simplest would be to use a pyparsing Regex expression in your grammar:
startsWithFoobar = Regex(r"foobar[a-zA-Z0-9_]+")


text:
Q: How to repeat testng suite-files with different parameters My requirement is that I have to repeat a suite (SBSuite.xml) which has multiple tests, with different set of parameters. I tried the below configuration but getting error. Can we repeat the suite-file or what is the correct solution to repeat a single suite file multiple times with params ?
<?xml version="1.0" encoding="UTF-8"?>
<suite name="SBCrossBrowser">
    <listeners>
        <listener class-name="net.sf.testng.databinding.TestAnnotationTransformer"></listener>
    </listeners>
    <suite-files>
        <parameter name="browser" value="CHROME" />
        <suite-file path="SBSuite.xml"/>
    </suite-files>

    <suite-files>
        <parameter name="browser" value="IE" />
        <suite-file path="SBSuite.xml"/>
    </suite-files>
</suite>

I am getting following error :
org.testng.TestNGException:
Two suites cannot have the same name: SBSuite
    at org.testng.TestNG.checkSuiteNamesInternal(TestNG.java:1019)
    at org.testng.TestNG.checkSuiteNamesInternal(TestNG.java:1022)
    at org.testng.TestNG.checkSuiteNames(TestNG.java:1012)
    at org.testng.TestNG.sanityCheck(TestNG.java:985)
    at org.testng.TestNG.run(TestNG.java:1037)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)

A: As you have mentioned you have to repeat a suite (SBSuite.xml) which has multiple tests, with different set of parameters IMO it would be better to put the entire testing steps under Test Annotation. Create single Test Suite to be executed with different set of parameters through <parameter> tag. e.g. <parameter name="browser" value="firefox"/>
Remember to keep the name of the Test Suites different. Through this approach you can execute the TestSuites one after another as well as parallel.
Let me know if this solves your Question.


text:
Q: Pandas: count occurrences that contains words and do not contain other words I'm trying to get a count of the number of entries that contain some words but also must not contain other words. To be clear, I want to get an idea of the number of occurrences assuming an eliminating condition is not met. Here's what I have:
 import pandas as pd
 import re

 data = pd.read_csv('rando-file')

 vague_series = pd.DataFrame([(data['text'].str.contains('bla1|bla2',
                                      flags=re.IGNORECASE, regex = True))

            &

           (~data['text'].str.contains('blah3|bla4',
                                flags=re.IGNORECASE, regex = True))])

 vague_count = vague_series.columns[0].sum()

 print(vague_count)

Any attempt to count or sum has failed in this instance with an invalid syntax error. removing the columns[0] bit resulted simply in a 0, 1 designation in place of true and false.

A: Could you post data sample  for test ?
I try it with a custom sample and it working well:
import pandas as pd
import re

sr = pd.Series(['New_York', 'Lisbon', 'Tokyo', 'Paris', 'Munich'])

idx = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5']

sr.index = idx
result = (sr.str.contains(pat='i[a-z]', regex=True)) & (~sr.str.contains('s[a-z]', regex=True))
print(result.sum())

>>>2

Maybe don't wrap it in DataFrame and try simply:
vague_series = (data['text'].str.contains('bla1|bla2', flags=re.IGNORECASE, regex=True) &
                ~data['text'].str.contains('blah3|bla4', flags=re.IGNORECASE, regex=True))
count = vague_series.sum()


text:
Q: How to create an App folder accessible also by others Apps using SAF in latest Android version without disrupt user experience Scenario an App create documents and has to store and open them.
Before SAF creating a MyAppDocument folder, where the App can store and open every file, was a smooth operation,
now with SAF if I use the intent with ACTION_OPEN_DOCUMENT_TREE in order to get access to the storage place where this folder must be created:
1- Appears the directory access picker dialog
2- If picker is positioned on main storage path(both internal or external sd card) and I target latest Android API level 30, the path cannot be selected and appears also an additional intimidating privacy warning that invite user to create a new folder or select another path to avoid privacy problems as shown in the picture (absurd considering that is supposes to be an user space not some system root directory)

The user can still follow the suggestion to choose a different path or create another folder then choose such path, but this is horrible for user experience, and many users will uninstall the app bothered or scared.
Is there another way to create a folder for the App that can be easily accessible by the user file manager\other apps(so the user can easily copy, open and move and manage files created inside it) without asking so many manual actions to the user?


text:
Q: Set a variable inside the function, but to be used outside? I'm not goot at javascript but i was trying to edit this userscript in order to produce different values everytime a key is pressed.
The original code has the var scanFreq and isDoneLoadingFreq set to an exact value, like 400. I wanted it to be random, that's why the Math function. But it only triggers once, so the code will always be repeating the switch(whichMove) case 1:, case2: etc.
I tried to generate the random numbers insite each case, but then the values won't come outside.
Edit: the isDoneLoadingFreq is beeing loaded in the setInterval(function(), right?
My goal is go make that value random every time a key is pressed :|
Edit2: (Code edited according to wwv)
This first function is triggered once it finds a pokémon. But It's old code, and the objective is that after the alert is closed, the code should not run more. What do I need to change? (Check the pastebin in the end of the post for more code, if you think there's something missing)
Edit3: Edited the function in order to stop the loop after an alert pops, but it's still happening
function found(thing){
        if($('#pkmnappear').first().html().toLowerCase().indexOf(thing.toLowerCase()) > -1){
            alert("Found Something");
            finderOn = true;
            clearInterval(a);
            if(autoWalkFind){
                clearInterval(b);
            }
            return true;
        }else{
            return false;
        }
    }
function setFinder(){
            finderOn = true;

            if(autoWalkFind) {
                var b;

                var checkLoading = function(){
                    var isLoading = $("#pkmnappear").text().indexOf("Please wait") > -1;
                    if(!isLoading){
                        switch(whichMove){
                            case 1:
                                fireKey(document,37);
                                whichMove = 2;
                                break;
                            case 2:
                                fireKey(document,38);
                                whichMove = 3;
                                break;
                            case 3:
                                fireKey(document,39);
                                whichMove = 4;
                                break;
                            case 4:
                                fireKey(document,40);
                                whichMove = 1;
                                break;
                        }
                        moveTimes=0;
                    }else{
                        moveTimes++;
                         // Not done loading. check again after a random delay
                        b = setTimeout(checkLoading, Math.floor(Math.random() * 300) + 400);
                    }
                    if(moveTimes >= 100)
                        location.reload(true);

                    // call setTimeout again with a new delay
                    b = setTimeout(checkLoading, Math.floor(Math.random() * 300) + 400);
                }

                // call setTimeout with the first delay
                b = setTimeout(checkLoading, Math.floor(Math.random() * 300) + 400);
            }

            var a;
            var scan = function(){
                var stopChecking = false;

                if(findPokemon)
                    for (var i = 0; i < pokemonToFind.length; i++)
                        stopChecking = stopChecking || found(pokemonToFind[i]);

                if(findLevels)
                    for (var i = 0; i < levelsToFind.length; i++)
                        stopChecking = stopChecking || found("Level: " + levelsToFind[i] + " ");

                if(findLevelsAndUp)
                    for(var l = levelsAndUpToFind; l<101;l++)
                        if (found("Level: " + l + " ")) {
                            stopChecking = true;
                            break;
                        }

                // Nothing found. check again after a random delay
                if(!stopChecking) {
                    a = setTimeout(scan, Math.floor(Math.random() * 100) + 120);
                }
            }

            // call setTimeout with the first delay
            a = setTimeout(scan, Math.floor(Math.random() * 100) + 120);

       }

        setFinder();

This is a link to the whole code I was using, just in case it's necessary: https://pastebin.com/Q0GudL5c

A: scanFreq and isDoneLoadingFreq are defined only when setFinder is called. In order to make it dynamic you have to define it as a function like this for example
var scanFreq = (function () { return Math.floor(Math.random() * 2000) + 110; });
var math2 = (function () { return Math.floor(Math.random() * 2000) + 400; });
var isDoneLoadingFreq = math2;

And then in setInterval you call setInterval(your_func, scanFreq())

A: setInterval will repeatedly execute the code at a set frequency. I'm not aware of any way to change that frequency, so changing those variables will have no effect.
However, setTimeout, will execute the code only once. Then if you add setTimeout calls at the end of the function, you can randomly generate a new delay each time.
To do that though you'll have to store the functions in variables. So your code will end up looking something like this:
    function setFinder(){
        finderOn = true;

        if(autoWalkFind) {
            var b;

            var checkLoading = function(){
                var isLoading = $("#pkmnappear").text().indexOf("Please wait") > -1;
            if(!isLoading){
                // ...
            }else{
                moveTimes++;

                    // Not done loading. check again after a random delay
                    b = setTimeout(checkLoading, Math.floor(Math.random() * 2000) + 400);
            }
                // ...
                // ...
            }

        }

        var a;
        var scan = function(){
            var stopChecking = false;

            if(findPokemon)
                for (var i = 0; i < pokemonToFind.length; i++)
                    stopChecking = stopChecking || found(pokemonToFind[i]);

            if(findLevels)
                for (var i = 0; i < levelsToFind.length; i++)
                    stopChecking = stopChecking || found("Level: " + levelsToFind[i] + " ");

            if(findLevelsAndUp)
                for(var l = levelsAndUpToFind; l<101;l++)
                    if (found("Level: " + l + " ")) {
                        stopChecking = true;
                        break;
                    }

            // Nothing found. check again after a random delay
            if(!stopChecking) {
                a = setTimeout(scan, Math.floor(Math.random() * 2000) + 400);
            }
        }

        // call setTimeout with the first delay
        a = setTimeout(scan, Math.floor(Math.random() * 2000) + 400);

   }


text:
Q: Ajax loading for complex projects My problem is actually not the ajax loading itself, more the capability to load it without javascript. I mean, I cope easily when I code my whole project just based on ajax-availability OR just without the use of ajax.
//EDIT: Although Arend already had a more or less valid answer, at the same time 'there is no direct answer to this question'. However, I'd like to see some other approaches of developers for scenarios like mine though! Even just a few links can help!
Basically I just get frustrated, coding everything twice on the same page to make sure that both users without and with Javascript enabled have the same experience. It's annoying and I was always wondering how others solve this problem.
When I update for example two divs with dependency on the same variables, it gets messy. Here's an example:
non-js-version
require 'classobject.class.php';
$another_var = 'something';
$class = new classobject($_POST['variable']); // just an example to show that this is dynamic - I'm aware of injection!
$function = $class->returnsth(); // returns 1

if(isset($_POST)) {
    echo '
Module 1 says:'; $require 'module_one.php'; echo '
';
    echo '

';
    echo '
Module 2 says:'; $require 'module_two.php'; echo '
';
}

Now in module_two.php and module_two.php I have code that executes differently depending on the return variable of $function.
Like:
if($function >= 1 && another_var != 'something') {
   // do stuff
}
else {
   // do other stuff
}

Now as this works easily with a reload, when I want to load the two modules on keyUp/enter/submit or whatever, I have basically a few problems:

*

*I have to send the $_POST variables manually to the modules to use them

*I have to re-execute the class & it's methods and make a link (require_once) to them in each of the module-files.

*As $another_var is not existent in the modules, I'd have to send this variable to each modules, too (with post for example) and then before it can be used, I'd have to 'change' it like $another_var = $_POST['another_var'];
I find this mildly annoying and I wonder how you guys do that. I hope my way of coding is not too silly, but I can't think of another way. It's probably hard to relate to my very basic example, but to bring a whole project with the code would be too much. To sum it up, I'm looking for a better way to code and clean this mess up - there must be a way! I thought about sessions, but for compatability I don't want to rely on them either (if someone doesn't allow cookies).
In case you can't relate to what I'm trying to accomplish with that way of having my code assembled, I'll explain a scenario I'm facing quite a lot (not important if you already understand my misery):

*

*Basically I have my index.php page where everything gets executed, with the html body and css styling and so on. This page expects some variables, that get set from the page that requires the index (like $another_var in my example).

*Now other variables can get set too (from a form for example). Depending on that different classes and methods load new variables (arrays) that get used in while-loops in my modules to echo everything out.

Hope that's not too abstract. Think of a booking system where some variables are set from the page you are coming from (the event you want to book) and then a few more things get set by the user (a timespan, some preferences,...). In the end it's supposed to show results from the database all the way to the end-result - you can say the user narrows the results from step to step.

A: There is no direct answer to your question, but there is some food for thought.
Seperation of concerns
You can think about if you can perhaps seperate your buisness logic and layout logic. Often the use of a template engine can help greatly with that. I've had positive experiences with for example Twig or Smarty (was some time ago, not sure how they measure up right now). It requires you to write your code in a (less linear) way, but more logical.
A typical example of an OOP like seperation of concerns might be something like this:
$this->setParam('Myparam','myvalue');

if ($this->isAjax())
{
    $this->setTemplate('ajax.php');
    $this->setLayout(false);
} else {
    $this->setTemplate('normal.php');
    $this->setLayout('Mylayout');
}

return $this->render();

It is an imaginative situation, which can be found in many MVC like applications and frameworks. The main idea is that you should have the possibility to seperate your layout from your data. I would suggest looking at some of the modern frameworks for inspiration (like symfony, codeigniter, zend framework).
Glossary / Often applied concepts in a decoupled PHP application
Here is a quick list of concepts that can be used.
Example mvc in php: http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
Note: I don't really like the implementation. I much more prefer the existing frameworks. I do like the explanation in total of this tutorial. E.g. for me this link is for learning, not for implementing.
Silex
For a simple decoupled php micro-framework I would really recommend silex, by the makes of symfony2. It's easy to implement, and to learn, but contains mainy of the concepts described here; and uses all the php 5.3+ goodies such as namespacing and closures.
see: http://silex.sensiolabs.org/
Frontcontroller Pattern
Only have one, and one only point of entry for your code. I usually only have one, and one only point in your application. Usually a frontcontroller 'dispatches' the request to the rest of the application
http://en.wikipedia.org/wiki/Front_Controller_pattern
Routing
A routing system is often used in combination with the frontcontroller pattern. It basically describes which URL is connected to which module / controller. This allows you to change the way people access your app without changing the urls.
See: https://stackoverflow.com/questions/115629/simplest-php-routing-framework
Controller
A controller is the place where buisness logic is applied. Getting the data from the database, checking privileges, setting the template, setting the layout, etc. (although this is also moved outside the controller if it becomes too big of a seperate concern).
Model
The model basically is the layer in which use manage your database. This can be a simple class where you move all your mysql_* functions, or it can be a full-featured ORM. The main philosphy is that all the logic related to fetching and placing information in the database is seperated.
One step up: ORM
An often used method in applications are Object Relational Models, these 'map' SQL records to PHP objects. Doctrine and Propel are two of these well worked out libraries. I heavily rely on these systems in my development. In this sense, the doctrine or propel part will represent the model layer.

*

*Doctrine: http://www.doctrine-project.org/

*Propel: http://www.propelorm.org/

*Other ORMS: Good PHP ORM Library?

*PHP ORMs: Doctrine vs. Propel
View:
The view usually consists of a templating engine. Some use plain PHP as a template, others, such as symfony create a seperate scope in which variables are placed. There are many discussions and opinions about what is best, one is right here on stackoverflow:

*

*Why should I use templating system in PHP?

*PHP vs template engine
Ones I like:
- Twig: http://twig.sensiolabs.org/
- sfTemplate: http://components.symfony-project.org/templating/
- Smarty: http://components.symfony-project.org/templating/
Decoupling mechanisms:

*

*Event based systems
Using events in your can help to seperate the code. For example if you want to send an email after a record has been saved, events are a good solution to do that; in general the model should not have to know about email. Thus events are a way to connect them: you can let your -email-send-class listen to certain records in order for them to send the right email. (Perhaps you'd rather want your e-mails send from your controller, this is probably a matter of taste).

*Dependency injection
When using OOP code in PHP many relied on having singleton classes running around (configuration, etc). From an OOP point of view, this can be considered bad, because it's hard to test it, and it's not considered very elegant to have dependencies running around like that. Dependency Injection is a pattern that came form Java and is now used in the newer frameworks to get around this. It might be a bit difficult to wrap your head around, but you will see it coming back in several new frameworks.
Dependency injection in php: Dependency Injection in PHP 5.3
Frameworks:
A lot of these methods are difficult, or a lot of work to implement yourself. Many will reside to a framework for this. You may or may not need a framework. You may, or may not want to you a framework, it's your choice. But it's still useful to learn how the frameworks do it, and not try to reinvent the wheel yourself.
The no-framework php frameworks: https://stackoverflow.com/questions/694929/whats-your-no-framework-php-framework
Good habits: https://stackoverflow.com/questions/694246/how-is-php-done-the-right-way
Frameworks worth looking at (imho): CodeIgniter, Kahona, CakePHP, Symfony (1.4/2.0), Silex, Zend Franework, Yii. There are many many more, each with their dedicated fans and haters.

A: I wrote something like this with PHP.  I already had abstracted the rendering of every page such that I define a $content variable and then require('layout.php').  The $content variable is just a big HTML string.
I wrote a PHP function to determine if request was AJAX or not.
The non-AJAX responses render the layout with $content in the middle, b/t header and footer layout content.
AJAX requests basically get this: json_encode(Array("content"=>$content)).  And I use jQuery to get the HTML out of the JSON response and modify the DOM.  Using json_encode() will handle escaping the string for javascript.
In the end, I effectively have AJAXified every page w/o over-engineering a complex solution.
Any browser that supports AJAX can also open a link in a new tab/window to simulate the non-AJAX request.  (Or bookmark/share a link, too.)