text:
Q: Using NSURLSession with backgroundSessionConfiguration to POST background vidoes PHP I am using NSURLSessionUploadTask to upload a image in Background using NSURLSession with backgroundSessionConfiguration.
I am sharing the below code snippets of IOS and PHP where I used to upload images[raw data] to server with PHP backend. And this file uploads in background.
       - (void)uploadImage:(NSURL*)image
       {
       NSString *urlString  =[NSString    stringWithFormat:@"www.dummy.com/upload.php"];
       NSURL *url   =[[NSURL alloc]initWithString:urlString];
       // 1
      static NSURLSession *upLoadSession = nil;
      static dispatch_once_t onceToken;
      dispatch_once(&onceToken, ^{
      NSInteger randomNumber = arc4random() % 1000000;
  NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:[NSString stringWithFormat:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession%ld",(long)randomNumber]];
  upLoadSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});

       NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
       [request setHTTPMethod:@"POST"];

       // 3
       self.uploadTask = [upLoadSession uploadTaskWithRequest:request fromFile:image];

       // 5
       [self.uploadTask resume];
        }

PHP function--
         $putdata = fopen("php://input", "r");

         /* Open a file for writing */
         $project_id = $_REQUEST["api"];
         $fp = fopen($project_id.".MOV", "w");

          /* Read the data 1 KB at a time
          and write to the file */
          while ($data = fread($putdata, 1024))
          fwrite($fp, $data);

         /* Close the streams */
         fclose($fp);
         fclose($putdata);

  >>>>3)I get response on logs on IOS from task.response-

   Connection = "keep-alive";
   "Content-Length" = 309;
   "Content-Type" = "text/html; charset=UTF-8";
   Date = "Wed, 02 Apr 2014 03:49:04 GMT";
   Server = "Apache/2.2.15 (Red Hat)";
   Via = "1.0 Proxy6-B24:3128 (squid/2.6.STABLE21)";
   "X-Cache" = "MISS from Proxy6-B24";
   "X-Cache-Lookup" = "MISS from Proxy6-B24:3128";
   "X-Powered-By" = "PHP/5.3.3";

I hope this helps someone in need.


text:
Q: How to plot the top 5 values in 'pandas.core.series.Series' in Bokeh? The first column contains names and the second column contains values.
how can I plot it using bokeh. here is a code below that plots in matlabplot
new_rf = pd.Series(rf.feature_importances_,index=x.columns).sort_values(ascending=False)

new_rf[:5]

such that x will take the variable name and y will take the value
p =figure()

p.vbar(
x = new_rf[:5].index, #here will be the feature name
top = new_rf[:5].values, #here will be feature_importance weight
)

This just gives me an empty plot

A: Issues with your code:

*

*You create new_rf but use imp_feat_rf. I assume it was just partial renaming when copying code over to SO

*vbar() requires width argument. You should see this error in the Python output when you run the code

*Working with categorical data requires setting explicit categories for ranges. More details are available at https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html. Note that x_range argument accepts lists but it does not accept pandas indices, so you have to convert the index to a list

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loop through and assign values to class properties using PropertyInfo[] I'm trying to automatically assign string values, from an array of strings, to a classes properties using a propertyinfo array.
Class Car
{
    public string wheels, doors, windows;
    PropertyInfo[] props = typeof(Car).GetProperties();
    public Car(string[] values)
    {
        int index=0;
        foreach(PropertyInfo pi in props)
        {
            pi.SetValue(pi.Name, values[index], null);
            //pi.SetValue(pi.Name, values[index]);
        }
    }
}

I get an error saying "Object does not match target type." I'm sure what I'm missing after seeing some other examples on Stack or other message boards.

A: I have created a public static class Extensions called Extensions where i have placed this code in you should be able to follow the code very easily
public static class Extensions
{
    public static void ConvertNullToStringEmpty<T>(this T clsObject) where T : class
    {
        PropertyInfo[] properties = clsObject.GetType().GetProperties();
        foreach (var info in properties)
        {
            // if a string and null, set to String.Empty
            if (info.PropertyType == typeof(string) && info.GetValue(clsObject, null) == null)
            {
                info.SetValue(clsObject, String.Empty, null);
            }
        }
    }
}


text:
Q: RabbitMQ - ensure single thread per message I have a program that uses NServiceBus for queued messages mechanism.
I see in the logs that sometimes a message is being handled twice, by different thread, though these messages are only sent once.
More so, if i enforce my service to use only 1 thread, i do not have this problem.
How can i ensure a message is only handled once?
Thank you.
Shortened log example (where you can see i get the message with chunkId 48, i finish processing everything including removing the callback, then i get the same message with chunkId 48 again, and at this point im unable to find the callback. and afterwards, an NserviceBus exception):

Risco.Rsp.RACServiceImpl.RACOutputMessageHandler [(null)] <(null)> - RACOutputMessageHandler.Handle start for ProcessType:GetClientCacheEntity with ProcessId:44eb600b-87e6-4eab-a54e-0a12480c9784 and ChunkId: 48 and TotalChunks: 57 and Topic: 23b041a3-4a62-48d1-a199-20a20e5de72a
  ....
  ....
  ...
  Risco.Rsp.RACServiceImpl.RACOutputMessageHandler [(null)] <(null)> - Sucessfuly sent result(s) for process id:44eb600b-87e6-4eab-a54e-0a12480c9784 with Process Type:GetClientCacheEntity, Client 44eb600b-87e6-4eab-a54e-0a12480c9784 (chunks 0 of 0)
  2017-01-02 11:13:13,882 [64] INFO  Risco.Rsp.RACServiceImpl.RACOutputMessageHandler [(null)] <(null)> - RACOutputMessageHandler.Handle start for ProcessType:GetClientCacheEntity with ProcessId:44eb600b-87e6-4eab-a54e-0a12480c9784 and ChunkId: 48 and TotalChunks: 57 and Topic: 23b041a3-4a62-48d1-a199-20a20e5de72a
  2017-01-02 11:13:13,888 [64] INFO  Risco.Rsp.RACServiceImpl.RACOutputMessageHandler [(null)] <(null)> - Handle(RACOutputMessage) - Unable to find callback for key 44eb600b-87e6-4eab-a54e-0a12480c9784, process id:44eb600b-87e6-4eab-a54e-0a12480c9784 with process Type:GetClientCacheEntity
  2017-01-02 11:13:13,923 [158] ERROR NServiceBus.Timeout.TimeoutManagerDeferrer [(null)] <(null)> - There was a problem deferring the message. Make sure that DisableTimeoutManager was not called for your endpoint.
  NServiceBus.Unicast.Queuing.QueueNotFoundException: Exchange for the recipient does not exist ---> RabbitMQ.Client.Exceptions.AlreadyClosedException: Already closed: The AMQP operation was interrupted: AMQP close-reason, initiated by Peer, code=404, text="NOT_FOUND - no exchange 'Risco.Rsp.Ac.AMAC.Service.Timeouts' in vhost 'AxesPlus'", classId=60, methodId=40, cause=
     at RabbitMQ.Client.Impl.ModelBase.WaitForConfirms(TimeSpan timeout, Boolean& timedOut)
     at RabbitMQ.Client.Impl.ModelBase.WaitForConfirmsOrDie(TimeSpan timeout)
     at NServiceBus.Transports.RabbitMQ.ConfirmsAwareChannel.Dispose() in c:\BuildAgent\work\ef98ad7376e3379a\src\NServiceBus.RabbitMQ\ConfirmsAwareChannel.cs:line 31
     --- End of inner exception stack trace ---
     at NServiceBus.Transports.RabbitMQ.ConfirmsAwareChannel.Dispose() in c:\BuildAgent\work\ef98ad7376e3379a\src\NServiceBus.RabbitMQ\ConfirmsAwareChannel.cs:line 47
     at NServiceBus.Transports.RabbitMQ.RabbitMqMessageSender.Send(TransportMessage message, SendOptions sendOptions) in c:\BuildAgent\work\ef98ad7376e3379a\src\NServiceBus.RabbitMQ\RabbitMqMessageSender.cs:line 27
     at NServiceBus.Timeout.TimeoutManagerDeferrer.Defer(TransportMessage message, SendOptions sendOptions) in C:\BuildAgent\work\3206e2123f54fce4\src\NServiceBus.Core\Timeout\Core\TimeoutManagerDeferrer.cs:line 42
  2017-01-02 11:13:13,936 [174] ERROR NServiceBus.Timeout.TimeoutManagerDeferrer [(null)] <(null)> - There was a problem deferring the message. Make sure that DisableTimeoutManager was not called for your endpoint.
  NServiceBus.Unicast.Queuing.QueueNotFoundException: Exchange for the recipient does not exist ---> RabbitMQ.Client.Exceptions.AlreadyClosedException: Already closed: The AMQP operation was interrupted: AMQP close-reason, initiated by Peer, code=404, text="NOT_FOUND - no exchange 'Risco.Rsp.Ac.AMAC.Service.Timeouts' in vhost 'AxesPlus'", classId=60, methodId=40, cause=
     at RabbitMQ.Client.Impl.ModelBase.WaitForConfirms(TimeSpan timeout, Boolean& timedOut)
     at RabbitMQ.Client.Impl.ModelBase.WaitForConfirmsOrDie(TimeSpan timeout)
     at NServiceBus.Transports.RabbitMQ.ConfirmsAwareChannel.Dispose() in c:\BuildAgent\work\ef98ad7376e3379a\src\NServiceBus.RabbitMQ\ConfirmsAwareChannel.cs:line 31
     --- End of inner exception stack trace ---
     at NServiceBus.Transports.RabbitMQ.ConfirmsAwareChannel.Dispose() in c:\BuildAgent\work\ef98ad7376e3379a\src\NServiceBus.RabbitMQ\ConfirmsAwareChannel.cs:line 47
     at NServiceBus.Transports.RabbitMQ.RabbitMqMessageSender.Send(TransportMessage message, SendOptions sendOptions) in c:\BuildAgent\work\ef98ad7376e3379a\src\NServiceBus.RabbitMQ\RabbitMqMessageSender.cs:line 27
     at NServiceBus.Timeout.TimeoutManagerDeferrer.Defer(TransportMessage message, SendOptions sendOptions) in C:\BuildAgent\work\3206e2123f54fce4\src\NServiceBus.Core\Timeout\Core\TimeoutManagerDeferrer.cs:line 42

A: The problem was the timeout configuration. The MessageHandler wasnt quick enough to process the message and leave the handler, so i fixed it by creating a new Task that would 'replace' the handler (meaning, at the start of the handler invoke a function that replaces the original handler)


text:
Q: Only display tweets from a single user using Twitter Streaming API I need to get the tweets from a single user in a streaming format. However, it still displays all tweets that retweet this user or are a reply to the tweets.
topic = "tweets"
accounts = ['user_id1', 'user_id2']

class TwitterStreamer():

    def __init__(self):
        pass

    def stream_tweets(self, topic, accounts):
        listener = StreamListener(topic)
        auth = tweepy.OAuthHandler(api_key, api_secret_key)
        auth.set_access_token(access_token, access_secret_token)
        stream = tweepy.Stream(auth, listener)
        stream.filter(follow=accounts)

class StreamListener(tweepy.StreamListener):

    def __init__(self, file_prefix):
        self.prefix = file_prefix

    @property
    def fetched_tweets_filename(self):
        topic
        date = datetime.datetime.now().strftime("%Y-%m-%d")
        return f"{self.prefix}_{date}.txt"

    def on_data(self, data):
        try:
            print(data)

            with open(self.fetched_tweets_filename, 'a') as tf:
                tf.write(data)
            return True
        except BaseException as e:
            print("Error on_data %s" % str(e))
        return True

    def on_exception(self, exception):
        print('exception', exception)
        stream_tweets(topic, accounts)

    def on_status(self, accounts, status):
        if status.user.id_str != accounts:
            return
        print(status.text)

def stream_tweets(topic, accounts):
    listener = StreamListener(topic)
    auth = tweepy.OAuthHandler(api_key, api_secret_key)
    auth.set_access_token(access_token, access_secret_token)
    stream = tweepy.Stream(auth, listener)
    stream.filter(track=accounts)

if __name__ == '__main__':
    twitter_streamer = TwitterStreamer()
    twitter_streamer.stream_tweets(topic, accounts)

I don't know what I'm doing wrong but I feel like the on_status command does not work at all.
Thanks for your help!

A: Don't change the parameters for on_status. Your accounts variable is a global variable and you should use it as such. Also, status.user.id_str is a str but accounts is a List[str]. You need the not ... in ... operators as opposed to !=. In other words, try out the changes below:
def on_status(self, status):
    if not status.user.id_str in accounts:
        return
    print(status.text)


text:
Q: Function isn't called properly? I have the code for caesar cipher encryption and I am trying to call the cleanup() function inside the fancy_caesar() function in order for the input keyword and message to be 'cleaned up.':
#with just .upper()
my_string = ''

def string():
    my_string = input("Enter your string: ")
    res = cleanup()
    print(res)

def cleanup(self):
    res = ''
    _char = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    lower_char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    all_char = _char + lower_char
    for ch in my_string:
        if ch in all_char:
            res += ch
    return (res.upper())

def swap(x, i, j):
    i, j = sorted((i, j))
    if i and j in range(len(x)):
        return x[:i] + x[j] + x[i+1:j] + x[i] + x[j+1:]
    else:
        return None
def inputs():
    x = input('Enter your string: ')
    i = int(input('Enter the index of the first letter: '))
    j = int(input('Enter the 2nd index of the next letter: '))
    print(swap(x, i, j))

#print(swap(x, i, j))

def fancy_caesar(message, keyword, true_false_statement):
    count = 0
    while count == 0:
        true_false_statement = str(input("Type True if you want to encrypt.\nType false if you want to decrypt: "))
        if true_false_statement == 'true' or true_false_statement == 'True' or true_false_statement == 't' or true_false_statement == 'T':
            count = count +1
        elif true_false_statement == 'false' or true_false_statement == 'False' or true_false_statement == 'F' or true_false_statement == 'f':
            count = count + 1
        else:
            print('None')
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    translated_message = ""
    keyword_index = 0

    for character in message:
        if character in alphabet:
            number = alphabet.find(character)
            if true_false_statement == 'true' or true_false_statement == 'True' or true_false_statement == 't' or true_false_statement == 'T':
                number = number + (ord(keyword[keyword_index]) - ord('a'))
            elif true_false_statement == 'false' or true_false_statement == 'False' or true_false_statement == 'F' or true_false_statement == 'f':
                number = number - (ord(keyword[keyword_index])) - ord('a')
            keyword_index += 1
            keyword_index = keyword_index % len(keyword)

            if number >= len(alphabet):
                number = number - len(alphabet)
            elif number < 0:
                number = number + len(alphabet)

            translated_message = translated_message + alphabet[number]

        else:
            translated_message = translated_message + character

    return (translated_message)

def main():
    message = input("Enter string you want to encrypt/decrypt: ")
    keyword = input('Keyword for encryption: ')
    true_false_statement = ''
    translated_message = fancy_caesar(message, keyword, true_false_statement)
    print(translated_message)

main()

I tried adding self to the cleanup() function which did not work at all since I was not given anything but blank in the ouput.
def fancy_caesar(message, keyword, true_false_statement):
    message = cleanup(message)
    keyword = cleanup(keyword)
    count = 0
    while count == 0:

I tried calling the cleanup() within the main() function and I got the same result.
This could be due to the fact that my_string isn't called in def string()
Which I ended up excluding it out of the cleanup() function in order for me to use the function for the fancy_caesar. Could I get any tips to solve these issues?
The output should result in the input string being all capatalized with no spaces or special characters which is done by the cleanup function.

A: cleanup() should take the string to be cleaned as a parameter.
def cleanup(my_string):
    res = ''
    _char = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    lower_char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    all_char = _char + lower_char
    for ch in my_string:
        if ch in all_char:
            res += ch
    return (res.upper())

Then you use it like this:
some_string = cleanup(some_string)


text:
Q: Read Bookmarks in android failing on real device I am reading the bookmarks from the browser in my app.
It is working on the Emulator in the computer, but when I am running the app on a real device it is crashing.
First of all I am filling a ListView like this:

String[] proj = new String[]{Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL};
String sel = Browser.BookmarkColumns.BOOKMARK;
myCursor = getContentResolver().query(Browser.BOOKMARKS_URI, proj, sel, null, null);

        int[] to = new int[]{R.id.txtTitle, R.id.txtUrl};
        adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.list_view_row, myCursor, proj, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        bookMarksListView = (ListView)findViewById(R.id.listViewBookMarks);
        bookMarksListView.setAdapter(adapter);

And that is working on the Emulator.
The emulator is running Android 2.3.3
And the real device is running android 4.0.4
I tought that Android 4.0.4 can run 2.3.3?
Any advice on how I should get this to work?
I want the app to be able to run on devices from 2.3.3 up to 4.0


text:
Q: Send and recieve json between android and php webservices - force close I am trying for sending data from my Android App and receiving output according to input. But application force closed as soon as i click on button.
Here is my code for java file in android:
package com.example.diary;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener
{
    private EditText value;
    private Button btn;
    private ProgressBar pb;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        value=(EditText)findViewById(R.id.editText1);
        btn=(Button)findViewById(R.id.button1);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);
        btn.setOnClickListener(this);
    }
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
                    if(value.getText().toString().length()<1){

                        // out of range
                        Toast.makeText(this, "please enter something", Toast.LENGTH_LONG).show();
                    }else{
                        pb.setVisibility(View.VISIBLE);
                        new MyAsyncTask().execute(value.getText().toString());
                    }

    }
    private class MyAsyncTask extends AsyncTask<String, Integer, Double>{

        @Override
        protected Double doInBackground(String... params) {
            // TODO Auto-generated method stub
            postData(params[0]);
            return null;
        }

        protected void onPostExecute(Double result){
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "Code Sent", Toast.LENGTH_LONG).show();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }
        public void postData(String valueIWantToSend) {

            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/remoteaccess/index.php");
            //HttpPost httppost = new HttpPost("http://192.168.1.13/educlinic/Widget/AndroidApp");
            try {

                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("myHttpData", valueIWantToSend));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                String response = httpclient.execute(httppost, responseHandler);

                //This is the response from a php application
                String reverseString = response;
                Toast.makeText(getApplicationContext(), "response" + reverseString, Toast.LENGTH_LONG).show();

                } catch (ClientProtocolException e) {
                Toast.makeText(getApplicationContext(), "CPE response " + e.toString(), Toast.LENGTH_LONG).show();
                // TODO Auto-generated catch block
                } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "IOE response " + e.toString(), Toast.LENGTH_LONG).show();
                // TODO Auto-generated catch block
                }
        }

}}

and this is code for xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:id="@+id/text1"/>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/text1"
        android:layout_below="@+id/text1"
        android:layout_marginLeft="21dp"
        android:layout_marginTop="22dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="59dp"
        android:text="Button" />

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="44dp" />

</RelativeLayout>

and this is for php:
<?php
$data = $_POST['myHttpData'];
 echo $data;
?>

Thanks in advance.

A: most probably you are getting following error:

RuntimeException: Can't create handler inside thread that has not
  called Looper.prepare()

inside postData method you are trying to show Toast's.but you are calling postData  method from non UI Thread (from doInBackground method of AsyncTask).
just remove Toast's  from postData method or use onPostExecute to access or update UI elements


text:
Q: nodemon cant reload my project: always have error EADR in use I was making a very simple node server, and run it with nodemon app.js. The server starting success, but if I make changes in the script and save it, I have an error about EADDR in use. The node process was not killed or exited. in package.json I put the delay parameter for nodemon.
My app.js (clean) it not work:
    const express = require('express')
    const app = express()
    const PORT = 5000;

    const routes = require('./Settings/routes')

    app.use(express.json())

    routes(app)

    app.listen(PORT, ()=>
        console.log('Сервер работает на порту ' + PORT)
    )

My app.js (with improvements), but it not work either
    const express = require('express')
    const app = express()
    const PORT = 5000;

    const routes = require('./Settings/routes')

    app.use(express.json())

    routes(app)

    app.listen(PORT, ()=>
        console.log('Сервер работает на порту ' + PORT)
    )

    // first create a generic "terminator"
    terminator = function(sig){
            if (typeof sig === "string") {
                    console.log('%s: Received %s - terminating sample app ...',
                        new Date(Date.now()), sig);
                    process.kill(process.pid, sig)
            }
            console.log('%s: Node server stopped.', new Date(Date.now()) );
    };

    const arrayOfSignals = [ 'SIGUSR2', 'SIGTERM']

    // then implement it for every process signal related to exit/quit
    arrayOfSignals.forEach(function(element, index, array) {
            process.on(element, function() {
                    console.log('Ожидаем перезапуск процесса')
                    terminator(element)
            });
    });

I tried with process.exit() and with process.kill()
I thought that nodemon must work from beginning...What I do not do right?
UPD: console error:

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
events.js:353
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::5000
    at Server.setupListenHandle [as _listen2] (net.js:1318:16)
    at listenInCluster (net.js:1366:12)
    at Server.listen (net.js:1452:7)
    at Function.listen (/chokoapp/backend/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/chokoapp/backend/app.js:15:5)
    at Module._compile (internal/modules/cjs/loader.js:1068:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
    at Module.load (internal/modules/cjs/loader.js:933:32)
    at Function.Module._load (internal/modules/cjs/loader.js:774:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1345:8)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...

OS: Ubuntu 18.04
Node - v  : 14.17.0

A:
Error: listen EADDRINUSE: address already in use :::5000

This means the port 5000 is already in use. So you can't use this port for your express server.
I'll suggest 2 solutions.
1. Change the port number of the express server.
const PORT = 5000; to something like const PORT = 8000;
2. Kill the process which is using port 5000.
First, you would want to know which process is using port 5000
sudo lsof -i :5000 OR in Windows CMD, netstat -ano | findstr 5000
this will list all PID listening on this port, once you have the PID you can terminate it with the following:
kill -9 {PID}

A: A simple fix that worked when I had a similar issue is to delay Nodemon's restart in package.json file:
nodemon --delay 500ms app.js

This seems to give a little time for ports to be correctly released.


text:
Q: Why loading the data as a table produces different anova results to loading data as a stack? Why loading the data as a table produces different anova results to loading data as a stack?
(1) I load the following table and obtain the anova.
31  42  14  80
42  26  25  106
84  21  19  83
26  60  36  69
14  35  44  48
16  80  28  76
29  49  80  39
32  38  76  84
45  65  15  91
30  71  82  39

> raw <- read.table("demotablenolabels.txt", sep="\t", header=FALSE)
> rawstack = stack(raw)
> rawstack$sample = rep(rownames(raw),4)
> repeated = aov(values ~ ind + sample, data=rawstack)
> summary(repeated)
            Df Sum Sq Mean Sq F value Pr(>F)
ind          3   7553  2517.7   4.036 0.0171 *
sample       9   1565   173.9   0.279 0.9751
Residuals   27  16843   623.8

(2) I save the following rawstack data to a file, load it and obtain a different anova result.
values  ind sample
31  V1  1
42  V1  2
84  V1  3
26  V1  4
14  V1  5
16  V1  6
29  V1  7
32  V1  8
45  V1  9
30  V1  10
42  V2  1
26  V2  2
21  V2  3
60  V2  4
35  V2  5
80  V2  6
49  V2  7
38  V2  8
65  V2  9
71  V2  10
14  V3  1
25  V3  2
19  V3  3
36  V3  4
44  V3  5
28  V3  6
80  V3  7
76  V3  8
15  V3  9
82  V3  10
80  V4  1
106 V4  2
83  V4  3
69  V4  4
48  V4  5
76  V4  6
39  V4  7
84  V4  8
91  V4  9
39  V4  10

> stackwithlabels <- read.table("demostackwithlabels.txt", sep="\t", header=TRUE)
> repeatedstack = aov(values ~ ind + sample, data=stackwithlabels)
> summary(repeatedstack)
            Df Sum Sq Mean Sq F value  Pr(>F)
ind          3   7553  2517.7   4.918 0.00591 **
sample       1    492   492.1   0.961 0.33356
Residuals   35  17916   511.9

(3) I convert the stackwithlabels back to a table and repeat the procedure and I get the orginal anova results (see 1).
> stackwithlabels[c(3)] <- list(NULL)
> rawwithoutlabels = unstack(stackwithlabels)
> restackwithoutlabels = stack(rawwithoutlabels)
> restackwithoutlabels$sample = rep(rownames(raw),4)
> rerepeatedstack = aov(values ~ ind + sample, data=restackwithoutlabels)
> summary(rerepeatedstack)
            Df Sum Sq Mean Sq F value Pr(>F)
ind          3   7553  2517.7   4.036 0.0171 *
sample       9   1565   173.9   0.279 0.9751
Residuals   27  16843   623.8

A: In your original data frame rawstack, sample is represented as a character vector.
str(rawstack$sample)
#  chr [1:40] "1" "2" "3" "4" "5" "6" "7" "8" "9" "10" "1" "2" "3" "4" "5" "6" "7" "8" ...

Hence, sample is interpreted as a factor in aov and has 10 - 1 = 9 degress of freedom.
summary(aov(values ~ ind + sample, data = rawstack))
#             Df Sum Sq Mean Sq F value Pr(>F)
# ind          3   7553  2517.7   4.036 0.0171 *
# sample       9   1565   173.9   0.279 0.9751
# Residuals   27  16843   623.8
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

If you write the data into a text file and read the data back into R, sample is represented as a numeric vector.
stackwithlabels <- read.table(text = capture.output(write.table(rawstack)))
str(stackwithlabels$sample)
#  int [1:40] 1 2 3 4 5 6 7 8 9 10 ...

Therefore the aovresult is different. Note that sample now has 1 degree of freedom.
summary(aov(values ~ ind + sample, data = stackwithlabels))
#             Df Sum Sq Mean Sq F value  Pr(>F)
# ind          3   7553  2517.7   4.918 0.00591 **
# sample       1    492   492.1   0.961 0.33356
# Residuals   35  17916   511.9
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


text:
Q: One static_assert makes another static_assert fail (is_default_constructible for inner class) The following code compiles:
struct Bar
{
    struct Foo
    {
        int v = 0;
    };

    // If uncomment the following line, both static assert will fail
    // static_assert(std::is_default_constructible_v<Foo>);
};

static_assert(std::is_default_constructible_v<Bar::Foo>);

But if I uncomment the first static_assert, both static_assert will fail. How can this happen?
See code in http://coliru.stacked-crooked.com/a/64e9c020056e37ed


text:
Q: How to understand the reduced cost in simplex method? I'm reading a note on the simplex method. The author mentions a quantity called "reduced cost", yet no interpretation of it is provided.
Here's the setup: $c \in \mathbb{R}^n$ is the cost vector, $A \in \mathbb{R}^{m \times n}$ is the constraint matrix in our system of $m$ equations in $n$ variables, $I \in [n]$ the index set of non-basic variables, and $I^C$ its complement. We start at a vertex $v$ of the associated polyhedron and try to move along an "interesting" direction $d$ (defined below). The reduced cost is defined as:
$$c - ((c_{I^C})^T (A_{I^C})^{-1}A))^T$$
where $c_{I^C}$ and $A_{I^C}$ are $c$ and $A$ restricted to the columns with indices in the subscripts, respectively.
I have two questions concerning this notion.

*

*What does this vector tell us?

*A bit further down, in showing that the simplex method is correct, the author argues in the following way. Let $v$ be a vertex outputted by the simplex method. Then for any $I \subseteq [n]$ "related to $v$" (defined below), and for any $i^* \in I$:
  $\bullet$ either $(c - ((c_{I^C})^T (A_{I^C})^{-1}A))^T)_{i^*} \leq 0$, or
  $\bullet$ there exists index $j$ such that $(v_{I^C})_j = 0$ and $((-A_{I^C})^{-1}A_{i^*})_j < 0$, and so $t = 0$.
The comment is that the first case corresponds to the situation where moving along the direction $d$ makes the objective function worse, and the second case the situation where doing so makes the solution infeasible.
I hope to understand the former case by reading answers to question $1$ above. As for the latter, I'm confused as to why this case can even exist. From what I understand, moving along a direction $d$ from $v$ is actually the same thing as moving along a $1$-face of the associated polyhedron. Since we start moving from a vertex with $(v_{I^C})_j = 0$, $v$ should already be a point of the polyhedron with the smallest $j$-value. So how can a direction $d$ that leads to another vertex with even smaller (in fact, negative) $j$-value exist?

I should note that the notations that I'm reading are rather unconventional. The author actually doesn't use the words "non-basic variables", but specifies $I$ (and $d$) as follows:

Given a vertex $v$ of the polyhedral set $Ax=b, x \geq 0$, and a subset $J$ of size $n - m$ of $[n]$, such that $v$ is the unique solution of the system of equations $Ax = b, x_j = 0$ for $j \in J$, we find:
  $\bullet$ a subset $I$ of $[n]$ of size $n - m$,
  $\bullet$ an index $i^* \in I$,
  $\bullet$ and a direction $d$,
such that:
  (i) $v$ is the unique solution of $Ax=b, x_{i}=0$ for $i \in I$
  (ii) $A d=0, d_{i}=0$ for $i \in I \setminus \{i^*\}, d_{i^*} > 0$
  (iii) $c^Td>0$
  (iv) the solution $v+t d$ is a feasible solution for some $t>0$.

A: The fundamental idea is that when $A\mathbf x = \mathbf b$ holds, we can express the objective function $\mathbf c^{\mathsf T} \mathbf x$ in several equivalent ways. (For example, if $x_1 + x_2 = 1$ holds, we can express $2x_1 + x_2$ as $x_1 + (x_1 + x_2) = x_1 + 1$.)
In particular, if we're at a solution where only the basic variables indexed by $B \subseteq [n]$ are nonzero, and the nonbasic variables indexed by $N = [n] - B$ are all zero, it makes sense to express the objective function in terms of the nonbasic variables only. That will let us see which nonbasic variables are good to bring into the basis. To do this, solve $A\mathbf x = \mathbf b$ for $\mathbf x_B$ in terms of $\mathbf x_N$:
$$
   A \mathbf x = \mathbf b \implies A_B \mathbf x_B + A_N \mathbf x_N = \mathbf b \implies \mathbf x_B = A_B^{-1}(\mathbf b - A_N \mathbf x_N).
$$
Then substitute this into the objective function
$$
   \mathbf c^{\mathsf T}\mathbf x = \mathbf c_B^{\mathsf T} \mathbf x_B + \mathbf c_N^{\mathsf T} \mathbf x_N = \mathbf c_B^{\mathsf T}A_B^{-1}(\mathbf b - A_N \mathbf x_N) + \mathbf c_N^{\mathsf T} \mathbf x_N.
$$
This has a constant component $\mathbf c_B^{\mathsf T}A_B^{-1}\mathbf b$ (which is the value of the objective function at the current basic solution) and a variable component $(\mathbf c_N^{\mathsf T} - \mathbf c_B^{\mathsf T}A_B^{-1}A_N) \mathbf x_N$. We might as well extend the variable component to $(\mathbf c^{\mathsf T} - \mathbf c_B^{\mathsf T}A_B^{-1}A) \mathbf x$, which includes all variables (the basic variables are included with coefficient $0$).
The coefficient vector of $\mathbf x$ in the variable component is exactly the reduced cost. It is the cost vector, re-expressed in terms of the nonbasic variables only.

The vector $\mathbf v$ "related to $N$" is the basic solution with basic variables $B$: it has $\mathbf v_B = A_B^{-1} \mathbf b$ and $\mathbf v_N = \mathbf 0$.
We've expressed the cost function already as $\mathbf c_B^{\mathsf T}A_B^{-1}\mathbf b +  (\mathbf c^{\mathsf T} - \mathbf c_B^{\mathsf T}A_B^{-1}A) \mathbf x$. Let $\mathbf r^{\mathsf T} = \mathbf c^{\mathsf T} - \mathbf c_B^{\mathsf T}A_B^{-1}A$ be the reduced cost, noting that $\mathbf r_B = \mathbf 0$. We spot that $\mathbf c_B^{\mathsf T}A_B^{-1}\mathbf b = \mathbf c_B^{\mathsf T} \mathbf v_B = \mathbf c^{\mathsf T} \mathbf v$, the objective value at $\mathbf v$.
So we can write the objective function at any point $\mathbf x$ as
$$\mathbf c^{\mathsf T} \mathbf x = \mathbf c^{\mathsf T} \mathbf v + \mathbf r^{\mathsf T} \mathbf x.$$ In particular:

*

*Suppose $\mathbf r \le \mathbf 0$. Then because $\mathbf x \ge \mathbf 0$ for every feasible $\mathbf x$, we have $\mathbf r^{\mathsf T} \mathbf x \le 0$, so $\mathbf c^{\mathsf T} \mathbf x \le \mathbf c^{\mathsf T} \mathbf v$. In other words, $\mathbf v$ is optimal.

*Suppose $r_j > 0$ for some $j \in N$. If we can pivot to a solution $\mathbf x$ where $x_j > 0$, but still $x_k = 0$ for all $k \in N - \{j\}$, then its objective value will be $\mathbf c^{\mathsf T} \mathbf v + \mathbf r^{\mathsf T} \mathbf x = \mathbf c^{\mathsf T} \mathbf v + r_j x_j > \mathbf c^{\mathsf T} \mathbf v$. In other words, the objective value will increase.


text:
Q: Setting a TImage's Parent I have a class
THexMap = Class(TScrollingWinControl)
  private
      FCanvas    :timage;    // the canvas to draw on.

Dureing the constructor I create  TImage Like so.
Constructor THexMap.Create(AOwner: Tcomponent);
    begin
      inherited Create(AOwner);

      FCanvas := timage.Create(self);
      FCanvas.Visible := true;

      { Set intial property values for component }

      MakeSolidMap;

    end;

If i try to set the parent here like so
FCanvas.parent := THexMap;

I get Incompatible types: TWinControl and Class of ThexMap
How do i make it so this image shows up inside the THexMap?
SOME MORE INFO THAT MIGHT HELP...
If i set the create like so
FCanvas := TImage.Create(AOwner);
The TImage is on the forum, but no image shows up. If i click on the component in the Object Inspector and then click on the property Picture, the correct image will show in the picture Editor.
THE REDRAW..
procedure THexMap.WndProc(var Message: TMessage);
const
  DISCARD_CURRENT_ORIGIN = nil;
var
  R : TRect;
  PS : PAINTSTRUCT;
begin
  if Message.Msg = WM_PAINT then
  begin
    if GetUpdateRect( Handle, nil, false ) then
    begin
      BeginPaint( Handle, PS );
      try
        R := PS.rcPaint;
        bitblt(fCanvas.Canvas.Handle, R.Left, R.Top, R.Width, R.Height, TempMap.Canvas.Handle, R.Left+FOffset.X, R.Top+FOffset.Y, SRCCOPY);
      finally
        EndPaint( Handle, PS );
      end;
    end
    else
      inherited;
  end
  else
    inherited;

end;

A: Parent is an instance of TWinConrol, not class type
(e.g. this boy's parent is John Doe, not mankind)
So you have to write:
FCanvas := timage.Create(self);
FCanvas.Parent := Self;

Visible = true is not needed here


text:
Q: Is it possible to use the relative pronoun "which" to refer to people? All of the grammar books I have consulted indicate that who(m)/that are the only relative pronouns to be used with people.
I thought that you could use "which" when you point out a specific person in a group.  Is this not acceptable/ is there a situation where one could use "which" to refer to a person directly?
A quick google search for "the man which" revealed several bible passages with this combination, but nothing in the line of grammar explanations.

A: Purdue's Online Writing Lab provides this chart when talking about relative pronouns:

Note that people are referred to only by the relative pronouns who and that (the latter in informal English only), while things and concepts are referred to by which.
Another website for English language help, TutorPal.com, explains that the use of "which" to refer to people is one of the ways that the King James Bible's English differs from modern English:

Use of relative pronouns: In Middle English, the language of King James, we find "which" in many instances where we could expect "who." For example, "Our father which art in heaven."

So to answer your question, using which to refer to people used to be acceptable, but now it's not.
You might be interested in reading this essay, which summarizes the historical development and modern usage of relative pronouns.

A: With question words it is acceptable to use which for people - Practical English Usage (Michael Swan):
622 which, what and who: question words
Which/What people have influenced you most in your life?
...
We prefer which when we have a limited number of choices in mind.
...
Before nouns, which and what can be used to ask questions about both things
and people.
...
Which teacher do you like best?


text:
Q: How to count checked checkbox with Javascript? I would like to count the checkboxes that are checked and display the count in the Div.
Here is my HTML :
<form name="liste_figurine" method="post">

<input type="checkbox" id="radio-1" class="z" name="chck1[]" onclick="updateCount()" />
<input type="checkbox" id="radio-2" class="z" name="chck2[]" onclick="updateCount()" />

</form>

Here is my JS :
function updateCount {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};

Here is an exemple : https://jsfiddle.net/r3todbs6/3/
Sorry, I'm not really used to JS... What is wrong with my code ?

Finally, it's working but I have one last issue : the onclick must contain 2 functions and I don't manage to make them working together.
Now this function works, alone : onclick="updateCount()"
This other function works also, alone : onclick="document.getElementById(\'radio-'.$ligne['id'].'-2\').checked = false"
But these two functions doesn't work, together :
onclick="updateCount(); fx2(document.getElementById(\'radio-'.$ligne['id'].'-1\').checked = false);"
What is wrong with the third proposition ? Is it a syntax error ?

A: window.updateCount = function() {
    var x = $(".z:checked").length;
    document.getElementById("y").innerHTML = x;
};

https://jsfiddle.net/73yfczcj/
try this. you have to use jquery in javascript setting.

A: Use length
function updateCount(){
    var x = $("input:checked").length;
    $("#y").html(x);
};

A: There are three issues for your Fiddle code:

*

*As others have mentioned, it should be length, not size().

*You should change the JavaScript setting -> Load type to "No wrap - in ". Otherwise, updateCount is not defined in global scope.

*You need to configure Fiddle to use jQuery if you use your original code.

A working example: https://jsfiddle.net/c5ez4w7y/

A: function updateCount {
    var x = document.querySelector('.z:checked').length;
    document.getElementById("y").innerHTML = x;
};

try this fuction if you don't want to use jQuery

A: The answer provided by kangsu is the best answer but here is how I did it.

var form = document.getElementById('form');
var checkBoxes = $(form).children('.checkbox');
var count = 0;

var divBoxesChecked = document.getElementById('boxesChecked');
divBoxesChecked.innerHTML = 0;

$(checkBoxes).on('click', function() {
  $.each(checkBoxes, function(i) {
    if (checkBoxes[i].checked) {
      count++;
    }
  });
  console.log(count);
  divBoxesChecked.innerHTML = count;
  count = 0;
});

<form id="form" method="post">

  <input type="checkbox" id="box_01" class="checkbox" name="box_01" />
  Box 1

  <input type="checkbox" id="box_02" class="checkbox" name="box_02" />
  Box 2

  <input type="checkbox" id="box_03" class="checkbox" name="box_03" />
  Box 3

</form>

Basically, every time one of the boxes is clicked it counts how many boxes are checked in total and prints that out to the div and the console, then it resets the counter to zero since it re-counts all of the checked boxes every time you click on one.


text:
Q: 5v power supply using 7805 I want to create a 5v power supply design to provide power to my PIC18F4550, for that I am using 7805 so it will give the required 5v as output.
I searched online and this is the diagram I found:-

It shows that I have to connect 2 capacitors with the 7805.
I am using a 9V battery as input power source to 7805.
In the datasheet the value of Ci and Co is given 0.33uF and 0.1uF respectively, but my friend used capacitors of value 470uF and 100uF respectively and he is getting correct output without any error.
My questions:-

*

*Can I use my friends(using Ci and Co is given 470uF and 100uF) choice of capacitor for my 5v power supply to microcontroller without any adverse effect?
If yes, then why is some other values given in datasheet.
OR
Is it really possible to use the 7805 without any capacitors at all if I am using a DC 9v battery as input?

*Is there some formula for calculation which can be done to determine the values of the capacitors? If yes, where I can find it?
I know this question has been asked a lot of times, but I am having a hard time understanding the answers provided on other questions. Please help me understand this basic concept.
Thanks.

A:
why is some other values given in datasheet.

The datasheet is giving minimum values which give the performance claimed in the datasheet. (Some datasheet values may be given with other values for \$C_i\$ and \$C_o\$, and it will tell you this.)
If you use smaller caps, ripple and noise will be higher than specified.
With a standard regulator like the 7805, there is no performance penalty to using larger caps than specified, other than the slower rise time on the rails. Some devices you may wish to power from the regulator won't be happy with a slowly-rising power rail, while others don't much care.
Obviously using caps larger than necessary has costs. Bottom line, you should engineer your cap values, not guess at them.
LDO type regulators generally will actually fail if you guess incorrectly on the cap type and value.

Is it really possible to use the 7805 without any capacitors at all if I am using a DC 9v battery as input?

You can get away with it, but whether it succeeds or not depends on conditions surrounding the regulator.
In your particular case, \$C_i\$ is cheap insurance against oscillation due to the input supply and ground impedances. A 9V battery has a fairly high impedance due to the small cell size and the number of them in series. This opens you up to ground bounce getting back to the input, which effectively closes a feedback loop on the system, which is a prerequisite for oscillation.
Other systems might not need \$C_i\$, such as because the regulator is connected to a nearby unregulated supply with its own output cap. That cap may suffice to decouple the regulator's input, too.
The story for \$C_o\$ is similar: if there is already a nearby downstream cap, you might not need a separate one for the regulator.
Bottom line, test under all the conditions you will need the system to operate under. Even when one of these caps isn't strictly required, it may improve performance.

Is there some formula for calculation which can be done to determine the values of the capacitors? If yes, where I can find it?

Any electronics text book. The Art of Electronics third edition just became available a few days ago. It certainly gives equations for capacitor voltage vs current and such.


text:
Q: CCEaseIn etc inside CCSequence How do you exactly use easing inside CCSequence?
Related to Using CCEaseOut together with CCSequence?

A: here is an example. This brings back my mapNode to the left border, for example when a LHS menu is popped out. Move duration and acceleration are computed as a function of the expected displacement :
- (void)setLeftClamp:(float)leftClamp {

    _leftClamp = leftClamp;

    CGPoint currentPosition = self.mapNode.position;
    if (currentPosition.x > self.maxX) {
        // ease right back in position
        CGPoint delta         = ccp (self.maxX - currentPosition.x, 0);
        id      move          = [CCMoveBy actionWithDuration:[self moveDuration:delta] position:delta];
        id      ease          = [CCEaseIn actionWithAction:move rate:[self moveAcceleration:delta]];
        id      delay         = [CCDelayTime actionWithDuration:.1f];
        id      easeAndCenter = [CCSequence actions:ease, delay, [CCCallFunc actionWithTarget:self selector:@selector(onMoveComplete)], nil];
        [self.mapNode runAction:easeAndCenter];

        targetMapLocation_ = ccpAdd(self.mapNode.position, delta);
        mapDisplacement_   = delta;
        isMapMoving_       = YES;

    }

}


text: Q: C++ DLL for Excel not able to work on other computer I built a C++ DLL, to be called from Excel-VBA, using Visual Studio 2017.  It works well on my computer with the DLL built by debug mode. When I try to use it on another computer without VS, it gives a run time error 53 - file not found. After some research on the web, I have tried to built the DLL under release mode. Now I'm getting run time error 53 - file not found on my pc with VS. The error message on the other computer is run time 'error 453 - cannot find DLL entry point'.


text:
Q: Android Tabcontent overlap with tab Hi I need some help with Tab. Got some layout advice need to consult.
My current tabcontent seems to overlap with my tab. Anyway to go about preventing that?

main.xml
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:id="@+id/LinearLayout01"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical">

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <TabWidget
                android:id="@android:id/tabs"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

        </FrameLayout>
    </LinearLayout>
</TabHost>

A: Well you have put the tabs into your tabcontent. The correct layout is this
<LinearLayout>
    <TabWidget />
    <FrameLayout />
</LinearLayout>

I guess you are following this tutorial. The first XML layout there is what yours should look like.


text:
Q: How to configure yii2 advance online hosting Please  I have a website I just finished developing using yii2 advance.
Please I will like to know how to arrange the files and folders so that if someone should type domain.com it will display d index page instead of have to rout to domin.com/frontend/web to view the page.
Thanks in advance.


text:
Q: Bash: How to shorten long lines of a log file whilst keeping a fixed number of characters from beginning and end of each line? I have a long log-file (ASCII text), which contains lines with different lengths going from some characters to many thousands characters. How can I shorten each long line with bash/linux commands?
Is it possible to replace the cutted text with something like "... N characters removed ..."?
My goal is to keep all lines with a length up to 100 characters untouched.
For all lines > 100 characters keep 40 characters from beginning, 40 characters from end, and insert "... N characters removed ..." in the middle where characters has been cut out (N replaced with number of removed characters).
Is this too complicated to do it with bash/linux commands?
Any help would be appreciated.

A: You can do this with awk
awk '
(length > 100) {
    l=length
    $0 = substr($0,0,40) "..."l-80" Characters Removed..." substr($0,l-39)
}1' ./infile

Proof of Concept
$ cat ./infile
|- These are the first 40 characters --|0123456789012345678901234567890|-- These are the last 40 characters --|
12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
9012345678901234567890
2345678901234567890
12345678901234567asdfasd9as98jf-a9jfa9uhf0sd9uhfas0dfadfa890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
123456789012345678901234567890123456789012345678901234567aisfjds9dafa908sfj9asdjf9asdf89012345678901234567890123456789012345678901234567890
12345678901234567890123456789012345678901234567890123456789012345678901234567890123456asf9jasf-asjf0as8789012345678901234567890

$ awk '
     (length > 100) {
        l=length
        $0 = substr($0,0,40) "..."l-80" Characters Removed..." substr($0,l-39)
    }1' ./infile
|- These are the first 40 characters --|...31 Characters Removed...|-- These are the last 40 characters --|
1234567890123456789012345678901234567890...30 Characters Removed...1234567890123456789012345678901234567890
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890
9012345678901234567890
2345678901234567890
12345678901234567asdfasd9as98jf-a9jfa9uh...70 Characters Removed...1234567890123456789012345678901234567890
1234567890123456789012345678901234567890...59 Characters Removed...1234567890123456789012345678901234567890
1234567890123456789012345678901234567890...47 Characters Removed...sf9jasf-asjf0as8789012345678901234567890

A: awk to the rescue :-)
I believe your problem is: when you do something like cat ... | cut -c..., how can you append something to this?
Let me give you an example: I have a file, test.txt, which looks as follows:
Prompt>cat test.txt
version = 1.203
RAM/ABC/INDIA
RAJ/XYZ/DELHI
VIRAJ/FDS/

I can show different parts of lines, one after the other, like this:
Prompt>cat test.txt | awk '{print substr($1,1,1) "..." substr($1,3,1)}'
// print the first character, some constant string in between, and the third character

This gives following result:
v...r
R...M
R...J
V...R

So, putting all things next to each other in an awk script, like {print <beginning> <middle> <end>} gets the job done.


text:
Q: Updating Android app properly? Help! I updated my android application on the market. This update included a change in the databaseHelper file where I put in more data and tables. Normally, when debugging, I would have to uninstall and reinstall the app because it doesn't see the new values in the database. Now, it's doing the same thing on the market.
Why is this happening? How can I fix this? Is it possible to 'rollback' the changes to the app?

A: You can't roll it back - there is no history in the market. You can publish your previous version again (which, of course, will cause database mayhem again).
As for upgrading databases - You should be using SQLiteOpenHelper to manage your database. That way, you can have a version number, which will be used to call onUpgrade() when necessary at which point you can use ALTER TABLE to add new columns (or create new tables altogether). The notepad example demonstrates all this.


text:
Q: Bisection method with geometric mean The bisection method is a well-known method for root-finding. Given a continuous function $f$ and an interval $[a,b]$ where $f(a)$ and $f(b)$ have opposite signs, a root can be guaranteed to be in $(a,b)$. The bisection method computes $f(\frac{a+b}2)$ and iteratively refines the interval based on its sign. The main advantage with this is the simplicity and guaranteed linear convergence since on every iteration the error could be said to halve.
In floating point arithmetic, however, the float which is directly in between $a$ and $b$ is not given by $\frac{a+b}2$ but rather $\sqrt{ab}$, assuming $a$ and $b$ are both positive. For this reason I wonder if it is actually advantageous to use the geometric mean instead of the arithmetic mean. Similar to the arithmetic bisection method, the geometric bisection method halves the error of the $\log(a)$ and $\log(b)$ on every step, so linear convergence is guaranteed in a similar manner.
Interestingly, the arithmetic mean halves the absolute error, while the geometric mean halves the relative error.
Q: Should we be using the arithmetic or geometric (or possibly other) mean when using bisection with floats? What are the advantages and disadvantages of each?

A: It would seem to be the case, at least as far as I have tested, that the geometric mean is quite useful when $a$ and $b$ differ greatly in magnitude.
Advantages of geometric means:
In double precision, the extreme cases are roughly $10^{\pm308}$. Supposing we are trying to reach $x=2$ to machine precision using these two initial points:

*

*arithmetic means would require roughly 1000 iterations.

*geometric means would require roughly 60 iterations.

This means the worst case scenario for geometric means is far better.
The less extreme scenario (such as with a bracket like $[1,6]$ for $x=2$) has arithmetic means requiring roughly 50 iterations to reach, but the same is true for geometric means as well. This may be justified by noting that the difference of the arithmetic and geometric means
$$\frac{a+b}2-\sqrt{ab}=\frac{(\sqrt a-\sqrt b)^2}2=\frac{(a-b)^2}{2(\sqrt a+\sqrt b)^2}\sim\frac{(a-b)^2}{8x}$$
decays quickly as the interval shrinks.
Disadvantages of geometric means:

*

*Some edge case handling becomes necessary (different signs or $0$ is one of the points), meaning more complicated code.

*May converge slower than expected if one point is very close to $0$ and the other is not (e.g. $[a,b]=[10^{-308},2]$ with a root at $x=1.3$) so that the geometric mean does not appear to be initially closing in on the root as rapidly as the arithmetic mean.

*Higher arithmetic cost per iteration because one square root (or two to avoid under-/over-flow using $\sqrt x\cdot\sqrt y$) must be computed.

Possible fixes:

*

*Handling cases when points are not of the same sign can be done by using the smallest positive float multiplied by the sign of the larger number.

*A mixture of arithmetic and geometric means should recover initially expected behavior.

*

*The arithmetic-geometric mean may be interesting to use.

*A simpler solution would be to alternate between arithmetic and geometric means.

Update 10/26:
As I've explained here, after one has $x/y\in(0.5,2)$, a swap from geometric mean to arithmetic mean should be used. This conclusion is drawn based on the structure of the double.
Update 11/03:
It should actually make more sense to use $(3x+y)/4$ when the geometric mean fails to significantly reduce the absolute error, where $|x|<|y|$. Intuitively this is roughly equivalent to two iterations of arithmetic means. In the worst case, this may cause one or two extra iterations of arithmetic means when one iteration of bisection would have sufficed. This is particularly of importance in relation to hybrid root-finding methods, where reducing the absolute error more readily improves the interpolation.


text:
Q: Firebase permission for storage function I'm trying to trigger my function on specific path in storage bucket using:
exports.generateThumbnail = functions.storage.bucket("users").object().onChange(event => {});

When I try to deploy it, console shows:
functions[generateThumbnail]: Deploy Error: Insufficient permissions to (re)configure a trigger (permission denied for bucket users). Please, give owner permissions to the editor role of the bucket and try again.

How can I do that? Do I nedd to setup IAM or bucket permission or maybe something else?

A: Looks like the issue is that you're trying to reference a bucket named "users" rather than filtering on an object prefix.
What you want is:
exports.generateThumbnail = functions.storage.object().onChange(event => {
  if (object.name.match(/users\//)) {
    // do whatever you want in the filtered expression!
  }
});

Eventually we want to make prefix filtering available so you can do object("users"), but currently you have to filter in your function like above.


text:
Q: Only show slider if one or more related items exist I have a portfolio on a WordPress theme and on the single portfolio page it has a slider of related portfolio items. Well it's a cool feature but it shows the slider even if no related items match that particular portfolio item.
Here is my template where I display the slider:

    <?php gbx_related_portfolio($post->ID); ?>

Here are my functions I am using to create my slider:
function get_related_portfolio($post_id) {
$item_cats = get_the_terms($post_id, 'portfolio_category');
if ($item_cats) {
    foreach ($item_cats as $item_cat) $item_array[] = $item_cat->term_id;
}

$args = wp_parse_args($args, array(
    'showposts' => 5,
    'post__not_in' => array($post_id),
    'ignore_sticky_posts' => 0,
    'post_type' => 'portfolio',
    'tax_query' => array(
        array(
            'taxonomy' => 'portfolio_category',
            'field' => 'id',
            'terms' => $item_array
        )
    ),
    'orderby' => 'rand'
));

$query = new WP_Query($args);
return $query;
}

AND
function gbx_related_portfolio($post_id) {
?>

Related Items

    <div class="iosslider recentportfolio-carousel <?php echo 'recentportfolio-carousel'.$randomid; ?>">

<?php
            $recentPortfolio = get_related_portfolio($post_id);

            if ($recentPortfolio->have_posts()) {
                while ( $recentPortfolio->have_posts() ) { $recentPortfolio->the_post(); global $post; ?>

                            <a href="<?php the_permalink(); ?>">
                                <?php
                                if('' != get_the_post_thumbnail())
                                    $full_image = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
                                else
                                    $full_image = get_template_directory_uri().'/images/thumbnail_placeholder.png';

                                echo 'ID)).'"/>';
                                ?>

                                    <a class="icon" href="<?php the_permalink(); ?>">
                                    <a class="icon swipebox" href="<?php echo $full_image; ?>" title="<?php echo get_the_title($post->ID); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo get_the_date('F j, Y'); ?>

                                <a href="#" class="like <?php echo gbx_get_like_status($post->ID); ?>" title="<?php echo gbx_get_like_title($post->ID); ?>" data_action="likepost" data_postid="<?php echo $post->ID; ?>" data_nonce="<?php echo wp_create_nonce("gbx_like_nonce"); ?>">

                                    <?php echo gbx_get_likecount($post->ID); ?>

                                <?php echo gbx_get_viewcount($post->ID); ?>

            <?php } } ?>

<?php
}

A: Your code is quite mingled with a lot of syntax errors. I have put all your code in one function and rearrange it and fixed the errors. I'm not 100% sure about this part though, it is untested
 function gbx_related_portfolio() {
wp_reset_postdata();
global $post;
$orig_post = $post;
if ( 'portfolio' == get_post_type() ) {
$tags = wp_get_post_terms($post->ID, 'portfolio_category');
if ($tags) {
    $tag_ids = array();

    foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
    $args=array(
        'tax_query' => array(
        array(
            'taxonomy'  => 'portfolio_category',
            'terms'     => $tag_ids,
            'operator'  => 'IN'
        )
    ),
    'post__not_in'          => array( $post->ID ),
    'posts_per_page'        => 5,
    'ignore_sticky_posts'   => 0
    );
    $my_query = new wp_query( $args );

    if( $my_query->have_posts() ) { ?>

Related Items

    <div class="iosslider recentportfolio-carousel <?php echo 'recentportfolio-carousel'.$randomid; ?>">

        <?php  while ( $my_query->have_posts() ) : $my_query->the_post(); ?>

                            <a href="<?php the_permalink(); ?>">
                                <?php
                                if('' != get_the_post_thumbnail())
                                    $full_image = wp_get_attachment_url(get_post_thumbnail_id($post->ID));
                                else
                                    $full_image = get_template_directory_uri().'/images/thumbnail_placeholder.png';

                                ?>

                                    <a class="icon" href="<?php the_permalink(); ?>">
                                    <a class="icon swipebox" href="<?php echo $full_image; ?>" title="<?php echo get_the_title($post->ID); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo get_the_date('F j, Y'); ?>

                                <a href="#" class="like <?php echo gbx_get_like_status($post->ID); ?>" title="<?php echo gbx_get_like_title($post->ID); ?>" data_action="likepost" data_postid="<?php echo $post->ID; ?>" data_nonce="<?php echo wp_create_nonce("gbx_like_nonce"); ?>">

                                    <?php echo gbx_get_likecount($post->ID); ?>

                                <?php echo gbx_get_viewcount($post->ID); ?>

            <?php endwhile; ?>

<?php
}
}
}
$post = $orig_post;
wp_reset_query();
}

Just call it as follows

    <?php gbx_related_portfolio(); ?>


text:
Q: Edit Existing Github project in Visual Studios I have cloned my team's github repository using Visual Studios 2013 team explorer. My team is using many different IDEs to work on this project (gvim, xcode, eclipse with c++ extensions, etc). The project includes an "includes" folder (for .h files), a "src" folder (for .cpp files), a "tests" folder for our unit tests, an "obj" folder (contains something called main.o), and two library folders "UnitTest++" and "SDL2".
My question is how can I view all these folders as they exist in our github repository and edit the files within these folders in Visual Studios 2013 (and if possible compile them with visual studios)?


text:
Q: Notification Widget in yosemite os I want to create a notification widget (Using todays extension) which will have a dynamic layout.
Example my layout will be like a table with two rows and 3 column, which can change to a table with 3 rows and 5 column in the future.
Can we do this using HTML, JavaScript and CSS.
Please suggest a way to do so..
I don't wont to change the installable again, it will be given to user once and the layout can be changed dynamically...
I am using dashcode.


text:
Q: If a car is recognized take a picture Run this code for Python and OpenCv. What i want to do, is to save in my dataset/test all the images of all the cars that the tool is detecting.
Run my code with
python3 car_detection y0d$ python3 build_car_dataset.py -c cars.xml -o dataset/test

So when i detect the face and put the rectangle on the face, i created an if function that is saying that if the face is recognized and has the rectangle on the image, then please save the pic of that face to my desired output
if rects:
            p = os.path.sep.join([args["output"], "{}.png".format(str(total).zfill(5))])
            cv2.imwrite(p, orig)
            total += 1

So the error i got is: ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() What should i do? Thank you in advance!
My full code is:
# USAGE
# python3 build_car_dataset.py --cascade haarcascade_frontalface_default.xml --output dataset/test
#  python3 build_face_dataset.py -c haarcascade_licence_plate_rus_16stages_original.xml -o dataset/test
#python3 build_face_dataset.py -c haarcascade_licence_plate_rus_16stages_original.xml -o dataset/test
#python3 build_car_dataset.py -c cars.xml -o dataset/test
from imutils.video import VideoStream
import argparse, imutils, time, cv2, os

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--cascade", required=True,
    help = "path to where the face cascade resides")
ap.add_argument("-o", "--output", required=True,
    help="path to output directory")
args = vars(ap.parse_args())

# load OpenCV's Haar cascade for face detection from disk
detector = cv2.CascadeClassifier(args["cascade"])

# initialize the video stream, allow the camera sensor to warm up and initialize the total number of example faces written to disk  thus far
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
# vs = VideoStream(usePiCamera=True).start()
time.sleep(2.0)
total = 0
# loop over the frames from the video stream
while True:
    # grab the frame from the threaded video stream, clone it, (just in case we want to write it to disk), and then resize the frame
    # so we can apply face detection faster
    frame = vs.read()
    orig = frame.copy()
    frame = imutils.resize(frame, width=400)
    # detect faces in the grayscale frame
    rects = detector.detectMultiScale(
        cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY), scaleFactor=1.1,
        minNeighbors=5, minSize=(30, 30))
    # loop over the face detections and draw them on the frame
    for (x, y, w, h) in rects:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        if rects:
            p = os.path.sep.join([args["output"], "{}.png".format(str(total).zfill(5))])
            cv2.imwrite(p, orig)
            total += 1

    # show the output frame
    cv2.imshow("Frame", frame)

    key = cv2.waitKey(1) & 0xFF

    # if the `q` key was pressed, break from the loop
    if key == ord("q"):
        break
# do a bit of cleanup
print("[INFO] {} face images stored".format(total))
print("[INFO] cleaning up...")
cv2.destroyAllWindows()
vs.stop()

A: Replace:
if rects:

with:
if rects is not None :

or with:
if rects != None :

and you'll be golden =)
I mean, you still won't be able to detect cars, but at least the error will go away. For the car detection I'd recommend to use CNN (convolution neural networks), google for "YOLO CNN" or "SSD CNN" -- there are plenty of already existing projects that detect cars, you may easily give yourself a good head start.

A: Let's say rects = [[1, 2, 3, 4], [3,4, 5, 6]]
for (x, y, w, h) in rects:
    print("I got here:", x, y, w, h)

would print:
I got here: 1 2 3 4
I got here: 3 4 5 6

But if rects = None, you'd get the error, 'NoneType' object is not iterable
If rects = [] you get no output and nothing inside the loop runs.
Basically what I'm saying is that because your if rects code is inside a loop that is looping through rects, you are already guaranteed that rects has info in it since your code needed rects to be a non-empty iterable to get that far.
What you probably really want to do is check if rects prior to looping over it. To be pythonic, we'll ask forgiveness rather than permission:
rects = None
try:
    for (x, y, w, h) in rects:
        print("I got here:", x, y, w, h)
except TypeError:
    print("no rects")

# no rects

Note that your error has little to do with the majority of your code. Be sure to try to reduce your problem to the smallest possible reproducible example that has the same issue. Often by doing so, it helps solve the issue.


text:
Q: T-SQL Group by / Order by + SQL Server Reporting Service Parameters select
    Users.UserId
   ,Users.FirstName + ' ' + Users.LastName AS
   ,[Month]
   ,[Day]
   ,x.[Przych]
   ,x.[Wych]
   ,x.[Przych] + [Wych] as [Ogół]
from
   (select
       CaseActionHistory.UserId
       ,month(CaseActionHistory.DateAdded) AS [Month]
       ,day(CaseActionHistory.DateAdded) AS [Day]
       ,sum(case when CaseActionHistory.CaseActionDefinitionId in (14,15,16) then 1 else 0 end) AS [Przych]
      ,sum(case when CaseActionHistory.CaseActionDefinitionId in (20,21,22,23,26) then 1 else 0 end) AS [Wych]
    from CaseActionHistory
    where CaseActionHistory.CaseActionDefinitionId in (14,15,16,20,21,22,23,26)
    group by month(CaseActionHistory.DateAdded),day(CaseActionHistory.DateAdded), CaseActionHistory.UserId
    order by month(CaseActionHistory.DateAdded) DESC,day(CaseActionHistory.DateAdded) DESC
OFFSET 0 rows
) AS x
inner join Users on x.UserId = Users.UserId

I'm trying to run out something out of this. My problem is: the results of such query are displayed like this:
User    Month    Day    X
User1     7       31    6
User2     7       31    7
User3     7       31    9
User1     7       30    8
User2     7       30    7
User3     7       30    8
User4     7       31    10
User5     7       31    20
User6     7       31    23
User4     7       30    5
User5     7       30    7
User6     7       30    65

So in fact few Users are grouped into small groups which are displayed first, then 2nd group, etc. so I suppose there's a problem either with group by or order by.
As an addition I'd like to ask a question concerning parameters in SQL Server. Out of code below I'd like to set up 3 parameters:
User
Month
Day

But my problem is that when I set up details of parameter and I run it some values are multiplied. Same user is multiplied few times, same month, same day etc. also report itself is not reacting on any kind of change within parameters.

The main idea of a report is to show the number of phone calls done by every employee, each day, every month and to be able to compare results with others.
Calls are splitted into: outgoing and incoming. After every phone call employee adds to system an information regarding what phone call it was and what they managed to do during this phone call.
So in fact we are working on 2 tables in this case:
CaseActionHistory and Users
So the plan was to show the number of phone calls (incoming, outgoing and sum of those) for every day for every person.
Since CaseActionHistory table consits only ID of User which done the action and I'd like to show the person's name (which is placed in Users table obviously).
The problem is that the report should show around 20 Users one by one, so for 31st of June 20 Users one by one, for 30th 20 Users one by one etc, but it shows like 5 Users for 31st, then same Users for 30th, then next 5 Users for 31st etc (link to image showing the situation below)
http://img801.imageshack.us/img801/2088/7blu.png
Columns are:
UserId (to be replaced with UserName) Day Month Incming Outgoing Sum
The rows on the bottom for 31st July should be on the top of the list but they are not.

A: Welcome to stack overflow.  A few things:

*

*If your data is 'multiplying' may you just do a 'distinct' in your main select statement and determine if it is not your dataset repeating?

*How are you applying parameters?  They should be predicates and have nothing to do with groupings except indirectly.  You may limit a set by a parameter but it will not affect your grouping directly, generally speaking.

*What do you want to group by?  Year, Month, (detail)?

SSRS starts out with a data connection (Data Source).  You then apply a Data Set which is a query or proc.  Which you have a query.  You can apply a predicate to the main dataset with a 'where User = @User' or 'where User in (@User)'.  The parameter will automatically be created if you do this in your dataset first with the '@(something)' creating a text parameter of said name.  You see the Built In Fields, Parameters, Images, Data Sources, DataSets in the 'Report Data' view which you will use constantly in SSRS creation with 'Business Intelligence Development Studio'.
So a simple example would be that you want to add a group for the Day to your '(Details)' row.  If you create a 'Table' element from the 'Toolbox' it will only have a single row called Details.  Fill it with your X value and user.  In the 'Design' surface at the bottom you will see 'Row Groups'.  Right click on your 'Details' row and choose add parent group.  Group by 'Day' check 'Add Group Header'.  You now have another row that will be grouping by Day.  You can repeat this process on the newly created group for a group for 'Month' and so and so on.


text:
Q: Adding Selenium Webdrive Test Cases to Jenkins I have been into QA for more than five years now, however my experience is mainly focused on manual execution. Therefore I decided to move into automation subject (C#, VS2015 and Webdriver) :)
Right now I would like to know how can I add Selenium WD TC into Jenkins for future builds? How can i run them and is there a way to monitor their results/progress/report?
P.s. For any support/anwsers/guidesm thank you!


text:
Q: Elasticsearch 7.x case insensitive sorting using normalizer I am using elasticsearch 7.5 and NEST client.
I want to sort a query, and as you know, by default does A..Za..z. I want it to be case insensitive.
I am trying to use a normalizer as is explained here
PUT /testindex
{
  "settings": {
     "analysis": {
       "normalizer": {
         "case_insensitive": {
            "filter": "lowercase"
         }
        }
       }
     }
}

And then I could use it in the mapping:
PUT /testindex/_mapping/testmapping
{
  "properties": {
    "Id": {
    "type": "keyword"
    },
    "Name": {
      "type": "text",
      "fields": {
        "keyword": {
          "type": "keyword",
          "normalizer": "case_insensitive"
        }
      }
     }
   }
}

The problem it comes when I try to do it on the C# NEST client:
client.Indices.Create("testindex", e => e
                .Settings(s => s
                    .Analysis(a => a
                        .Normalizers(n => n.Custom("case_insensitive",c => c.Filters("lowercase")))))
                .Map(m => m
                    .Properties(p => p
                       .Text(st => st.Name("Name")
                       **.NORMALIZER**)))
            );

There is no way to add the normalizer the Name property field.
Any ideas? Another way to do it efficiently?
Thanks a million.

A: This property is part of keyword type properties as docs say.

The normalizer property of keyword fields is similar to analyzer
  except that it guarantees that the analysis chain produces a single
  token.

Simply changing your prop. to keyword field will allow you to place normalizer
await client.Indices.CreateAsync("testindex", e => e
    .Settings(s => s
        .Analysis(a => a
            .Normalizers(n => n.Custom("case_insensitive", c => c.Filters("lowercase")))))
    .Map(m => m
        .Properties(p => p
            .Keyword(st => st.Normalizer("case_insensitive").Name("Name"))))
);

Hope that helps.


text:
Q: Error compiling extension methods with Kotlin 1.4.10 I don't use Kotlin on a daily basis so I might missed changes between 1.3.72 and 1.4.10. Fact is, code that used to compile with the older version now breaks with the newer. Case in point this file https://github.com/griffon/griffon/blob/development/subprojects/griffon-javafx-kotlin/src/main/kotlin/griffon/javafx/kotlin/collections/reduce/ReducingBindingsExtension.kt
produces lost of errors such as
e: /Users/aalmiray/dev/github/griffon/subprojects/griffon-javafx-kotlin/src/main/kotlin/griffon/javafx/kotlin/collections/reduce/ReducingBindingsExtension.kt: (59, 29): None of the following functions can be called with the arguments supplied:
public open fun <T : Any!> reduceThenMapToBoolean(p0: ObservableList<TypeVariable(T)!>!, p1: TypeVariable(T)!, p2: BinaryOperator<TypeVariable(T)!>!, p3: Function<in TypeVariable(T)!, Boolean!>!): BooleanBinding! defined in griffon.javafx.beans.binding.ReducingBindings
public open fun <T : Any!> reduceThenMapToBoolean(p0: ObservableList<TypeVariable(T)!>!, p1: TypeVariable(T)!, p2: ObservableValue<BinaryOperator<TypeVariable(T)!>!>!, p3: ObservableValue<Function<in TypeVariable(T)!, Boolean!>!>!): BooleanBinding! defined in griffon.javafx.beans.binding.ReducingBindings
public open fun <T : Any!> reduceThenMapToBoolean(p0: ObservableList<TypeVariable(T)!>!, p1: Supplier<TypeVariable(T)!>!, p2: BinaryOperator<TypeVariable(T)!>!, p3: Function<in TypeVariable(T)!, Boolean!>!): BooleanBinding! defined in griffon.javafx.beans.binding.ReducingBindings
public open fun <T : Any!> reduceThenMapToBoolean(p0: ObservableList<TypeVariable(T)!>!, p1: Supplier<TypeVariable(T)!>!, p2: ObservableValue<BinaryOperator<TypeVariable(T)!>!>!, p3: ObservableValue<Function<in TypeVariable(T)!, Boolean!>!>!): BooleanBinding! defined in griffon.javafx.beans.binding.ReducingBindings
public open fun <K : Any!, V : Any!> reduceThenMapToBoolean(p0: ObservableMap<TypeVariable(K)!, TypeVariable(V)!>!, p1: TypeVariable(V)!, p2: BinaryOperator<TypeVariable(V)!>!, p3: Function<in TypeVariable(V)!, Boolean!>!): BooleanBinding! defined in griffon.javafx.beans.binding.ReducingBindings

The full list of errors can be found at https://gist.github.com/aalmiray/e17662a1ffae53006b2f633a35bfec02
Is there a different idiom in Kotlin 1.4 that must be used to write extension functions? What am I missing? TIA.
UPDATE: MCVE can be found at https://github.com/aalmiray/kotlin-mcve. The error is different but the effect is the same, code compiles with 1.3.72 but breaks with 1.4.10.
MCVE project structure
.
├── README.md
├── build.gradle
├── settings.gradle
└── src
    └── main
        └── java
            └── com
                └── acme
                    ├── ReducingBindings.java
                    └── ReducingBindingsExtension.kt

settings.gradle
// empty

build.gradle
plugins {
    id 'java-library'
    id 'org.jetbrains.kotlin.jvm' version '1.4.10'
}

ext.kotlinVersion = '1.4.10'

repositories {
    jcenter()
}

dependencies {
    api "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
}

compileKotlin {
    kotlinOptions.jvmTarget = '1.8'
}

ReducingBindings.java
package com.acme;

import javafx.beans.binding.BooleanBinding;
import javafx.collections.ObservableList;

import java.util.function.BinaryOperator;
import java.util.function.Function;

import static javafx.beans.binding.Bindings.createBooleanBinding;

public class ReducingBindings {

    public static <T> BooleanBinding reduceThenMapToBoolean(final ObservableList<T> items, final T defaultValue, final BinaryOperator<T> reducer, final Function<? super T, Boolean> mapper) {
        return createBooleanBinding(() -> mapper.apply(items.stream().reduce(reducer).orElse(defaultValue)), items);
    }

}

ReducingBindingsExtension.kt
package com.acme

import javafx.beans.binding.BooleanBinding
import javafx.collections.ObservableList
import java.util.function.BinaryOperator
import java.util.function.Function

fun <T> ObservableList<T>.reduceThenMapToBoolean(defaultValue: T?, reducer: BinaryOperator<T>, mapper: Function<in T, Boolean>): BooleanBinding {
    return ReducingBindings.reduceThenMapToBoolean(this, defaultValue, reducer, mapper)
}

Run it with Java 8 and Gradle 6. Or you know, just clone the repo from https://github.com/aalmiray/kotlin-mcve

A:
Is there a different idiom in Kotlin 1.4 that must be used to write extension functions?

No it is the same. But they introduced new type inference mechanism, maybe this is the case.
When I changed type of mapper parameter from Function<in T, Boolean> to Function<in T?, Boolean> in provided example, it compiled!


text:
Q: Width of a UIView not changing based on constraints I have a UIView that I am drawing and adding a subview to another UIView.
This acts as a separator so it needs to be 1px high and the width of the view that it is being added on.
This is the code I have so far:
 var underline = UIView()
 underline.frame = CGRectMake(0, 37, backgroundSection.bounds.size.width, 1)
 underline.backgroundColor = UIColor.whiteColor()
 backgroundSection.addSubview(underline)

This doesn't draw the UIView's width to be the same width as backgroundSection. This draws it as the same width as how backgroundSection looks on the IB before constraints have resized the view.
I could set backgroundSection's clipToBounds to true but I have a shadow on backgroundSection that would be removed if it were to be set to true.
How can I fix this.
Thanks,
Alex

A: You should not be using frame setting when you are using constraints. Auto Layout will do all of the frame setting for you.
Instead, you need to add constraints to your view:
var underline = UIView()
backgroundSection.addSubview(underline)

// These two lines will add horizontal and vertical constraints pinning the underline view to backgroundSection's edges
backgroundSection.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: nil, metrics: nil, views: ["view": underline]))
backgroundSection.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: nil, metrics: nil, views: ["view": underline]))


text:
Q: How can I groupby and aggregate pandas dataframe with many columns I am working on a pandas dataframe with 168 columns. First three columns contain name of the country, latitude and longtitude. Rest of the columns contain numerical data. Each row represents a country but for some countries there are multiple rows. I need to aggregate those rows by summing. I can aggregate first three columns with following code:
df = df.groupby('Country', as_index=False).agg({'Lat':'first','Long':'first'})

However, I couldn't find a way to include in that code remaining 165 columns without explicitly writing all the column names. In addition, column names represent dates and are named like 5/27/20,5/28/20,5/29/20, etc. So I need to keep the column names.
How can I do that? Thanks.

A: Maybe you can generate the dictionary from the column names:
df = df.groupby('Country', as_index=False).agg({c: 'first' for c in df.columns})


text:
Q: How to use a wildcard when querying belongs_to relationships in rails? I have a search/filter form where the user may select none to many parameters from which to filter records.  The filters could include a specific user_id, or company_id, or project_id, etc.  Any combination of these parameters could be submitted to filter records by.
What I'm trying to do is create as simple a query as possible and not need to re-query a subset.
I could pull this off by using more logic in the query...but, it seems there should be a rails way.
Thing.where( params[:user_id].present? ? user_id: params[:user_id] : "user_id IS NOT NULL" ).
   where( params[:company_id].present? ? company_id: params[:company_id] : "company_id IS NOT NULL" )

What I'm striving for is something cleaner...like:
Thing.where( user_id: params.fetch(:user_id, '*') )

Then, I could chain all the available search params like this:
Thing.where(
   user_id: params.fetch(:user_id, '*'),
   company_id: params.fetch(:company_id, '*'),
   project_id: params.fetch(:project_id, '*')
)

Another approach
Thing.where('') will return all Things.  So, I could do something like:
Thing.where( params[:user_id].present? ? { user_id: params[:user_id] } : '' )

But, this doesn't seem like the rails way.
Is there a way to do this?  Thanks!

A: Just create a model that takes the parameters as input and creates a scope:
class ThingFilter
  include ActiveModel::Model
  include ActiveModel::Attributes
  attribute :user_id
  attribute :company_id
  attribute :project_id

  def resolve(scope = Thing.all)
    attributes.inject(scope) do |filtered, (attr_name, value)|
      if !value.present?
        scope.merge(Thing.where.not(attr_name => nil))
      else
        scope.merge(Thing.where(attr_name => value))
      end
    end
  end
end

class Thing < ApplicationRecord
  def self.filter(**kwargs)
    ThingFilter.new(**kwargs).resolve(self.where)
  end
end

@things = Thing.filter(
  params.permit(:user_id, :company_id, :project_id)
)

This is extremely easy to test and lets you add features like validations if needed without making a mess of your controller. You can also bind it to forms.

A: There's a method called #merge which can be used in this case.
@things = Thing.all
@things = @things.merge(-> { where(user_id: params[:user_id]) }) if params[:user_id].present?
@things = @things.merge(-> { where(company_id: params[:company_id]) }) if params[:company_id].present?
@things = @things.merge(-> { where(project_id: params[:project_id]) }) if params[:project_id].present?

Although it's not the most concise way to do it, it's pretty readable in my opinion.

Found a concise way to do it, but use it according to your opinion on readability.
@things =
  params.slice(:user_id, :company_id, :project_id).
    reduce(Thing.all) do |relation, (column, value)|
      relation.where(column => value)
    end

A: It feels like you may be coding that which the Ransack gem already provides.
It accepts search parameters, such as user_id_eq and company_name_present, and sort parameters, and converts them to the required SQL.
https://github.com/activerecord-hackery/ransack


text:
Q: How can I return more than one object of different type in C# .net? I have two objects and I dont want to create a wrapper class to have data of this two object, no 'Out' parameter is there any way that I can return more than one object of different type?
Will really appreciate it!!
Thanks

A: No. You can't.
You can use an array or a map to return them, though.

A: public class VPair<TFirst, TSecond>
    {
        public TFirst First { get; set; }
        public TSecond Second { get; set; }

        public VPair(TFirst first, TSecond second)
        {
            First = first;
            Second = second;
        }
    }

or
Tuple class in c#4.0
bonus:
public class VTriple<TFirst, TSecond, TThird> : VPair<TFirst, TSecond>
    {
        public TThird Third { get; set; }

        public VTriple(TFirst first, TSecond second, TThird third)
            : base(first, second)
        {
            Third = third;
        }
    }

A: In c++ this can be done with something called std::pair. There is a StackOverflow post on how to do it in C#: What is C# analog of C++ std::pair?

A: You can return a List< Object >.

A: return new object[] { object1, object2 }

Alternatively, you can use an anonymous type. See this article for more information.


text:
Q: Mixed content blocking in chrome cast receiver app I am trying to play a DRM protected content using Chromecast custom receiver. I am following this doc https://developers.google.com/cast/docs/custom_receiver.
But it is not working for me. It gives the following error log.
Mixed Content: The page at 'https://abcdefgfgh/index.html' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://mytestvideo'. This content should also be served over HTTPS.

Please advice.
Thanks in advance.

A: Looks like the log there is descriptive enough as to what it means. You need to have all your video content to be served over https (SSL should be signed by a known authority, not a self-signed one) and the server also has to provide the appropriate CORS headers. Please address those and see if that helps or not. As a side note, you might want to grab our reference receiver as your starting point; it already does a lot of the work for you.


text:
Q: How to generate SEF url from product name for other languages in php I want to form a SEF url for the products. For example, if the product name is Sony Ericcsson K550 , my url will be sony-ericcsson-k550. But in case of other languages like turkish, russian and chinese if we enter product name in those particular languages i want to do the same (to form a product url) with out using another field to get product name in english.
I have checked in magento with russian language, when i entered russian language it tooks russian texts for product name and it forms product url in a different manner in english language.
For example, in magento i have added product name as "Новые, Xbox 360 Slim, любой модификации" and it forms an url as follows. privet-jeto-ispytanij-produkta
How it is possible? How to do it in normal php? can any one help me?
Thanks in advance.

A: You can specify the product URL key at a store view level. Russian, turkish, etc are store views. When you edit the product you can change the scope:

*

*Choose Store View (top - left corner)

*Put the value you need in the field: URL Key

*Save

Using php, you need to specify the storeId:
Mage::app()->setCurrentStore(STORE_ID);
$product
->setUrlKey('your-url-key-at-a-store-view-level')
->save()

A: By default magento dose not support non-latin characters in URL key, but there is an extension on Magento connect, named "URL Key Master by Magendev" which allows you to use any character in almost any language in URL key which is more SEF.
it also can automatically generate and replace new URL keys base on product name with your old messy URL keys in a safe and quick way just by two clicks.
take a look at these videos:
http://magendev.com/urlkeymaster-doc/urlkeymaster-introduction.html
http://magendev.com/urlkeymaster-doc/urlkeymaster-auto-generate.html


text:
Q: TS2307: Cannot find module 'angular' There are many questions on this exact error. Nevertheless, I cannot find one that fixes my problem. I'm probably missing something simple but I don't know what.
In my project I just created the first ts file - initialize.ts:
import angular from "angular";

namespace AngularTypeScriptStarterKit {
    angular
        .module('app', []);

}

Now the problem is that 'angular' is marked with red, saying:

TS2307: Cannot find module 'angular'

I have the declarations file for angular located at /typings/globals/angular/index.d.ts
Any help will be profoundly appreciated.
typings.json:
{
  "globalDependencies": {
    "angular": "registry:dt/angular#1.5.0+20160725073351",
    "jquery": "registry:dt/jquery#1.10.0+20170310222111"
  },
  "dependencies": {
    "angular": "registry:dt/angular#1.6.0+20170321201455"
  }
}

Please let me know for any other required information and I'll update my question.

A: If your application is not able to find module you should provide the typescript reference path on the first line of the file itself. Include following line of code :
///
reference path="../../typings/index.d.ts" /,
at top of Initialize.ts In typescript reference path is required for third party libraries so that typescript compiler can understand the method definitions. More on reference path in following link : https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html

A: Typings is deprecated.
You need to use DefinitelyTyped.
Just do :
npm install --save-dev @types/angular

index.d.ts reference


text:
Q: EF Metadata Class not working I seem to be having trouble creating a metadata class for my generated model classes. I have created the below code, but Resharper is telling me that the partial class is a partial class with a single part. The actual Membership generated class is in another project in the same solution. Would that be the problem?
[MetadataType(typeof(MembershipViewModel))]
public partial class Membership
{
}

public class MembershipViewModel
{
    [Required, StringLength(3, MinimumLength = 3, ErrorMessage = "Format: (045/135)")]
    [DisplayAttribute(Name = "Report Cycle")]
    public string ReportCycle { get; set; }
}


text:
Q: How to push array keys and values in a session variable in php? Here is an example (please don't consider the below example, it is not a part of my program)
array( 'agur' => 100,
       'agur' => 300,
       'babu' => 200 );

The above array values i want to insert into a SESSION variable one by one at a time.
Problem is not the above example array i want to insert. The actual script is like Each and every time when i click a link the values from the query string i want to insert into a SESSION Array.
I've tried the below code this didn't help me!
if( !isset( $_SESSION['allmarks'] ) )
{
    $_SESSION['allmarks'] = array();
}
$name = $_GET['name']; //eg. agur
$mark = $_GET['mark']; //eg. 100

$_SESSION['allmarks'] ["$name"] = $mark;

The output im getting is only the last value inserted
'agur' => 300

I've tried array_push too, but it didn't help for me!.
I want the result like below when i var_dumb the SESSION['allmarks']
'agur' => 100
'agur' => 300
'babu' => 200

A: You need to use foreach and loop the array,
  $arr  = array( 'agur' => 100,  'agur' => 300,   'babu' => 200 );
  if( !isset( $_SESSION['allmarks'] ) )
  {
    $_SESSION['allmarks'] = array();
    foreach($arr as $k => $v)
     $_SESSION['allmarks'][$k] = $v;
   }

A: Use foreach() for walking through array

A: No need to loop if you want to just set a session key to this array.
Also, don't forget session_start() (common mistake).
$array = array( 'agur' => 100,
       'agur' => 300,
       'babu' => 200 );

session_start();
$_SESSION['allmarks'] = $array;


text:
Q: I am trying to make an apk its generated but with this error Execution failed for task ':app:bundleReleaseJsAndAssets'
Task :app:bundleReleaseJsAndAssets
  Scanning folders for symlinks in C:\react-native\first_app\node_modules (109ms)
  Scanning folders for symlinks in C:\react-native\first_app\node_modules (47ms)
  warning: the transform cache was reset.
  Loading dependency graph, done.

Unable to resolve module AccessibilityInfo from C:\react-native\first_app\node_modules\react-native\Libraries\react-native\react-native-implementation.js: Module AccessibilityInfo does not exist in the Haste module map
This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: watchman watch-del-all.
  2. Delete the node_modules folder: rm -rf node_modules && npm install.
  3. Reset Metro Bundler cache: rm -rf /tmp/metro-bundler-cache-* or npm start -- --reset-cache.  4. Remove haste cache: rm -rf /tmp/haste-map-react-native-packager-*.
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.

Process 'command 'cmd'' finished with non-zero exit value 1

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org
BUILD FAILED in 42s
12 actionable tasks: 1 executed, 11 up-to-date

A: As mentioned here, It may be because of you did not bundled correctly for android.
You can add following script
"bundle-android": "node node_modules/react-native/local-cli/cli.js bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/"
into scripts of your package.json
and the run npm run bundle-android
after that try running gradlew assembleRelease -x bundleReleaseJsAndAssets in android directory of your project. Hope it will solve your problem.