text:
Q: How to extract single word (not larger word containing it) in pandas dataframe? I would like to extract the word like this:
a dog ==> dog
some dogs ==> dog
dogmatic ==> None

There is a similar link:
Extract substring from text in a pandas DataFrame as new column
But it does not fulfill my requirements.
From this dataframe:
df = pd.DataFrame({'comment': ['A likes cat', 'B likes Cats',
                               'C likes cats.', 'D likes cat!',
                               'E is educated',
                              'F is catholic',
                              'G likes cat, he has three of them.',
                              'H likes cat; he has four of them.',
                              'I adore !!cats!!',
                              'x is dogmatic',
                              'x is eating hotdogs.',
                              'x likes dogs, he has three of them.',
                              'x likes dogs; he has four of them.',
                              'x adores **dogs**'
                              ]})

How to get correct output?
                            comment      label EXTRACT
0                           A likes cat   cat     cat
1                          B likes Cats   cat     cat
2                         C likes cats.   cat     cat
3                          D likes cat!   cat     cat
4                         E is educated  None     cat
5                         F is catholic  None     cat
6    G likes cat, he has three of them.   cat     cat
7     H likes cat; he has four of them.   cat     cat
8                      I adore !!cats!!   cat     cat
9                         x is dogmatic  None     dog
10                 x is eating hotdogs.  None     dog
11  x likes dogs, he has three of them.   dog     dog
12   x likes dogs; he has four of them.   dog     dog
13                    x adores **dogs**   dog     dog

NOTE: The column EXTRACT gives wrong answer, I need like the column label.

A: We can use str.extract with negative lookahead: ?!. We check if the the characters after the match are not more than 2 letters. For example dogmatic:
After that we use np.where with positive lookahead. The pseudo logic is like following:

All the rows which have "dog" or "cat" with alphabetic characters in front of it will be be replaced by NaN

words = ['cat', 'dog']

df['label'] = df['comment'].str.extract('(?i)'+'('+'|'.join(words)+')(?![A-Za-z]{2,})')
df['label'] = np.where(df['comment'].str.contains('(?<=\wdog)|(?<=\wcat)'), np.NaN, df['label'])

Output
                                comment label
0                           A likes cat   cat
1                          B likes Cats   Cat
2                         C likes cats.   cat
3                          D likes cat!   cat
4                         E is educated   NaN
5                         F is catholic   NaN
6    G likes cat, he has three of them.   cat
7     H likes cat; he has four of them.   cat
8                      I adore !!cats!!   cat
9                         x is dogmatic   NaN
10                 x is eating hotdogs.   NaN
11  x likes dogs, he has three of them.   dog
12   x likes dogs; he has four of them.   dog
13                    x adores **dogs**   dog

A: What you are trying to achieve is extracting the label of your sentence. It is a natural language processing problem not a programming problem.
Approaches:

*

*Use a stemmer/lemmatizer .  You could match the output of the stemmer with your stemmed class name list. This will most likely not give you a high enough accuracy.

*Train a machine learning classifier on your topics/labels.

Lemmatizer solution - I used some preprocessing code from another answer in this question
import nltk
import pandas as pd

lemma = nltk.wordnet.WordNetLemmatizer()
nltk.download('wordnet')

df = pd.DataFrame({'comment': ['A likes cat', 'B likes Cats',
                           'C likes cats.', 'D likes cat!',
                           'E is educated',
                          'F is catholic',
                          'G likes cat, he has three of them.',
                          'H likes cat; he has four of them.',
                          'I adore !!cats!!',
                          'x is dogmatic',
                          'x is eating hotdogs.',
                          'x likes dogs, he has three of them.',
                          'x likes dogs; he has four of them.',
                          'x adores **dogs**'
                          ]})

word_list = ["cat",  "dog"]    # words (and all variations) that you wish to check for
word_list = list(map(lemma.lemmatize, word_list))

df["label"] = df["comment"].str.lower().str.replace('[^a-zA-Z]', ' ').apply(lambda x: [ lemma.lemmatize(word) for word in x.split()  ])
df["label"] = df["label"].apply(lambda x: [i for i in word_list if i in x])

df["label"] = df["label"].apply(lambda x: None if not x else x)
print(df)

A: df = pd.DataFrame({'comment': ['A likes cat', 'B likes Cats',
                           'C likes cats.', 'D likes cat!',
                           'E is educated',
                          'F is catholic',
                          'G likes cat, he has three of them.',
                          'H likes cat; he has four of them.',
                          'I adore !!cats!!',
                          'x is dogmatic',
                          'x is eating hotdogs.',
                          'x likes dogs, he has three of them.',
                          'x likes dogs; he has four of them.',
                          'x adores **dogs**'
                          ]})

word_list = ["cat", "cats", "dog", "dogs"]    # words (and all variations) that you wish to check for

df["label"] = df["comment"].str.lower().str.replace('[^\w\s]','').str.split().apply(lambda x: [i for i in word_list if i in x])
df["label"] = df["label"].apply(lambda x: None if not x else x)
df["label"] = df["label"].str.replace("[","").str.replace("]","").str.replace("'","").str.replace("s","")

Then that gives you:
df
    comment                             label
0   A likes cat                         cat
1   B likes Cats                        cat
2   C likes cats.                       cat
3   D likes cat!                        cat
4   E is educated                       None
5   F is catholic                       None
6   G likes cat, he has three of them.  cat
7   H likes cat; he has four of them.   cat
8   I adore !!cats!!                    cat
9   x is dogmatic                       None
10  x is eating hotdogs.                None
11  x likes dogs, he has three of them. dog
12  x likes dogs; he has four of them.  dog
13  x adores **dogs**                   dog

A: Something like this?
/^(.*?[^a-z\r\n])?((cat|dog)s?)([^a-z\r\n].*?)?$/gmi

\2 will contain one of: cat, dog, cats, dogs
https://regex101.com/r/Tt3MiZ/3

A: You can compile regex for cat, cats, dog and dogs.
import re
regex = re.compile(r'cats', re.I)
data = ['A likes cat', 'B likes Cats',
                           'C likes cats.', 'D likes cat!',
                           'E is educated',
                          'F is catholic',
                          'G likes cat, he has three of them.',
                          'H likes cat; he has four of them.',
                          'I adore !!cats!!',
                          'x is dogmatic',
                          'x is eating hotdogs.',
                          'x likes dogs, he has three of them.',
                          'x likes dogs; he has four of them.',
                          'x adores **dogs**'
                          ]
for i in data:
    t = regex.search(i)
    print(t)

A: In this case I imagine you don't even need to use regex. Just use the equal-to operator == to specify the exact match since you're looking for "dog" "dogs" "cat" "cats" as the entire word. For example:
for word in string:
    if word == "dogs":
        print("Yes")
    else:
        print("No")

If your string were "he likes hotdogs", the above loop would return "No"


text:
Q: localization in asp.net web forms with one global resource I want to have one some resource files like this:
Mui.resx
Mui.fr.resx
Mui.es.resx
...

and I want to be able to do in my codebehind something like this:
Label1.Text = Mui.Hello;

and in my aspx something like this:
<%=Mui.Hello %>

anybody knows how to do this ? is it possible ?

A: Yes it is possible. You can add your resource file from File-New- Resource File  and there you can add their own Resource key and their values as you want either in English or other language.,
Check these
How to: Retrieve Resource Values Programmatically and ASP.NET Web Page Resources Overview

To retrieve global resources using strong typing

*

*Get the resource using the following syntax:

Resources.Class.Resource

  Example:

String welcome;
welcome = Resources.WebResources.WelcomeText;

But if you using Localization
  Have you check this MSDN resouce:
Walkthrough: Using Resources for Localization with ASP.NET

Check the section Explicit Localization with ASP.NET on the link above.
Example:
label's text attribute now has an explicit expression stating the base file from which to retrieve the resource and the key to select.
<asp:Label ID="Label2" Runat="server" Text="<%$ Resources:LocalizedText, Msg1 %>">

And on your page:
Simple call with full path of resource key.
Check this great article - Resources and Localization  that will explain you more about this.
Edit- Web.Config Culture Settings:
Add this
<globalization culture="auto" uiCulture="auto" enableClientBasedCulture="true"/>   in web.config under <system.web>
If you want it on some pages then use <@Page> directive's Culture and UICulture attributes.

A: Add the Resources namespace.
Label1.Text = Resources.Mui.Hello;

and
<%=Resources.Mui.Hello %>

A: I've the same problem and finally discovered the solution.
In the browser if you choose the browser language French [fr] ASP loads the resource.fr.resx
But, if you you choose the browser language French (France)[fr-FR] ASP loads the resource.fr-FR.resx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error 24 : Write error : cannot write compressed block I recently updated from Ubuntu 18.04 to 19.10. It looks to me as if the update installed an older kernel (5.3.0-29) than the one I had running under 18.04 (5.0.0-36). Since then I've had errors on all apt updates which show initramfs failing:
Setting up initramfs-tools (0.133ubuntu10) ...
update-initramfs: deferring update (trigger activated)
Processing triggers for initramfs-tools (0.133ubuntu10) ...
update-initramfs: Generating /boot/initrd.img-5.3.0-29-generic
Error 24 : Write error : cannot write compressed block
E: mkinitramfs failure cpio 141 lz4 -9 -l 24
update-initramfs: failed for /boot/initrd.img-5.3.0-29-generic with 1.
dpkg: error processing package initramfs-tools (--configure):
 installed initramfs-tools package post-installation script subprocess returned
error exit status 1
Errors were encountered while processing:
 initramfs-tools
E: Sub-process /usr/bin/dpkg returned an error code (1)

My output of uname -r is
5.3.0-29-generic

and
alex@acer:~$ dpkg --list | grep linux-image
ii  linux-image-5.0.0-36-generic                  5.0.0-36.39                                         amd64        Signed kernel image generic
ii  linux-image-5.3.0-29-generic                  5.3.0-29.31                                         amd64        Signed kernel image generic
ii  linux-image-generic                           5.3.0.29.33                                         amd64        Generic Linux kernel image

Any ideas on how to solve? I'm not even sure what the issue is, but have gone through plenty of other solutions.

A: I encountered this problem as my /boot partitions was full.
I carefully deleted a few large initrd.img files that I was sure I did not need anymore.
Make sure you write down your last working kernel. Do not delete all others right away, because you don't want them all to be regenerated.
I ran sudo apt autoremove --purge and did another sudo apt dist-upgrade -V to get the missind initrd image files generated.
once you have rebooted on your last kernel. and things are fine. Then I invite you to clean up all the old stuff.
Current packages you should NOT touch
dpkg -l | egrep "linux-(signed|modules|image|headers)" | grep $(uname -r)
Old packages you can purge
dpkg -l | egrep "linux-(signed|modules|image|headers)" | grep -v $(uname -r | cut -d - -f 1)
I purged them all with
dpkg -l | egrep "linux-(signed|modules|image|headers)" | grep -v $(uname -r | cut -d - -f 1) | awk {'print $2'} | xargs sudo apt purge -y
I still had 4.10 and 4.13 packages on a Ubuntu 20.10 running 5.8.0-45

A: OK I think I may have just solved this. I didn't notice at first that I was actually using the newer kernel rather than the old one. In my first couple of boots after update, the older kernel (5.0.-) was in use, rather than the newer one (5.3.-).
So with sudo apt purge linux-image-5.0.0-36-generic it looked like that freed some some space on /boot and voila computer says
Setting up initramfs-tools (0.133ubuntu10) ...
update-initramfs: deferring update (trigger activated)
(Reading database ... 328490 files and directories currently installed.)
Purging configuration files for linux-image-5.0.0-36-generic (5.0.0-36.39) ...
rmdir: failed to remove '/lib/modules/5.0.0-36-generic': Directory not empty
Processing triggers for initramfs-tools (0.133ubuntu10) ...
update-initramfs: Generating /boot/initrd.img-5.3.0-29-generic

A: As a workaround you can try this for more temporary scratch space:
cd /
sudo rsync -av /boot/ /boot2/
sudo mount --bind /boot2 /boot
sudo update-initramfs -u
sudo umount /boot
sudo rsync -av /boot2/ /boot/ --exclude "*.new" --exclude "*.dpkg-bak" --delete --inplace

A: 5.3 is a newer/later kernel than 5.0
Only the first two numbers are from upstream and are significant in comparing kernels.
The other trailing minor numbers are internal Ubuntu codes that apply only to that kernel, ie. don't compare minor numbers of a 5.3 series kernel to a 5.0 series kernel.  The minor numbers (ie. those after 5.0/5.3, should only be used to compare within the same kernel)
https://wiki.ubuntu.com/Kernel/MainlineBuilds
note: by two numbers I mean number.number; so 4.19 example from the pasted link qualifies as first two numbers as I'm using the term.


text:
Q: Using C to Call a function inside a Python file I'm using the following code to call a script called multiple inside a python file called also multiple.py:
#include <Python2.7/Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pDict, *pFunc;
    PyObject *pArgs, *pValue;
    int i;

    if (argc < 3) {
        fprintf(stderr, "Usage: call pythonfile funcname [args]\n");
        return 1;
    }

    Py_Initialize();
    pName = PyString_FromString("multiply");

    Py_DECREF(pName);

    if (pModule != NULL) {
        pFunc = PyObject_GetAttrString(pModule, argv[2]);

        if (pFunc && PyCallable_Check(pFunc)) {
            pArgs = PyTuple_New(argc - 3);
            for (i = 0; i < argc - 3; ++i) {
                pValue = PyInt_FromLong(atoi(argv[i + 3]));
                if (!pValue) {
                    Py_DECREF(pArgs);
                    Py_DECREF(pModule);
                    fprintf(stderr, "Cannot convert argument\n");
                    return 1;
                }
                PyTuple_SetItem(pArgs, i, pValue);
            }
            pValue = PyObject_CallObject(pFunc, pArgs);
            Py_DECREF(pArgs);
            if (pValue != NULL) {
                printf("Result of call: %ld\n", PyInt_AsLong(pValue));
                Py_DECREF(pValue);
            }
            else {
                Py_DECREF(pFunc);
                Py_DECREF(pModule);
                PyErr_Print();
                fprintf(stderr,"Call failed\n");
                return 1;
            }
        }
        else {
            if (PyErr_Occurred())
                PyErr_Print();
            fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
        }
        Py_XDECREF(pFunc);
        Py_DECREF(pModule);
    }
    else {
        PyErr_Print();
        fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
        return 1;
    }
    Py_Finalize();
    return 0;
}

This is given the following error:
Failed to load "multiply.py"

And I can't figure it out what I'm doing wrongly.
The structure:
| dist/
| - main.out
| src/
| - main.c
| multiple.py

Inside the multiple.py:
def multiply(a, b):
    print "Will compute", a, "times", b
    c = 0
    for i in range(0, a):
        c = c + b
    return c

And the command line:
gcc src/main.c -framework Python -o dist/main.out && ./dist/main.out multiply.py 32

Thank you.


text:
Q: Postgraphile order by result of calculation (with input) Some context:
My table has two columns, longitude and latitude.
I want to be able to create a query that can receive an input of a longitude, latitude and a number that represents the maximum number of kilometers distance.
The query will return the rows that are within that distance ordered by the resulting distance.
I have seen few options for custom conditions, but that might be pretty hacky...
I thought maybe there is a way to do it and use the build in order by that PostGraphile generates, but the I'm if there is a way to pass variable to the order by.
The question:
What is the best to do it in PostGraphile?
Thanks in advance!

A: To do this, step 1 is to build your filter object with your x, y and radius:
const { makePluginByCombiningPlugins, makeAddPgTableConditionPlugin } = require('graphile-utils');

const PositionFilterObjectPlugin = builder => {
  builder.hook('build', build => {
    const nonNullFloat = new build.graphql.GraphQLNonNull(build.graphql.GraphQLFloat);
    const PositionFilter = new build.graphql.GraphQLInputObjectType({
      name: 'PositionFilter',
      fields: {
        x: {
          type: nonNullFloat,
        },
        y: {
          type: nonNullFloat,
        },
        radius: {
          type: nonNullFloat,
        },
      },
    });
    build.addType(PositionFilter);

    return build;
  });
};

/*
   Due to a plugin ordering issue that cannot be addressed in V4, we can't
   just use makeExtendSchemaPlugin to add this type; we have to write it
   out by hand in the build hook.

   input PositionFilter {
     x: Float!
     y: Float!
     radius: Float!
   }
*/

(build.graphql is an instance of the graphql module, the reference GraphQL implementation, you can read more about it here and here.)
Step 2 is to add a condition that also does ordering:
const PositionConditionPlugin = makeAddPgTableConditionPlugin(
  'public',
  'entities',
  'closeTo',
  build => ({
    type: build.getTypeByName('PositionFilter'),
  }),
  (value, { queryBuilder, sql, sqlTableAlias }) => {
    if (value == null) {
      return;
    }

    const { x, y, radius } = value;
    const valX = sql.value(x);
    const valY = sql.value(x);
    const valR = sql.value(radius);

    const distance = sql.fragment`(((${sqlTableAlias}.x - ${valX}) ^ 2 + (${sqlTableAlias}.y - ${valY}) ^ 2) ^ 0.5)`;

    // Order the result set by the proximity of the entity to the given point
    queryBuilder.orderBy(
      distance,
      true, // Ascending
      false,
    );

    // Filter to only entities within the given radius
    return sql.fragment`${distance} < ${valR}`;
  },
);

Finally you either load both these plugins or if you prefer you can make a single plugin that encompasses both:
module.exports = makePluginByCombiningPlugins(PositionFilterObjectPlugin, PositionConditionPlugin);

I've added an example with ordering to the docs:
https://www.graphile.org/postgraphile/make-add-pg-table-condition-plugin/#example-with-ordering
NOTE: before graphile-utils 4.9.1 is released you'll need to add this plugin via --prepend-plugins (or prependPlugins for library users) because otherwise there's a plugin ordering issue that means that orders added by makeAddPgTableConditionPlugin come after the default orders.


text:
Q: How to forward Screen Capture in iOS 11 Control Center to your App? I saw that TeamViewer allows iOS Screen Capturing by leveraging the Screen Recorder feature from the Control Center in iOS 11. As seen here:
How is that possible? I checked out the ReplayKit, but couldn't find any feature that would hook up to the Control Center like that.

A: You need to add a Broadcast Upload Extension to your app.
(In Xcode, File > New Target, select "Broadcast Upload Extension")
Once the extension is installed (alongside your app), a force-touch on the screen recording icon in control center will give the option of using your broadcast extension, instead of the default ("Camera Roll").
There is very little documentation on iOS Screen Recording right now. But this WWDC video talks about it at a high level:
https://developer.apple.com/videos/play/wwdc2017/606/


text:
Q: Is it possible to change the color of grid lines in a chart and can we add dots at the data points in line chart in power bi? Is it possible to change the background gridline color of the line chart & can we dot at the data points of the line chart?

A:
Can you add markers (or dots) to the line chart?

Yes, but the X axis must be of type "categorical".
navigate to "Shapes" > "Show Marker" (on/off)

Can you change the background grid line color?

Yes you can.
Expand "Y Axis" > navigate at the bottom until you find "Gridlines" (on/off) > here you have all the gridline settings


text:
Q: AppleScript is throwing a stack overflow error on changing file extension Why does this function throw a stack overflow error?
on convertFileExtenstion(parentFolder, thisFile)
  set filePath to ((parentFolder as text) & thisFile) as alias
  if my fileExists(filePath) is equal to true then
     set name extension of filePath to "txt"
     log filePath
  end if

end convertFileExtenstion

on fileExists(theFile)
  set fileExists to false
  tell application "Finder"
      if exists (file theFile as alias) then
          set fileExists to true
      end if
  end tell

  return fileExists
end fileExists

The file is just on my desktop, I am only trying to change the extension on one file.
path: Macintosh HD:Users:xxxxxxxxx:Desktop:prebidServerBidders:client.yaml
Edit: It's not just extensions, I can't change the file name either.

A: You can't set the name extension of a file this way.
the 'name extension' is a property from 'file information' you can GET but not SET.
 get name extension of (info for filePath)

*

*extract the file name without extension,

*add yours

*change the whole the name with the help of the Finder

tell application "Finder" to set name of filePath to theNewFileNameWithMyExt


text:
Q: Unable to receive SIP calls when app is killed What should I do to receive SIP calls even when app is in background, exits or restarts?
Currently we're running a foreground service with sticky notification to keep connected with our sip server. This solution isn't completely working
Please help me to achieve this, Thanks in advance!

A: Firstly, you want a Mainservice that never stops (Even when the device booted, with the help of a bootup receiver).
You have to initialise your sip manager, sip profile and call related codes in the MainService and not in the MainActivity.
Then, You need a BroadCast receiver that receives incoming sip calls. see below example,
public class YourReceiver extends BroadcastReceiver {
SipAudioCall incomingCall   = null;
private static YourReceiver instance;
MainService mainService;
public Intent incomingCallIntent;

public static YourReceiver getInstance() {
    return instance;
}

/**
 * Processes the incoming call, answers it, and hands it over to the
 * MainActivity.
 * @param context The context under which the receiver is running.
 * @param intent The intent being received.
 */
@Override
public void onReceive(final Context context, Intent intent) {
    Log.i(TAG, "onReceive: ");
    instance    = this;
    mainService = MainService.getInstance();

    try {
        SipAudioCall.Listener listener = new SipAudioCall.Listener() {
            @Override
            public void onRinging(SipAudioCall call, SipProfile caller) {
                Log.i(TAG, "onRinging: ");

            }

            // extra added
            @Override
            public void onRingingBack(SipAudioCall call) {
                Log.i(TAG, "onRingingBack: ");
                super.onRingingBack(call);
            }

            @Override
            public void onReadyToCall(SipAudioCall call) {
                Log.i(TAG, "onReadyToCall: ");
                super.onReadyToCall(call);
            }

            @Override
            public void onError(SipAudioCall call, int errorCode, String errorMessage) {
                Log.e(TAG, "onError: errorCode = " + errorCode + ", errorMessage = " + errorMessage);
                super.onError(call, errorCode, errorMessage);
            }

            @Override
            public void onChanged(SipAudioCall call) {
                Log.i(TAG, "onChanged: ");
                super.onChanged(call);
            }

            @Override
            public void onCalling(SipAudioCall call) {
                Log.i(TAG, "onCalling: ");
                super.onCalling(call);
            }

            @Override
            public void onCallHeld(SipAudioCall call) {
                Log.i(TAG, "onCallHeld: ");
                super.onCallHeld(call);
            }

            @Override
            public void onCallBusy(SipAudioCall call) {
                Log.i(TAG, "onCallBusy: ");
                super.onCallBusy(call);
            }

            @Override
            public void onCallEnded(SipAudioCall call) {
                Log.i(TAG, "onCallEnded: ");

            }

            @Override
            public void onCallEstablished(SipAudioCall call) {
                Log.i(TAG, "onCallEstablished: ");
                super.onCallEstablished(call);
            }
        };

        mainService  = MainService.getInstance();
        incomingCall = mainService.manager.takeAudioCall(intent,listener);
        if(mainService.manager.isIncomingCallIntent(intent)){
            incomingCallIntent = intent;
        }

        //starting call screen activity when the receiver receives incoming call
        Intent i    = new Intent(context, CallActivity.class);
        i.putExtra("name", peerName);
        i.putExtra("number", peerNumber);
        i.putExtra("callType", "Incoming");
        context.startActivity(i);

//Sip call received by YourReceiver is assigned to MainService.call so that the MainService can do the further processes.
        mainService.call = incomingCall;

    } catch (Exception e) {
        if (incomingCall != null) {
            incomingCall.close();
        }
    }
}

}

A: For making a Service run continuously, start a Job scheduler to make this job be a part of android system jobs.
package com.xxx;

import android.app.job.JobParameters;
import android.app.job.JobService;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;

import androidx.annotation.RequiresApi;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class XXJobService extends JobService {
    private String TAG = "XXJobService";
    private Context context;

    public XXJobService() {
    }

    @Override
    public boolean onStartJob(JobParameters params) {
        context = this;

        try {
            if (!MyApp.isServiceRunning(context, MainService.class.getName())) {
                Log.i(TAG, "onStartJob : MainService not running so start");

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    context.getApplicationContext()
                            .startForegroundService(new Intent(context, MainService.class)
                                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                } else {
                    context.getApplicationContext()
                            .startService(new Intent(context, MainService.class)
                                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "Exception - MainService not running: " + e.getLocalizedMessage());
        }

        Log.i(TAG, "onStartJob, returnValue = " + returnValue);
        return returnValue;
    }

    @Override
    public boolean onStopJob(JobParameters params) {

        boolean returnValue = true;

        Log.i(TAG, "onStopJob, returnValue = " + returnValue);
        return returnValue;
    }
}

Create an Application class in your project that extends Application and define it in your manifest also.
import android.app.ActivityManager;
import android.app.Application;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import java.util.Arrays;
import java.util.List;

public class MyApp extends Application {

    Context context;
    private static MyApp instance;
    static String TAG = "MyApp";
    MainService mainService;
    JobScheduler jobScheduler;
    private static final int JOB_ID = 1;

    public static MyApp getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context  = this;
        instance = this;
        Log.i(TAG, "onCreate: ");

        // Job scheduler for android version Lolipop(Android 5.0) and above
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                jobScheduler             = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
                ComponentName jobService = new ComponentName(getPackageName(), XXJobService.class.getName());
                Log.e(TAG, "onCreate: ComponentName : " + jobService );
                JobInfo jobInfo          = new JobInfo.Builder(JOB_ID, jobService)
                        .setPersisted(true)
                        .setPeriodic(5000)
                        .build();
                int jobId                = jobScheduler.schedule(jobInfo);

                if (jobId == JobScheduler.RESULT_SUCCESS) {
                    Log.e(TAG, "JobScheduler RESULT_SUCCESS");
                    // Toast.makeText(context, "Successfully scheduled job : " + jobId, Toast.LENGTH_SHORT).show();
                } else {
                    Log.e(TAG, "JobScheduler RESULT_FAILURE: " + jobId);
                    // Toast.makeText(context, "RESULT_FAILURE: " + jobId, Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                Log.e(TAG, "JobScheduler Exception : " + e.getLocalizedMessage());
            }
        }

        if (!isServiceRunning(context, MainService.class.getName())) {
            try {
                Intent intent = new Intent(context, MainService.class);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startForegroundService(intent);
                } else {
                    startService(intent);
                }
            } catch (Exception e) {
                Log.e(TAG, "Exception startService : " + e.getLocalizedMessage());
            }
        }

        mainService = MainService.getInstance();
        Log.e(TAG," MainSerivice : " + mainService);

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                handleUncaughtException(t, e);
            }
        });
    }

    public static boolean isServiceRunning(Context context, String serviceClassName) {
        if (context == null || serviceClassName.equalsIgnoreCase("")) {
            Log.i(TAG, "isServiceRunning called with context = null or service name blank");
            return false;
        }

        ActivityManager activityManager                     = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> services   = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (ActivityManager.RunningServiceInfo runningServiceInfo : services) {
            if (runningServiceInfo.service.getClassName().equals(serviceClassName))
                return true;
        }

        return false;
    }

}

Finally, put a BootUpReceiver to automatically start the notofication and services whenever the phone is restarted. It should have the permission
 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<receiver
            android:name=".StartupReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.xx.MainService" />
                <action android:name="android.intent.action.ACTION_SHUTDOWN" />
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />

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

A: Running a service is the right way. You just have to start the activity which will handle your incoming call from the service. The activity can then bind to your service and request all it needs to take over the call. That's actually all you need.


text:
Q: How to add settings section on android rom settings? I'm creating my Rom from sources, Aosp based, and I have added some features.
But I have a problem with last one.
My question is: How can I add settings on a setting section already existent or creating new one?
My sources are here -> https://github.com/EF-Aosp
Look for Apps_Settings Repo, the battery customizable commits. I need to show the settings for battery icon customizations. I really need help.


text:
Q: How to redirect user when certain condition is met using REST JAX-RS implementation? I used to just use Tomcat and JSP pages which I can execute query, then assign query result into the array or object then pass that data onto client side via response.
request.setAttribute("errorMessage", "this is error!!");
request.getRequestDispatcher("report.jsp").forward(request, response);

In client jsp code, I could do something like:
${errorMessage}
Then the "this is error!!" message would show up.
I want to do the same thing with REST JAX-RS GlassFish v3.
    @Path("schedule/test")
    @POST
    @Consumes("application/x-www-form-urlencoded")
    @Produces("application/vnd.ms-excel")
    public Object tmpTest(String content) {
        try {

            //just my method to execute query and get result
            Vector out = (Vector)QueryManager.executeQuery;

            //if query result is empty, I want user to redirect to report.jsp page
            if(out.isEmpty()) {
                request.setAttribute("errorMessage", "This is error!!");
                request.getRequestDispatcher("report.jsp").forward(request, response);
                return null;
            }
        ....continue code......
   }

This results in mysterious exception I've never seen.
java.lang.ClassCastException: $Proxy109 cannot be cast to org.apache.catalina.core.ApplicationHttpRequest
            at org.apache.catalina.core.ApplicationHttpRequest.getRequestFacade(ApplicationHttpRequest.java:1001)
            at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:472)
            at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:379)
            at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:336)
            at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:314)

So how can I redirect a user to report.jsp and also pass message like "This is error" ?
The client jsp expects the error msg variable to have a value:
<b>${errorMessage}</b>

A: That's not RESTful. You need to throw a WebApplicationException with a specific status code so that the client understands what exactly went wrong. E.g. when it's actually the server's mistake:
throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);

Or when it was after all client's mistake:
throw new WebApplicationException(Response.Status.BAD_REQUEST);

See also HTTP status code definitions for an overview.

The ClassCastException which you're facing is by the way occurring because the dispatched request is actually not an instance of the servletcontainer-provided implementation (in this particular case, the one of Tomcat or a Tomcat-fork). After all, you shouldn't be doing it this way. You're developing a REST webservice, not a JSP/Servlet website. It are two distinct worlds.

A: As mentioned before, you should try WebApplicationException.
I believe you this would give you your desired answer:
Try this:
        if(out.isEmpty()) {
             java.net.URI location = new java.net.URI("report.jsp");
             throw new WebApplicationException(Response.seeOther(location).build());
         }


text:
Q: Python split string every n character I need help finding a way to split a string every nth character, but I need it to overlap so as to get all the
An example should be clearer:
I would like to go from "BANANA" to "BA", "AN", "NA", "AN", "NA", "
Here's my code so far
import string

import re

def player1(s):

    pos1 = []

    inP1 = "AN"

    p = str(len(inP1))

    n = re.findall()

    for n in range(len(s)):

        if s[n] == inP1:

            pos1.append(n)

    points1 = len(pos1)

    return points1

if __name__ == '__main__':

    = "BANANA"

A: You can do this pretty simply with list comprehension;
input_string = "BANANA"
[input_string[i]+input_string[i+1] for i in range(0,len(input_string)-1)]

or for every nth character:
index_range = 3
[''.join([input_string[j] for j in range(i, i+index_range)]) for i in range(0,len(input_string)-index_range+1)]

A: This will iterate over each letter in the word banana, 0 through 6.
Then print each letter plus the next letter. Else statement for when the word reaches the last letter.
def splitFunc(word):
    for i in range(0, len(word)-1):
        if i < len(word):
            print(word[i] + word[i+1])
        else:
            break

splitFunc("BANANA")

Hope this helps

A: Those are called n-grams.
This should work :)
text = "BANANA"
n = 2
chars = [c for c in text]
ngrams = []
for i in range(len(chars)-n + 1):
  ngram = "".join(chars[i:i+n])
  ngrams.append(ngram)
print(ngrams)

output: ['BA', 'AN', 'NA, 'AN', 'NA']


text:
Q: Force generic type to be the type of a unique symbol in typescript After reading this answer about nominal typing I thought to move it one step further with
export type MARKED<C, M> = C & {
  readonly m: M;
};

and to be used like
const readonly SPECIAL: unique symbol = Symbol();
isSpecial(value: C): value is MARKED<C, typeof SPECIAL> {
  return someVerificationOf(value);
}

Here I try to be extra safe by replacing the "brand" with a unique symbol, though MARKED could as well be used with just a string as
class Foo { ... };
type SpecialFoo = MARKED<Foo, 'special'>;

Is there a chance to force the 2nd generic parameter of MARKED to be a unique symbol? I tried things like
type MARKED<C, M extends unique symbol> = ...

but this is obviously wrong.

A: Please see the docs

To enable treating symbols as unique literals a new type unique symbol is available. unique symbol is a subtype of symbol, and are produced only from calling Symbol() or Symbol.for(), or from explicit type annotations. The new type is only allowed on const declarations and readonly static properties, and in order to reference a specific unique symbol, you'll have to use the typeof operator. Each reference to a unique symbol implies a completely unique identity that's tied to a given declaration.

Especially this: in order to reference a specific unique symbol, you'll have to use the typeof operator
Hence, in order to use unique symbol constraint, you need to use typeof:

const UNIQUE: unique symbol = Symbol();

type MARKED<U extends typeof UNIQUE> = U

type Result = MARKED<typeof UNIQUE>

But, I'd willing to bet, that you have several unique symbols and you don't want to create utility type for each symbol.
Let's take a look closer to this line: unique symbol is a subtype of symbol.
What it gives us?
unique symbol is a subtype of symbol. It gives us a door for checking whether some type is a subtype of symbol or not. It is already something.
So, we need to check whether passed type is a subtype of symbol:
type IsUnique<UniqueSymbol extends symbol> =
    (UniqueSymbol extends symbol
        ? (symbol extends UniqueSymbol
            ? false
            : true
        )
        : false
    )

// true
type Check = IsUnique<symbol & { tag: 42 }>

Above util does not meet our requirements.
We need also to check if symbol contains only symbol keys.
type IsExactKeys<S extends symbol> =
    (keyof S extends SYMBOL_KEYS
        ? (SYMBOL_KEYS extends keyof S
            ? true
            : false
        )
        : false
    )

type IsUnique<UniqueSymbol extends symbol> =
    (UniqueSymbol extends symbol
        ? (symbol extends UniqueSymbol
            ? false
            : IsExactKeys<UniqueSymbol>
        )
        : false
    )
// never
type Check = IsUnique<never>

Ooops, it still does not work with never.
Let's handle never type:

const UNIQUE: unique symbol = Symbol();
const REGULAR: symbol = Symbol()

type SYMBOL_KEYS = keyof symbol;

type IsExactKeys<S extends symbol> =
    (keyof S extends SYMBOL_KEYS
        ? (SYMBOL_KEYS extends keyof S
            ? true
            : false
        )
        : false
    )

// credits goes to https://github.com/microsoft/TypeScript/issues/40248
type IsNever<T> = [T] extends [never] ? true : false;

type IsUnique<UniqueSymbol extends symbol> =
    (IsNever<UniqueSymbol> extends true ? false
        : (UniqueSymbol extends symbol
            ? (symbol extends UniqueSymbol
                ? false
                : IsExactKeys<UniqueSymbol>
            )
            : false
        )
    );

type Assert<T extends true> = T

type Unique = {
    readonly StaticSymbol: unique symbol
}['StaticSymbol']

/**
 * Ok
 */
type Test0_0 = Assert<IsUnique<Unique>> // ok
type Test0 = Assert<IsUnique<typeof UNIQUE>> // ok

/**
 * Expected errors
 */
type Test1 = Assert<IsUnique<typeof REGULAR>> // error
type Test2 = Assert<IsUnique<
    & typeof REGULAR
    & { readonly tag: unique symbol }
>> // error

type Test3 = Assert<IsUnique<symbol>> // error
type Test4 = Assert<IsUnique<any>> // error
type Test5 = Assert<IsUnique<unknown>> // error
type Test6 = Assert<IsUnique<never>> // error

export type MARKED<C, M extends symbol> =
    IsUnique<M> extends true ? C & {
        readonly m: M;
    } : never

Playground
Seems to be it works now. Please keep in mind, above constraint is indirect. I'd say that it is a duck constraint.
If something is:

*

*a subtype of symbol

*has same keys as a symbol

*is not never

*symbol is not assignable to passed type but passed type is assignable to symbol

then, probably we have a deal with unique symbol.
Please add more tests.
Please trust above code only for 90%.

A: This is not a direct answer to the question formulated in the subject but to the targeted problem of getting nominal typing in typescript without the danger of  intricate name collisions that may happen with "brand" type nominal typing as described in this answer.
Suppose we have
class Foo { ... }

yet under certain circumstances, in particular after verifying some constraint of a Foo object, we want to carry along the information that the constraint holds. We use the following:
const VERIFIED_FOO = Symbol();
type VerifiedFoo = Foo & {
  readonly [VERIFIED_FOO]: undefined;
}
isFoo(foo: Foo) foo is VerifiedFoo {
  return elaborateFooVerificationPassed(foo);
}

By using a Symbol as the property name in the attached marker type, we should be safe from spurious name clashes. Further, a VerifiedFoo can be used everywhere a Foo can be used, but not the other way round. Finally, after using the type guard isFoo, the compiler knows it and helps to not confuse the two types. This can be used, for example, like:
handle(foo: Foo): void {
  if (isFoo(foo)) {
    // Here we know it is a VerifiedFoo, not just Foo
    // and in particular the compiler knows it too.
    doHandle(foo);
  }
}
private doHandle(foo: VerifiedFoo): void {
  // no need to handle special cases for non verified foo objects
}


text:
Q: REGEX two decimals required I have a regex ^\d+(\.\d{2})?$
Here, the two decimals are optional. I want the decimals to be mandatory. Any suggestions?

A: Just remove the ? at the end. And the grouping is then also not needed.
^\d+\.\d{2}$

see msdn about quantifiers


text:
Q: UIsegmentedControl title appearance
HI, i set my uisegmentedcontrol's width manually, but when the width gets too small, the words becomes ...
Is that anyway that it won't behave in this way? Instead, i just want to show the text just like the picture shown below.

A: I'd suggest changing your design here and going for a different approach.
The design that you seem to want makes readability pretty much impossible.
Plus, what happens if I'm using your app and add another "Active Project". What happens if I have 10 active projects?
Take the fact that the UI does not work as a sign that you are using the wrong UI for the problem you are trying solve.
I'd suggest possibly just have the current project title here with a button to maybe present a list of projects to switch to... or something.

A: The text has been truncated. If you want it to fit your segment, you need to update the segment control size based on the text length. If you just want to get rid of truncation, you can use the following snippet. However, it's not recommended, as later Apple might change the UISegmentControl hierarchy.
    for item in segmentedControl.subviews {
        for subview in item.subviews {
            if subview.isKind(of: UILabel.self) {
                let _label = subview as! UILabel
                _label.numberOfLines = 0
                _label.lineBreakMode = .byWordWrapping
            }
        }
    }


text:
Q: Django: how to interact with tables from MySQL I am trying to write a very simple web application, which could show tables from existing MySQL databases, and authorized users could insert values and delete rows as well. But I am new to Django and do not know how to start the project.
I also tried two tutorials: https://realpython.com/learn/start-django/#django-18 http://tutorial.djangogirls.org/en/index.html
Basically, I hope Django could show databases'name and tables name automatically. Besides, after clicking one table, users could query the table.
Any thoughts? Thanks.

A: This is a perfect tutorial for beginners ..
  Tutorial

A: Using an existing database with Django is no problem. Please have a look at the docs how exactly integrating legacy databases works.
https://docs.djangoproject.com/en/1.8/howto/legacy-databases/

A: Read the manuals carefully. They are the best!
https://docs.djangoproject.com/en/1.8/intro/

A: maybe this will help there are a lot of tutorials in the internet
https://realpython.com/learn/start-django/


text:
Q: Wordpress issue - could not get domain name I'm trying to test a Wordpress configuration I'm building in Chef with Test Kitchen. The server is coming up with a temporary ip - this seems to have something to do with the error I'm getting when I try to visit the site in a browser:
Could not get domain name.10.10.0.1

No errors in the httpd error.log. Any ideas on how to get past this? I tried faking the hostname in /etc/hosts for the main ip but that did not work.


text:
Q: re-using Vuetify theme colors Vuetify provides a configurable theme which defines a set of color that may be overridden when constructing the Vuetify object, e.g.
const vuetify = new Vuetify({
  theme: {
    themes: {
      light: {
        primary: '#3f51b5',
        secondary: '#b0bec5',
        error: '#b71c1c',
      }
    }
  }
})

In the example above, I've overridden 3 of the theme colors. How can I use these theme colors in my own components, e.g. if I want to set the background color of a div to match the primary color
<template>

</template>

In the example above I've hard-coded the primary color, but I assume Vuetify provides a way of avoiding this repetition, e.g. a SASS/SCSS variable?

A: If you don't need to support IE11 you can tell the theme system to use CSS custom properties instead:
new Vuetify({
  theme: {
    options: { customProperties: true },
  },
})

Then you can access the colors directly in your stylesheet:
#container {
  background-color: var(--v-primary-base);
}

https://vuetifyjs.com/en/features/theme/#custom-properties

Vuetify 3 doesn't support IE so this is always enabled, and the custom properties are r,g,b lists so you need to use rgb() or rgba() to access them:
#container {
  background-color: rgb(var(--v-theme-primary));
  color: rgba(var(--v-theme-on-primary), 0.8);
}

A: You can simply achieve that by applying the CSS as per your custom theme. Please follow the below steps.
Add a wrapper element <v-app> around your component content and then by using computed property get the theme colors.
<v-app :style="getColors">

computed: {
   getColors () {
      let themeColors = {}
      Object.keys(this.$vuetify.theme.themes.light).forEach((color) => {
        themeColors[`--v-${color}`] = this.$vuetify.theme.themes.light[color]
      })
      return themeColors;
   }
}

And then in CSS, You can achieve like this :
#container {
  color: var(--v-primary);
}

Live demo :

new Vue({
  el: "#app",
  opts: {
      theme: {
          themes: {
              light: {
                  primary: '#3f51b5',
                  secondary: '#b0bec5',
                  error: '#b71c1c',
              }
          }
      }
  },
  vuetify: new Vuetify(this.opts),
  computed: {
      getColors () {
          let themeColors = {}
          Object.keys(this.$vuetify.theme.themes.light).forEach((color) => {
              themeColors[`--v-${color}`] = this.$vuetify.theme.themes.light[color]
          })
          return themeColors
      }
  }
});
.container {
    color: var(--v-primary);
  }

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vuetify@2.x/dist/vuetify.min.css"/>

    <v-app :style="getColors">

Hello

    </v-app>


text:
Q: Cinema4D: How do I import/include/embed a user python script into another? I would like to embed a script file full of often used defs into other script files.
For example, I would like test.py to load the contents of defs.py (which is in the same folder) into itself in line.
When I try adding
import defs

into the body inside test.py I get error "No module named defs"

A: For anybody else facing this issue. Just add this on top of your script:
import sys
sys.path.append(os.path.dirname(__file__))


text:
Q: What is the correct way to override an interface method to ensure that it can only be used on objects of identical types? I am creating a Matrix class in Java to use in a linear algebra program. Right now it holds doubles, but I want to abstract it.
I've created an interface called MatrixElement, which will contain add, multiply, divide, and any other arithmetic methods needed to perform these matrix operations.
Here is a snippet of the Matrix class:
public class Matrix<T extends MatrixElement> {

    private ArrayList<ArrayList<T>> rows;

    public Matrix(int numRows, int numCols) {

        if (numRows <= 0) {
            throw new IllegalArgumentException("Matrix must have at least one row.");
        }

        if (numCols <= 0) {
            throw new IllegalArgumentException("Matrix must have at least one column.");
        }

        this.rows = new ArrayList<ArrayList<T>>();

        for (int r = 0; r < numRows; r++) {
            ArrayList<T> row = new ArrayList<T>();
            for (int c = 0; c < numCols; c++) {
                row.add(new T());
            }
            this.rows.add(row);
        }

    }

     /* lots of methods omitted */

     public static Matrix sum(Matrix a, Matrix b) {

        if (a.numRows() != b.numRows() || a.numCols() != b.numCols()) {
            throw new IllegalArgumentException("Matrices must be the same size.");
        }

        Matrix sum = new Matrix(a.numRows(), b.numCols());

        for (int r = 1; r <= b.numRows(); r++) {
            for (int c = 1; c <= b.numCols(); c++) {
                sum.setEntry(r, c, a.getEntry(r, c).add(b.getEntry(r, c)));
            }
        }

        return sum;

    }

    public Matrix add(Matrix matrix) {
        return Matrix.sum(this, matrix);
    }

}

Here is how methods are declared in MatrixElement
public interface MatrixElement {
    public MatrixElement add(MatrixElement e);
}

Finally, here's a sample class I've created that implements this interface:
public class Fraction implements MatrixElement {

    private BigInteger numerator;
    private BigInteger denominator;

    public Fraction(int num, int denom) {
        numerator = BigInteger.valueOf(num);
        denominator = BigInteger.valueOf(denom);
    }

    @Override
    public Fraction add(MatrixElement e) {

        Fraction f;

        try {
            f = (Fraction) e;
        } catch (ClassCastException cce) {
            throw new IllegalMatrixOperationException("Cannot add " + this.getClass().toString() + " and " + e.getClass().toString());
        }

        /* addition code omitted */

        return this;

    }
}

The main idea here is this:

*

*Matrix objects can hold instances of any one class that implements the interface MatrixElement

*MatrixElement contains arithmetic methods necessary for matrix manipulation, such as add

*The kicker: Classes that implement MatrixElement can only use its methods on other instances of the same class. For example, Fraction can only be added to other Fraction instances. Two classes may implement MatrixElement, but they shouldn't necessarily be able to add to one another.
I ran this design by another programmer and was told that casting like this is bad practice. If so, what is the correct way to do this? How can I use an interface to 'group' classes that have similar functionality to be used in parameterization, but then restrict which children of said interface can be used in the children's methods?

A: There are two requirements for generics in the post above.

Requirement 1: Elements that can be added to other elements of the same type

You would like to impose a contract on certain data types so that instances of those types can be added to other instances of the same type, and same type only. The intention is to support the following kinds of operations:
int + int = int
long + long = long
real fraction + real fraction = real fraction
complex number + complex number = complex number

This contract can be expressed as follows:
public interface MatrixElement<T> {
  T add(T e);
}

In simple language, this contract says that a MatrixElement is a type whose instances can be added to other instances of the same type to yield yet another instance of the same type, which is what was required.

Requirement 2: Two-dimensional matrices of elements, all of the same type can be added to other two-dimensional matrices of elements of the same type and same dimensions

This contract can be expressed as:
public class Matrix<T extends MatrixElement<T>> {
  public Matrix<T> add (Matrix<T> another) { ... }
}

This contract says that a Matrix consists of elements of type MatrixElement, such that all elements are of the same type. The Matrix also allows addition with another Matrix, provided both have elements of the same type. The result is returned as a third Matrix with elements of the same type.

A sample is available on Github.


text:
Q: Get count of items in a Grouped View using JavaScript is there a way to get the count of items in a Grouped View via Javascript? The grouped view already has a count, but want to pass along that count to another object (a chart) and can't get past the list items.

A: You could go CSR/JSLink and count before the HTML is displayed
Or once the page has loaded analyze the HTML
[].map.call(
  document.querySelectorAll("tbody[id^='titl']")
  ,function(body){
    console.log(body.innerText);
    var span=body.querySelector("span[style*='lighter']")
    var label=span.innerHTML;
    var value=Number(label.split('')[1]);
    console.info(value);
});


text:
Q: how to dynamically set the value of a cell in gridview based on selection of dropdownlist? I have a gridview with a dropdown and textbox in footer. My dropdownlist is bounded to a table named Tax. Requirement is to set the value of textbox to corresponding to selection of the tax name in dropdown. I've successfully binded the dropdownlist but can't get value of textbox to be set to its related value.
DropDownList ddlTax = (DropDownList)TaxGV.FooterRow.FindControl("Footer_ddlTaxName");

        //fill the dropdown
        FillDropDownListTaxName(ddlTax);

public void FillDropDownListTaxName(DropDownList ddl)
    {
        string str = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
        SqlConnection con = new SqlConnection(str);
        con.Open();
        SqlCommand cmd = new SqlCommand("Select Id, Name from Taxes", con);
        cmd.CommandType = CommandType.Text;
        ddl.DataSource = cmd.ExecuteReader();
        ddl.DataTextField = "Name";
        ddl.DataValueField = "Id";
        ddl.DataBind();
        ddl.Items.Insert(0, new ListItem("--Select--", "0"));
    }

Now just remaining question is how to show related value in footer textbox, when a value is selected in dropdown.
Can Anybody help;

A: I have worked out a solution after going thorougly in comments. Thanks to Chetan Ranpariya. Here is my findings for the answer.
protected void Footer_ddlTaxName_SelectedIndexChanged(object sender, EventArgs e)
    {
        string str = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
        SqlConnection con = new SqlConnection(str);
        con.Open();
        SqlCommand cmd = new SqlCommand("Select Value from Taxes where Id=@TaxId", con);
        DropDownList ddl_Tax = (DropDownList)TaxGV.FooterRow.FindControl("Footer_ddlTaxName");
        cmd.Parameters.AddWithValue("@TaxId", ddl_Tax.SelectedValue);
        SqlDataReader reader = cmd.ExecuteReader();
        TextBox tb_Value = (TextBox)TaxGV.FooterRow.FindControl("Footer_txtValue");
        if(reader.Read())
        {
            tb_Value.Text = Convert.ToString(reader["Value"]);
        }
    }


text:
Q: Spark: load csv file with a different schema I have a csv file like this :
product price,product origin,phone number
20,US,200200

I would like to load the csv file using a new schema so that my dataset should look like this:
|price | origin | number |
|20    | US     | 200200 |

I tried to create a schema using structfield :
sparkSession.read().format("csv")
                .option("header", "false")
                .option("delimiter", ",")
                .schema(myScheme).load(csv)

but what I got is like this:
|price     | origin | number |
|200200    | US     | 20     |

What is the correct way to load the csv with a new scheme with correct column orders ?

A: Using a csv file with the exact contents that you posted in your question:
product price,product origin,phone number
20,US,200200

You should be able to  create a schema by using types from org.apache.spark.sql.types._. You could do something like this:
import org.apache.spark.sql.types._
val mySchema = new StructType()
  .add("product price", IntegerType)
  .add("product origin", StringType)
  .add("phone number", StringType)

val df = spark
  .read
  .option("header", "true")
  .schema(mySchema)
  .csv("./simpleCSV.csv")

df.show
+-------------+--------------+------------+
|product price|product origin|phone number|
+-------------+--------------+------------+
|           20|            US|      200200|
+-------------+--------------+------------+

df.printSchema
root
 |-- product price: integer (nullable = true)
 |-- product origin: string (nullable = true)
 |-- phone number: string (nullable = true)

Hope this helps!


text:
Q: 2 dummy variables in a dataframe I have a dataframe x_0 of 5 numeric variables and 2 categorical variables:
['v1',
'v2',
'v3',
'v4',
'v5',
'v6',
'v7']
I want to convert v6 and v7 to dummy variables. I have tried with the following code but I receive a traceback:
x = pd.concat([x_0['v1', 'v2', 'v3', 'v4', 'v5'], pd.get_dummies(x_0['v6', 'v7'])], axis = 1)

A: Use double [] for selecting by multiple columns names:
x = pd.concat([x_0[['v1', 'v2', 'v3', 'v4', 'v5']],
               pd.get_dummies(x_0[['v6', 'v7']])], axis = 1)


text:
Q: How to convert string to number in Typescript? I have a const inherited from another component that looking at its typeof, is a string.
In javascript my code looks like this:
Here I display a number, eg 24%
{parseInt(progression * 100, 10)}%

Here I display a progress bar
<Bar style={{ width: `${progression * 100}%` }} />

I'm trying to change this code now to typescript and I did the following:
I declared the typing:
interface ProgressionProps {
  progression: string;
}

Here where I should display the %, I put it like this:
{Number(progression * 100, 10)}%

But I have the error:

The left-hand side of an arithmetic operation must be of type 'any',
'number', 'bigint' or an enum type.ts

And also in the other code:
<Bar style={{ width: `${progression * 100}%` }} />

I got the same error:

The left-hand side of an arithmetic operation must be of type 'any',
'number', 'bigint' or an enum type.ts

What am I doing wrong? What is the way to pass this code correctly to typescript?
Thanks if can someone help me!!

A: You need to parse the string to a number before you multiply it:
{Number(progression) * 100}%

And
<Bar style={{ width: `${Number(progression) * 100}%` }} />


text:
Q: How to return boost::fusion::vector elements to add to a std::array>? I have a std::array and a boost::fusion::vector<X, Y> which I want to pass in to func1(). This function will add a boost::fusion::vector<X, Y> instance to each std::array element.
I have to use fusion::fold() so that I can add the correct number of elements to the fusion::vector<X,Y>, right?
So I currently have something like this:
void func1(){
    boost::fusion::vector<X,Y> my_vec;
    std::array<boost::fusion::vector<X,Y> > my_array[10];
    func2(my_vec, my_array);
}

void func2(boost::fusion::vector<X,Y> my_vec, std::array<boost::fusion::vector<X,Y> > my_array){

    //THIS IS THE PART I AM UNSURE ABOUT
    for(int k=0; k<10; k++){
        //The first two parameters aren't so important- just included to show the idea
        my_array[k] = boost::fusion::fold(my_vec, 1, some_struct);
    }
}

//This part is irrelevant
struct some_struct
{
    typedef int result_type;

    template<typename T>
    int operator()(int x, T& t) const
    {
        t = something(x);
        //Not sure if this part needs to return a boost::fusion::vector<X, Y>
        return x;
    }
};

The part I am unsure about is how to use the signature of my_vec in order to create multiple boost::fusion::vector<X,Y> instances and return them back so that I can add to the array in func2().
Could somebody please advise?
EDIT - Just spotted I got the first parameter for fold() wrong, have amended my question.

A: I'm not sure I understood your question really well so first let's explain what fold is to try to clarify.
In general (not just for fusion) "folding" a function taking two parameters is applying it to each and every element of the vector and to the result of the application of the function to the previous element of the vector. The first element is being given the initial value.
So if I define the function to fold as A f(A, B), the folding of this function will be equivalent to (for 4 elements):
f(f(f(f(A_initial_value, B_0), B_1), B_2), B_3);

(capitalized prefix is there just to enforce type)
Now, more precisely fusion fold. It will fold the function on all the elements inside the boost::fusion::vector<>. As a boost::fusion::vector<X, Y> is equivalent to a std::tuple<X,Y> it will call f on different types:
A_final_value = f(A_initial_value, X_value), Y_value);

So, when you do:
my_array[k] = boost::fusion::fold(my_vec, 1, some_struct);

my_array[k] will receive an numeric value, and that won't compile since you've defined it as fusion::vector<X,Y>
So having trying to clarify fold, I would say no to your question, but I admit that I do not understand what you mean by "add the correct number of elements to the fusion::vector<X,Y>".
EDIT: Updating according what've been said in comment.
The goal isto generate a fibonacci sequence in your std::array<fusion::vector<int, int, int, int>> such as walking each vector of the array will give the fibonacci in the right order.
Using fusion you have to pass a state while iterating through the elements of the vector and so foldwas a good choice.
Here is my suggestion for this (but starting the fibonacci sequence at the second element and not the first, cause I didn't bother to handle the special case... sorry :) ):
template <typename Value>
struct Generator
{
  // Easier to read and mandatory for fold
  typedef typename std::tuple<Value, Value> result_type;

  // The function that generate the fibonacci and update the Value
  result_type operator()(result_type previous, Value& elem) const
  {
    elem = std::get<0>(previous) + std::get<1>(previous);
    return std::make_tuple(std::get<1>(previous), elem);
  }
};

// Use template to be a bit more generic on array size and vector type
template <typename Vector, size_t array_size, typename Value>
void func2(std::array<Vector, array_size>& array, std::tuple<Value, Value> init)
{
  // The state that will be fed across the fold function
  auto previous = init;
  for (auto& vect: array)
  {
    // Generate the fibonnaci value for every element of the vector starting
    // from where the state is. The return value of fold is the new state
    previous = boost::fusion::fold(vect, previous, Generator<Value>());
  }
}

// Tool to print the vector
struct Printer
{
  template <typename Elem>
  void operator()(const Elem& elem) const
  {
    std::cout << elem << std::endl;
  }
};

// Use template to be a bit more generic on array size and vector type
template <typename Vector, size_t array_size, typename Value>
void func1(std::tuple<Value, Value> init)
{
  // Create the vector
  std::array<Vector, array_size> array;

  // FIll it with fibonacci
  func2(array, init);

  // Print it
  for (auto vect: array)
  {
    boost::fusion::for_each(vect, Printer());
  }
}

http://rextester.com/XCXYX58360


text:
Q: SQL query not displaying the first result? I am trying to dynamically create a navigation menu in my php page.
I have a query to create a list of the active pages but for some reason the first result never shows
$menu = mysql_query("SELECT link FROM myTable WHERE active_page='y' ORDER BY menu_order");
$menulist = mysql_fetch_array($menu);

  while($menulist = mysql_fetch_array($menu))
  {
  $themenu = $themenu . "
" . $menulist['link'] . "
";
  }

  $echo $themenu;

returns
item 2
item 3
item 4
...
Any ideas why this might be

A: Remove
$menulist = mysql_fetch_array($menu);

This extraneous call is pulling the first record, but you're not doing anything with it as you are in your where loop.

A: It doesn't display the first item because you are fetching twice before displaying anything...
$menu = mysql_query("SELECT link FROM myTable WHERE active_page='y' ORDER BY menu_order");

  while($menulist = mysql_fetch_array($menu))
  {
  $themenu = $themenu . "
" . $menulist['link'] . "
";
  }

  $echo $themenu;

A: You should drop
$menulist = mysql_fetch_array($menu);

This moves the cursor one step forward and efficently skips the first row.
You should also drop the $ before your echo.

A: It's skipping the 1st element because you are calling mysql_fetch_array($menu) before the while loop.


text:
Q: Как правильно вернуть указатель файла на позицию назад? Когда я делал парсинг, я использовал fseek(f, -1, SEEK_CUR);,чтобы возвращаться на позицию назад.И в Ubuntu на gcc всё работало,но теперь в Windows на Visual Studio он работает не так как я планировал.
В этом ответе , мне подсказали, что "что такой способ позиционирования не обязан поддерживаться в текстовых потоках.". Как же тогда верно вернуться на позицию в файле назад (или на указанное количество шагов(байт) назад). Просто иначе придётся переделывать парсинг.


text:
Q: Sending coordinates from google maps to other application I would like to send coordinates (lon & lat) from Google Maps to my application.
I was trying to do this by using share i Google Maps and teh pointing my application.
I know that by using share GM sens text with and address and link to map.
 Since there are no coordinates in open text, I was trying to get them from link.
Link is in shortUrl version (eg. goo.gl/maps/n8HffcEcMeG2) by I was able to transform it to longUrl version. But in this version there are still no lon & lat visible.
Howevwer when I click this link (short or long version) and map is opened in the browser the link changes after ~1sec to antother (3rd) version that contains lon and lat.
Any suggestions how I can the coordinates from shortUrl / longUrl ?
Or are there any other methods to send coordinates form Google Maps to other application?


text:
Q: Connection to some websites fail on fresh installation I have recently installed Ubuntu 20.04.3 LTS but now some websites are unreachable. I first noticed the problem during my Android Studio install when the Android SDK add-on list couldn't be reached but later I while researching noticed that while some websites like google.com would load, others like stackoverflow and askubuntu.com wouldn't.
The PC is connected via Ethernet into a Switch into a WiFi Repeater which admittedly is kind of a wonky setup but it has never caused any issues while Windows 7 was installed.
I have set the IPv4 DNS to 8.8.8.8 in case it was connecting to a bad DNS Server but left the setting for IPv6 on automatic.
I'd appreciate any help. If you need any more information I'd obviously be glad to provide that.


text:
Q: set the padding of a text field using swift in xcode How to create some space at the beginning of a text field using swift?
I looked at the post
padding of text field
I don't understand what the subclass is doing and how do I use that class to padding.
Thank you very much

A: Based on @Jorge Casariego's answer I came up with this solution.
You can set PaddedTextField class and the desired padding through the Interface Builder!
class PaddedTextField: UITextField {

    @IBInspectable var padding: CGFloat = 0

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + padding, y: bounds.origin.y, width: bounds.width - padding * 2, height: bounds.height)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + padding, y: bounds.origin.y, width: bounds.width - padding * 2, height: bounds.height)
    }
}

A: full code sample:
make sure your TextField points to RoundedTextField via Story board
import UIKit

class RoundedTextField: UITextField {

    override func awakeFromNib() {
        // add rounded corner
        self.layer.cornerRadius = 15.0
        self.clipsToBounds = false

        super.awakeFromNib()
    }

    // For the padding from the left
    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + 15.0, y: bounds.origin.y, width: bounds.width, height: bounds.height)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + 15.0, y: bounds.origin.y, width: bounds.width, height: bounds.height)
    }
}

A: https://stackoverflow.com/a/27066764/846780
This answer is very clear,

*

*If you subclass UITextField you can override textRectForBounds, editingRectForBounds and placeholderRectForBounds. These methods just allow you to add a rect (frame) to your textfield's label.

*newBounds method create the rect (frame) that will be added to textfield's label.

*Finally your padding is: let padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5);

*Now you have a custom UITextField that has a custom padding.

*If you create your new subClass like this class MyTextField: UITextField for example, you only need to change the class of the UITextField that you've added into IB file.

A: Complementing the answer of klevison-matias this is the code I use when I want to add a padding to my TextField in Swift 3
//UITextField : override textRect, editingRect
class LeftPaddedTextField: UITextField {

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width, height: bounds.height)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return CGRect(x: bounds.origin.x + 10, y: bounds.origin.y, width: bounds.width, height: bounds.height)
    }

}

Then in my TextField I use in this way:
let emailTextField: LeftPaddedTextField = {
    let textField = LeftPaddedTextField()
    textField.placeholder = "Enter email"
    textField.layer.borderColor = UIColor.lightGray.cgColor
    textField.layer.borderWidth = 1
    textField.keyboardType = .emailAddress
    return textField
}()

let passwordTextField: LeftPaddedTextField = {
    let textField = LeftPaddedTextField()
    textField.placeholder = "Enter password"
    textField.layer.borderColor = UIColor.lightGray.cgColor
    textField.layer.borderWidth = 1
    textField.isSecureTextEntry = true
    return textField
}()

A: Create TextField outlet and use following code. Say "nameTextField" has to add padding.
let paddingView = UIView(frame: CGRectMake(x: 0, y: 0, width: 30, height: 30))
nameTextField.leftView = paddingView
nameTextField.leftViewMode = .always
nameTextField.placeholder = "Enter Name"

You can add Image in paddingView.


text:
Q: jquery object containing all element definitions Not sure if my title explains what I am trying to do very well, but is it possible to retrieve an object of jquery select definitions including any definitions that were not present in the DOM when the page was loaded so that I can call the object or read it's properties again if required ?

    $('#div1').on('click',function(){
        do something...
    })

    $('#div2').on('click',function(){
        do something...
    }).css('background','red').data('xxx','yyy').attr({class:'myclass'})

    $('#div3').on('click',function(){
        do something...
    })

    setTimeout(function(){
        console.log(jqueryArray['#div2].onClick)
        console.log(jqueryArray['#div2].attr())
        console.log(jqueryArray['#div2].css())
    },2000)

In this example, div 1 and 3 existed, but div2 was not present when the page was loaded.
Is there an internal jquery array or object that contains all of the selectors that were parsed during the loading of the page that can be accessed after the page was loaded ?

A: Your looking for a delegate.
$(parentSelector).on(event, childSelector, eventHandler);

This functions much like a normal event handler, except it is bound to a parent element that already exists.  Events from the children bubble up and the parent evaluates the child selector to see if they match.  If so it applies the handler against it.
Since it works off of bubbled up events, it does not care when the children were created.  Only that it is getting events.


text:
Q: Angular 5 Modal close programmatically I am using angular 5

Replace Note

Please upload a pdf file you want to replace with the existing one. This will replace {{notesToBeRelaced?.note?.title}}

This is a modal. After completing the task the modal do, I want to close it programmatically with typescript.
I am trying to get a reference of the modal like :

 @ViewChild('noteModal')  noteModal: ElementRef;

After binding data I am trying to close or hide the modal :

 onReplaceNote(event) {
    this.onReplaceDataBind(JSON.parse(event.xhr.response));
  }
 onReplaceDataBind(data) {
   this.uiNotes.forEach(uiNote => {
     if (uiNote.note.itemId == data.itemId) {
       uiNote.note.title = data.title;
     }
   });
   this.noteModal.nativeElement.hide();
 }

At a point I want to close / hide the modal. like I have tried in this.noteModal.nativeElement.hide();

A: I have already done before let try this just for suggestion,
Html File, Change your code like this,

Typescript,
@ViewChild('closeModal') private closeModal: ElementRef;
public hideModel() {
        this.closeModal.nativeElement.click();
}

I hope its solve your problem, If any error please let me know.
Thanks,
Muthu

A: You can close the modal using attr.data-dismiss in a button for example: (Tested on Angular 10)
<button type="button" class="btn btn-block btn-primary" [attr.data-dismiss]="<expression>" id="saveButton" (click)="action()">

Where < expression > is the expression you want to evaluate and action() is the method or function you want to call, for example, to validate if the form is valid, using reactive forms:
<button type="button" class="btn btn-block btn-primary" [attr.data-dismiss]="Form.valid ? 'modal' : null" id="saveButton" (click)="saveMyModalInfo()">

This will evaluate if the form is valid, if it isn't data-dismiss will "point" to null, otherwise it will "point" to the modal.


text:
Q: Magento - Loop through all products in category, change value and save I need to loop through all the products in a particular category, change a custom attribute and then save each product.
Currently i have:
$_category = Mage::getModel('catalog/category')->load($_POST['id']);
$all_products = $_category->getProductCollection();

foreach ($all_products as $product) {
    $product = Mage::getModel('catalog/product')->load($product->getId());
    $product->setCustomAttribute(xxxx);
    $product->save();
}

Is this best practice and can it be improved for performance? The collections average around 15-20 products in each and i am getting a very slow loadtime or even the script timing out.
I've used set_time_limit(0); to try and force it through but i imagine i can improve my code to stop me having to do this? Eventually the collections may have over 100-200 products each so need to find a good performance now

A: If you are doing a massive update of the same attribute and for the same value, consider trying updateAttributes:
// Iterate over the foreach and get all the product ids into an array
// $attr = array("attribute_code" => "attribute_value");
Mage::getSingleton("catalog/product_action")->updateAttributes($productIds, $attr, $storeId);

It should be much quicker.


text:
Q: regex - each digit equal to next or previous I need a regex code (for egrep) to match only lines where a digit is equal to the previous one or the next one.
ex: 66688833777443344477774488555
but not: 262227723336339337775533777
Any help please?

A: Think about this for a while. In essence your problem means: Match a number where each digit is immediately repeated at least once.
Now if you know that ([0-9])\1+ will match one such group of digits (like 22 or 777), then you're halfway there.
The next step is to match one or more of these groups. For that, you need another + quantifier plus another pair of parentheses that encloses the to-be-repeated group:
(([0-9])\2+)+

Note that the backreference changed to \2 because ([0-9]) is now the second (inner) group.
Finally, to make sure that the entire line matches, we need to use some anchors:
^(([0-9])\2+)+$

A: A solution using look around ^(?:(\d)(?:(?=\1)|(?<=\1{2})))+$ :
^    # start of input
  (?:    # start not capturing group for repetition for each decimal
    (\d)    # any decimal captured in a group
    (?:
      (?=\1)     # positif look ahead for an ocurrence of the capture in the group
      |            # or
      (?<=\1{2}) # positif look behind for the matched decimal and the same decimal one position before
     )
  )+     # end of repetition group for each decimal
$     #end of input


text:
Q: R tidymodels / VIP variable importance determination Via tidymodels and the vip package in R, I computed the variable importance. Code wise it would look like this:
rf_vi_fit %>%
pull_workflow_fit() %>%
vip(geom = "point") +
labs(title = "Random forest variable importance")

Visually it would look something like this:

However, what does the variable improtance actually entail? The variable importance can be based on multiple metrics, such as the gain in R-squared or the gini-loss, but I am unsure where the variable importance from the vip is based on. My other predictions has a variable importance of values around 3 to 4 instead of 0.005 as in this model.
I could not find what the variable importance is based on in the vip() documentation either.

A: The answer to you inquiry lies in various sections in the vip documentation https://cran.r-project.org/web/packages/vip/vip.pdf.
The vip() function is a wrapper around vi() used to plot the variable importance scores. In the vip() documentation, the ... argument is "Additional optional arguments to be passed on to vi()".
In the vi() function, there is an argument called method.

method = c("model", "firm", "permute", "shap")
Character  string  specifying  the  type  of  variable  importance  (VI)  to  compute.  Current  options  are:
"model" (the  default),  for  model-specific  VI  scores  (see vi_model() for details).
"firm", for variance-based VI scores (see vi_firm() for
details).
"permute", for permutation-based VI scores (see vi_permute for details).
"shap", for Shapley-based VI scores.
For more details on the variance-based methods, see Greenwell et al. (2018) and Scholbeck et al. (2019).

Then, if you check the documentation of vi_models(), it describes in details the model-specific VI score for each type of model. Below is an excerpt describing RandomForest model specific importance.

Random forests typically provide two measures of variable importance.
The first measure is computed from permuting out-of-bag (OOB) data: for each tree, the prediction error on the OOB portion of the data is recorded (error rate for classification and MSE for regression).  Then the same is done after permuting each predictor variable.  The difference between the two are then averaged over all trees in the forest, and normalized by the standard deviation of the differences.  If the standard deviation of the differences is equal to 0 for a variable, the division is not done (but the average is almost always equal to 0 in that case). See importance for details, including additional arguments that can be passed via the ... argument.
The second measure is the total decrease in node impurities from splitting on the variable, averaged over all trees.  For classification, the node impurity is measured by the Gini index. For regression, it is measured by residual sum of squares. See importance for details.


text:
Q: Is there any good way to keep CodeMirror from initializing as a white box I'm using Codemirror 5.62.3 and the 'monokai' theme ( with a dark background ). When I reload the page, the CodeMirror is initialized as a small white box before the styling takes effect. Is there any good way to avoid this behaviour? I've tried only rendering the Codemirror once it's value has been loaded, however there is still a brief period where the box is white

A: Not a perfect solution, but fixed by setting all textareas to:
textarea {
    outline:none;
    background: rgb(0,0,0,0);
    border: none;
    resize: none;
}


text:
Q: Barycenter of a triangle Let $A$, $B$, and $C$ denote vertices of a triangle in the plane. Let $O$ be some point in the plane. Prove that $OM = \frac{1}{3}(OA+OB+OC)$, where $M$ denotes the barycenter of the triangle, and all objects in the equation are geometrical vectors.
I have been trying to prove this statement for hours now. I typically end up with statements like $AM=AM$ or $0=0$ and am really struggling. I can prove this using the center of mass concept in physics, where each point is assigned the same weight, but I cannot prove it purely geometrically. Also, I can prove geometrically that $OM = \frac{1}{2}(OA+OB)$ for a line $AB$ with midpoint $M$, but the 2D triangle seems to be a bit tougher.

A: The barycenter, or centroid, of a triangle happens to be the mean of the three vertices, but the definition is the center of mass of the whole triangle.
To see why the barycenter is the mean of the vertices, consider a triangle with two vertices on the $x$-axis:

The mean of the $y$-position would be
$$
\frac{\int_0^1\overbrace{{\ \ \ \ }th{\ \ \ \ }}^y\,\overbrace{(1-t)b\,h\,\mathrm{d}t}^{\mathrm{d}A}}{\int_0^1\underbrace{(1-t)b\,h\,\mathrm{d}t}_{\mathrm{d}A}}
=\frac{bh^2\int_0^1t(1-t)\,\mathrm{d}t}{bh\int_0^1(1-t)\,\mathrm{d}t}
=\frac13h
$$
That is, the distance from the side opposite each vertex to the barycenter is $\frac13$ the distance of the vertex from the side opposite.
Thus, the barycentric coordinates of the center of mass would be
$$
M=\frac13A+\frac13B+\frac13C
$$
Writing this as offsets from a point $O$, we get
$$
OM=\frac13OA+\frac13OB+\frac13OC
$$

A: Consider using barycentric coordinates. For simplicity, set a coordinate system so that point $A$ is located at the origin $r_1 = (0,0)$, point $B$ is located at some point $r_2 = (a,0)$ on the x-axis, and $C$ is at some point $C = (b,c)$. The point $O$, whose corresponding vector I denote by $v$, is expressible as the linear combination
$$v =\lambda_2 r_2 + \lambda_3 r_3,$$
where $\lambda_i \in \mathbb{R}$, and $\lambda_2 + \lambda_3 = 1.$ Note that the centroid point $M$, denoted by $u$, has coordinates
$$ u = \frac{1}{3} r_2 + \frac{1}{3} r_3.$$
So
$$OM = ||v - u||$$
Meanwhile,
$$OA + OB + OC = || v|| +|| v - r_2|| + ||v - r_3 ||$$
Expanding these out explicitly should lead you to the desired identity.


text:
Q: How to calculate acceleration vector of a moving object to intercept a stationary object The short version: I'm moving on a certain straight-line trajectory (two dimensions only, thank goodness), and I want to intercept a stationary object, with constraints on maximum acceleration and maximum speed. I can't seem to come up with a formula to do it.
The long version: I'm writing a computer game to entertain myself. I've figured out a lot of the equations I need, but this one is stumping me. I think it's a basic missile guidance problem in 2D with a stationary target, but I can't work it out, and I haven't found anything online to...guide me.
Edit: I forgot to mention, my game (so far) has no gravity and no friction. Not even real mass, just acceleration and velocity vectors.
I'm at point (Xs, Ys), moving at constant velocity (XVs, YVs), not accelerating. I want to go as quickly as possible to the target, which is stationary at point (Xb, Yb). I don't need to slow down on the approach, I just want my trajectory to intersect the point. And I don't have to be moving at top speed when I get there, I just want to get there. Here's how I'm thinking about the acceleration and speed constraints:
My max speed is MSs, and my max acceleration +/-MAs (I'm not sure how to express this properly. I mean, √(Xsa^2 + Ysa^2) <= MAs, where Xsa and Ysa are the x/y of my acceleration vector). Is there a way to calculate the necessary acceleration (Xsa, Ysa) to get me to my target? I mean, I'm sure there is a way, but I can't find it.
I found a paper on missile guidance with a couple of promising equations, but I'm not sure how to translate them into what I need. When I plug in the numbers I have, I get back nonsense, so I think I'm just misreading the equations. I have some algebra and trig, and some very basic calculus, but no physics background.
The simpler the answer, the better. Or if it's a complex answer, a link to an explanation of the math would be most helpful.


text:
Q: Retrieve ReportType in Visual Studio Code I am able to retrieve Email Templates in VIsual Studio Code as follows
  sfdx force:source:retrieve -m EmailTemplate:"[FolderName]/[EmailTemplateDeveloperName"

I have tried searching, but can't find the command to retrieve 'Custom Report Types'
I am not able to retrieve Custom Report Type from the org browser. I don't see the new Custom Report Types I created under the menu ReportType as seen in the screen shot.

A: This should do the trick
sfdx force:source:retrieve -m ReportType


text:
Q: Some products images doesn't show up because the URL is uppercase Since I've migrated Magento 1.7 to 1.9 some images doesn't show up. I found that the ones who doesn't show up are those with uppercase letters in url and when I manually insert lowercase letters, the image show up.
What can I do?
Thank you very much.

A: First, thanks to R.S to help me found the latest piece to resolve my puzzle.
To solve this problem:

*

*Make a php script to put your files in lowercase (sorry isn't recursive so you will need to make it folder by folder)

<?php

// The directory that contains the files that you want to rename to lowercase
$directory = "/public_html/media/catalog/product/s/t/";

$conn = ftp_connect("website");
ftp_login($conn,"username","password");

ftp_pasv($conn,true);

ftp_chdir($conn,$directory);
$dir = ftp_nlist($conn,".");

foreach($dir as $fsObject)
{
    if($fsObject != "." || $fsObject != "..")
    {
        if($fsObject != strtolower($fsObject))
        {
            ftp_rename($conn,$fsObject,strtolower($fsObject));
            echo strtolower($fsObject)."
";
        }
    }
}

ftp_close($conn);
echo $directory."
";
echo "Finish!";

?>

*Run these SQL queries:
update catalog_product_entity_media_gallery set value = lcase(value) where lcase(value) like '%.jpg';
update catalog_product_entity_varchar set set value = lcase(value) where lcase(value) like '%.jpg';

*Clean your images cache in Cache Management

A: My only advice is to double and triple check that you've flush all caches possible (Magento Cache, System Cache, and all 8 caches along with media cache). If you're using Zend Full Page cache, empty that too. Go to /var/cache and delete everything in here and do the same in var/sessions (if you're storing sessions in the file system and not the database).
If all of that fails try using a different browser that you have yet to view the site on. If that fails try uploading a fresh copy of your version of magento, replacing all the core files. I've seen crazy things happen with Magento and a upload of a clean copy fixes problems for whatever reason. Hope this helps!


text:
Q: Invalid CSRF Token via Postman I am using the csrf protection in my MEAN-Stack Application with the csurf node.js module.
As long as I send POST requests from my Angular frontend to the web service, everything works fine. But if I try to make a POST request via postman, I'll always face:

"ForbiddenError: invalid csrf token"

According to the first answer from How do I send spring csrf token from Postman rest client? i get the Token out of the cookie from the login request and set it to every post request.
Get requests are working fine.
I configured it as follows:
app.use(csrf({cookie: {path: '/', httpOnly: true}}));
app.use(function(req, res, next) {
    let token = req.csrfToken();
    res.cookie('XSRF-TOKEN', token);
    res.locals.csrfToken = token;
    next();
});

Best regards,
Tobias


text:
Q: How to solve the error: Cannot invoke initializer for type `......` with an argument list of type`...`? I need help with solving the error:

Cannot invoke initializer for type 'QuotesViewController.RandomItems' with an argument list of type '(items: [String], seen: Int)'

This is my code:
struct RandomItems: Codable
{
    var items : [String]
    var seen  = 0

    init(_ items:[String])
    { self.items = items }

    mutating func next() -> String
    {
        let index = Int(arc4random_uniform(UInt32(items.count - seen)))
        let item  = items.remove(at:index)
        items.append(item)
        seen = (seen + 1) % items.count
        return item
    }
    func toPropertyList() -> [String: Any] {
        return [
            "items": items,
            "seen": seen
        ]
    }

    }
}

extension QuotesViewController.RandomItems {
    init?(propertyList: [String: Any]) {
        return nil
    }
}

let a = QuotesViewController.RandomItems(items: ["hello"], seen: 2) //<-- Error
let data: Data = try! JSONEncoder().encode(a)
let b = try! JSONDecoder().decode(QuotesViewController.RandomItems.self, from: data)

A: This line
let a = QuotesViewController.RandomItems(items: ["hello"], seen: 2) //<-- Error

invokes an initialiser that does not exist. Create one like this:
init(items:[String], seen: Int)
{
    self.items = items
    self.seen = seen
}

For good measure, change the existing initialiser to
init(_ items: [String])
{
    self.init(items: items, seen: 0)
}

so that, if you need to add extra stuff to the initialisers, you only need to do it in one place.
Or just have one initialiser
init(items:[String], seen: Int = 0)
{
    self.items = items
    self.seen = seen
}


text:
Q: Toolbar v7 not working on android 4 and older Am using support library v7 for Toolbar the app working fine on my android 5.1 but when I try to install the app on older visions it say "unfortunately app name has stop". Am using AIDE on my Android 5.1.

A: Make sure you are using the Toolbar from support library instead of the native one included in Marshmallow. You must replace in your code:
XML
Replace
<Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

by
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"/>

JAVA
Change
import android.widget.Toolbar;

by
import android.support.v7.widget.Toolbar;


text:
Q: What am I doing wrong with the ag-grid in react? I'm trying to make the the ag-grid group selectable if say for example we have the care maker and you can select the parent and everything underneath that parent also gets selected.
I've looked into the ag-grid documentation but it looks like I'm doing everything right.
Here's my code below:
import React, { useState } from 'react';
import { AgGridReact, AgGridColumn } from 'ag-grid-react';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-balham.css';

const DummyGrid = () => {
  const [gridApi, setGridApi] = useState(null);
  const columnDefs = [
    {
      headerName: 'Make', field: 'make', checkboxSelection: true , rowGroup: true, groupSelectsChildren: true
    },
    {
      headerName: 'Model', field: 'model'
    },
    {
      headerName: 'Price', field: 'price'
    }
  ]

  const onGridReady = (params) => {
    setGridApi(params.api);
  }
  const rowData = [
    { make: 'Honda', model: 'Chev', price: 6000 },
    { make: 'Honda', model: 'Civic', price: 120000 },
    { make: 'Toyota', model: 'Celica', price: 5000 },
    { make: 'Mitsubishi', model: 'GTR', price: 5000 }
  ]

  const handleClick = () => {
    const selectedNodes = gridApi.getSelectedNodes();
    const selectedData = selectedNodes.map(node => node.data);
    const selectedDataStringRepresentation =  selectedData.map(node => node.make + ' ' + node.model).join(', ');
    console.log(`The Data selected: ${selectedDataStringRepresentation}`);
  }

  return(
    <div className="ag-theme-balham"
        style={{
          width: 600,
          height: 600
        }}>
      <button onClick={handleClick}>Click this!</button>
      <AgGridReact
        rowData = {rowData}
        columnDefs={columnDefs}
        rowSelection="multiple"
        onGridReady={onGridReady}
      />
    </div>
  );

};

export default DummyGrid;

As you can see from the output below that they're not grouping even though they the same maker. What am I doing wrong?

A: 2 things you're doing wrong.
First, you need to import the RowGroupingModule module and pass it to your grid as modules:
import { RowGroupingModule } from '@ag-grid-enterprise/row-grouping';

modules={[RowGroupingModule]}

Secondly, you need to set groupSelectsChildren on the grid itself, not on your column definition:
groupSelectsChildren={true}

Demo.


text:
Q: How to find a Lax pair I've been getting into Hamiltonian PDE's lately and they give the KdV equation a lax pair to proof that it is integrable in some sense.
My question is the following how does on find a lax-pair if we just start from an hamiltonian PDE or more specific how did they find it for the KdV-equation.
Or was it just guessing?