text:
Q: Vlookup with multiplication using collection/dictionary or classes My problem is the following, I have a trial balance (list of accounts ran for multiple months with their ending balance in various currencies) and a second sheet showing fxrate conversion rates to USD for those months. First sheet could have hundreds of thousands of lines, while the second around 150-200 rows. A quick extract of those two sheets would look as follows:
1st sheet:
A - Month; B - Currency; C - ending balance; Col D (USD); Col E (USD per Dec-18 rate)
Dec-18         EUR               12000
Dec-18         GBP               55000
Dec-18         SEK               1500000
Mar-19         EUR               60000
Mar-19         GBP               1700
Mar-19         SEK               500

2nd sheet:
A - Month; B - Currency;    C - fxrate
Dec-18         EUR               0.9
Dec-18         GBP               0.7
Dec-18         SEK               9.3
Mar-19         EUR               0.85
Mar-19         GBP               0.75
Mar-19         SEK               9.1

My goal is to:

*

*fill in Col D from 1st sheet by multiplying Col C with fxrate value from Col C from 2nd sheet AND do that for the matching month. So in D1 I'd like to find what fxrate for EUR for Dec-18 is (0.9) and multiply 12000 by that value. However for D4 I'd like to know fxrate for EUR for Mar-19 (0.85) and multiply 60000 by that value

*fill in COl E from 1st sheet by choosing upfront from which month I would like to use the fxrate from (no matter what month is stated in Col A in 1st sheet). So for example I could assing to some variable "Dec-18" and then use only fxrates from Dec-18 for the whole list of items on 1st sheet. So this time in E2 I would multiply 12000 by 0.9 (same as above), however for E4 I would multiply 6000 but again by 0.9 (not 0.85).

I've looked at posts on regular vlookup, on dictionaries and classes but I could no answer to that question. Can anyone help and at least guide me towards a partial solution which I could try to enhance on?

A: You can do a trick and use SUMIFS. Since we can assume that every Month-Currency combination in Sheet2 is unique that will return the actual fxrate because the sum of only one unique entry is the value itself:
This formula will return fxrate
=SUMIFS(Sheet2!C:C,Sheet2!A:A,Sheet1!A:A,Sheet2!B:B,Sheet1!B:B)

And you just need to multiply that with column C
=SUMIFS(Sheet2!C:C,Sheet2!A:A,Sheet1!A:A,Sheet2!B:B,Sheet1!B:B)*C:C

to get your result (use this formula for column D).
For column E it is almost the same formula you just need to write your fixed month value somewhere and use this cell in the SUMIFS as criteria instead of column A.
=SUMIFS(Sheet2!C:C,Sheet2!A:A,$I$2,Sheet2!B:B,Sheet1!B:B)*C:C

I used cell $I$2 (see the red in the example below):
Sheet1

Sheet2


text:
Q: iOS - AudioServicesPlayAlertSound not working on ipod? I cannot get AudioServicesPlayAlertSound(kSystemSoundID_Vibrate) to make the ipod beep - I know it cannot vibrate, but its suppsoed to beep atleast.
It compiles fine, added the audiotoolbox and just calling that line, and nothing happens. The sound is on of course.
Any idea on what it could be?

A: Hopefully this may give you some more info?
https://discussions.apple.com/thread/1649698?start=0&tstart=0

I had the same problem, but it worked fine a few days later without any changes??
PS. Stupid i Know but make sure the volume is on and up when your testing...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django project using python 2.7 even though interpretor points to python version 3.5 My project interpretor points to python version 3.5.2:
(/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5)
However when I go to the python shell in the project terminal (i'm using pycharm btw), it loads python 2.7. Any idea why?

A: You need to activate the same virtual environment PyCharm is using when you develop your project.
So, lets say you have a configuration like this:

Then you open the terminal and do:
$ cd ~/Documents/dev/
$ source ./pavorai-env-pycharm/bin/activate
$ NOW RUN YOUR DJANGO PROJECT

You should be using the same environment PyCharm is using. Please do note that directory you are using WILL BE different than the one I am showing in this example.


text:
Q: Apache high CPU usage but medium overall CPU usage I am running a website on an Apache server. The server itself is an 8 core server with 35G RAM. I am monitoring the statistics of the apache resource usage and the overall server resource usage.
I noticed the CPU usage of apache actually goes over 100%, even up to 150%! How is this possible?
Looking at my overall CPU utilization across all my CPUs, it is only around 0.3.
Currently, from Google Analytic, there is around 400 users viewing the website simultaneously. I am also browsing the site and refreshing pages just to test, everything seems smooth.
So my question is, is this apache CPU usage stats something I need to be worried about?
Any help would be appreciated.

A: If I'm not wrong, the CPU usage of process can go upto (100 x no. of cores)%. If you're worried about performance and want to peek under Apache's hood, try to use gdb as explained in this guide: http://httpd.apache.org/dev/debugging.html


text:
Q: Scanning a text file into an array and omitting one specified line I'm a beginner and need some help. I'm trying to scan a text file into an array line by line, but omitting one line. My text file is
i am
you are
he is
she is
it is
I want to create a method that will scan this and put elements into an array with an exception for one line (that is chosen by entering the String as a parameter for the method). Then erase the original text file and print there the created array (without that one deleted line). Sorry, I suck at explaining.
I have tried this:
public static void deleteLine(String name, String line) throws IOException {
    String sc = System.getProperty("user.dir") + new File("").separator;
    FileReader fr = new FileReader(sc + name + ".txt");
    Scanner scan = new Scanner(fr);
    int n = countLines(name); // a well working method returning the number if lines in the file (here 5)
    String[] listArray = new String[n-1];
    for (int i = 0; i < n-1; i++) {
        if (scan.hasNextLine() && !scan.nextLine().equals(line))
            listArray[i] = scan.nextLine();
        else if (scan.hasNextLine() && scan.nextLine().equals(line))
            i--;
        else continue;
    }
    PrintWriter print = new PrintWriter(sc + name + ".txt");
    print.write("");
    for (int i = 0; i < n-2; i++) {
        print.write(listArray[i] + "\n");
    }
    print.close()
}

I get an error "Line not found" when I enter: deleteLine("all_names","you are") (all_names is the name of the file). I'm sure the problem lies in the for-loop, but I have no idea why this doesn't work. :(
//SOLVED//
This code worked after all. Thanks for answers!
public static void deleteLine(String name, String line) throws IOException{
    String sc = System.getProperty("user.dir") + new File("").separator;
    FileReader fr = null;
    fr = new FileReader(sc+name+".txt");
    Scanner scan = new Scanner(fr);
    int n = LineCounter(name);
    String[] listArray = new String[n-1];
    for (int i = 0; i < n-1; i++) {
        if (scan.hasNextLine()) {
            String nextLine = scan.nextLine();
            if (!nextLine.equals(line)) {
                listArray[i] = nextLine;
            }
            else i--;
        }
    }
    PrintWriter print = new PrintWriter(sc+name+".txt");
    print.write("");
    for(int i=0;i<n-1;i++){
        print.write(listArray[i]+System.lineSeparator());

    }
    print.close();

}

A: Have a look at how you are comparing String objects. You should use the equals method to compare a String's content. Using operators like == and != compares if the String objects are identical.
Now after using equals correctly have a look at how you are using nextLine. Check its Javadoc

A: You are reading the lines twice scan.nextLine() while comparing and because of that you run out of the lines.
Replace your loop with this one or similar
for (int i = 0; i < n; i++) {
        if (scan.hasNextLine()) {
            String nextLine = scan.nextLine();
            if (nextLine.equals(line)) {
                listArray[i] = nextLine;
            }
        }
    }

A: I feel LineCounter(name) works because you did not put a ".txt" there. Try removing the ".txt" extension from the file name in the Filereader and Printwriter objects and see if it works. Usually in windows, the extension is not a part of the file name.

A: Here's an alternative (easier) solution to do what you want, using easier to understand code. (I think)
Also it avoids multiple
loops, but uses a single Java 8 stream to filter instead.
public static void deleteLine(String name, String line) throws IOException {
    List<String> lines = Files.readAllLines(Paths.get(name));
    lines = lines.stream().filter(v -> !v.equals(line)).collect(Collectors.toList());
    System.out.println(lines);

    // if you want the String[] - but you don't need it
    String[] linesAsStringArr = new String[lines.size()];
    linesAsStringArr = lines.toArray(linesAsStringArr);

    // write the file using our List<String>
    Path out = Paths.get("output.txt"); // or another filename you dynamically create
    Files.write(out, lines, Charset.forName("UTF-8"));
}


text: Q: ZX axis 2 dof orientation interpolation I have 2 DOF orientation for Z and X axes how can I interpolate between 2 orientations? I have interpolated for 3 DOF orientation with slerp using quaternions and rotation matrix for inverse kinematics, but I could not deal with 2 DOF orientaion one.


text:
Q: Ubuntu search not finding any files I've noticed that the search indexes only those files which have previously been opened with some application.
For example, searching for a presentation returns 0 results initially, but once I navigate to the file in Nautilus, and open it with LO - it becomes, along with the folder hierarchy it is in.
I've tested this primarily with files on another partition (where my home folder is) and on another disk (where most of my documents are).
Why is this so? Is it a bug or an intentionally missing feature? (Windows 7 finds all files whether they've been opened or not.)

A: The reason search isn't working in this case is because /media is blacklisted in /etc/updatedb.conf. The solution is to mount the partition on /mnt and ran sudo /etc/cron.daily/mlocate.
Search uses multiple search engines. Zeitgeist indexes the recently used documents, which is why some files from the partition are showing, and some aren't. But other search engines (mlocate) and os-walk (previously 'find') are problematic.
If your drives are NTFS, they aren't blacklisted, but are probably mounted in /media, which is why they aren't being indexed.

A: As dez93_2000 mentioned, /media path is blacklisted, but you can remove it from /etc/updatedb.conf and set PRUNE_BIND_MOUNTS to "no". If you run updatedb after that you should notice some time will be spent on processing newly found media devices.


text:
Q: How to recognize user inputted websites as link tags using HTML or Javascript? If the user inputs any of the following:

*

*http://www.foo.com

*www.example.org

*fooexample.gov/images/foo.jpg

then the script should automatically make the output recognize these as links
practically every email service do this and most professional dynamic sites as well, so I'm wondering how this is coded.
Thanks :)

A: I wrote a demo for your question, in here: http://jsfiddle.net/abruzzi/9dqbf9fr/4/
Actually the key is replacing the url string by regExp like below:
$('textarea').change(function() {
    var tmp = $(this).val();
    var url_reg = /(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w\.-]*)*/g;

    var result = tmp.replace(url_reg, function(link) {
        return ''+ link +'';
    });

    $('p').text(result);
});

A: *

*first, you should attach an event to the input controller, like keyUp, keyDown or Input in jquery.

*second, using regular expressions to find out that the value in controller is the url or email format.

*at last, dynamic replace the input values by wrapping a  element


text:
Q: Structured streaming custom deduplication I have a streaming data coming in from kafka into dataFrame.
I want to remove duplicates based in Id and keep the latest records based on timestamp.
Sample data is like this :
Id  Name    count   timestamp
1   Vikas   20      2018-09-19T10:10:10
2   Vijay   50      2018-09-19T10:10:20
3   Vilas   30      2018-09-19T10:10:30
4   Vishal  10      2018-09-19T10:10:40
1   Vikas   50      2018-09-19T10:10:50
4   Vishal  40      2018-09-19T10:11:00
1   Vikas   10      2018-09-19T10:11:10
3   Vilas   20      2018-09-19T10:11:20

The output that I am expecting would be :
Id  Name    count   timestamp
1   Vikas   10      2018-09-19T10:11:10
2   Vijay   50      2018-09-19T10:10:20
3   Vilas   20      2018-09-19T10:11:20
4   Vishal  40      2018-09-19T10:11:00

Older duplicates are removed and only the recent records are kept based on the timestamp field.
I am using watermarking for timestamp field.
I have tried using "df.removeDuplicate" but it keeps older records intact and anything new gets discarded.
Current code is as follows :
df = df.withWatermark("timestamp", "1 Day").dropDuplicates("Id", "timestamp")

How can we implement custom dedup method so that we can keep latest record as unique record?
Any help is appreciated.

A: Sort the timestamp column first before dropping the duplicates.
df.withWatermark("timestamp", "1 Day")
  .sort($"timestamp".desc)
  .dropDuplicates("Id", "timestamp")


text:
Q: On save creating a dist folder in every created folder Every time I create a folder with a file, on save it creates a dist folder. Is there any tslint feature that could cause this?
Every folder has a 'dist' folder below it.

A: That is actually configured in your tsconfig.json. There maybe additional configuration you have set in it. Usually the tsconfig.json outDir is usually configured like this:
tsconfig.json
{
    ...,
    "outDir": "dist"

}


text:
Q: Linq Grouping - aggregate, outside of a group by I've got a SQL query, that works as follows:
SELECT TOP 100
    Max(Table_ID) as Max_ID,
Col1,
Col2,
Col3,
COUNT(*) AS Occurences
FROM myTable
GROUP BY Col1, Col2, Col3
ORDER BY Occurences DESC

How can I write an identical Linq query?
The issue is, that as soon as I apply my grouping, I cannot access the non-grouped columns Table_ID in my case.
var errors = from r in MyTable
    group e by new {e.Col1, e.Col2} into g
    orderby g.Count() descending
    select new {MaxId = ???, Count =  g.Count(), g.Key.Col1, g.Key.Col2};

A: Use g.Max(x => x.TableID):
var errors = from r in MyTable
    group e by new {e.Col1, e.Col2} into g
    orderby g.Count() descending
    select new {MaxId = g.Max(x => x.TableID),
                Count =  g.Count(), g.Key.Col1, g.Key.Col2};

(Assuming you want the maximum within each group, of course.)

A: Jon's answer is good, I just want to elaborate a little on why:

The issue is, that as soon as i apply my grouping, I cannot access the non-grouped columns

r went out of scope... why is that?
The two ways of ending a query are select or group by clauses.  When you add the query continuation clause into g to the group by, you are saying - the top level elements of the query are g and all variables introduced in the query up to this point are removed from scope.
If you search this msdn article for the word splice, you can see samples.
Don't confuse this use of into with join on equals into, which is a group join, not a query continuation.  Group join does not remove previous variables from scope.


text:
Q: How to create variables to loop over files and emerge in dataframe? I want to create a DataFrame with data for Tennis matches of a specific player 'Lenny Hampel'. For this I downloaded a lot of .json files with data for of his matches - all in all there are around 100 files. As it is a json file i need to convert every single file into a dict, to get it into the dataframe in the end. Finally I need to concatenate each file to the dataframe. I could hard-code it, however it is kind of silly I think, but I could not find a proper way to iterate trough this.
Could you help me understand how I could create a loop or smth else in order to code it the smart way?
from bs4 import BeautifulSoup
import requests
import json
import bs4 as bs
import urllib.request
from urllib.request import Request, urlopen
import pandas as pd
import pprint

with open('lenny/2016/lenny2016_match (1).json') as json_file:
    lennymatch1 = json.load(json_file)

player = [item
          for item in lennymatch1["stats"]
          if item["player_fullname"] == "Lenny Hampel"]

with open('lenny/2016/lenny2016_match (2).json') as json_file:
    lennymatch2 = json.load(json_file)

player2 = [item
          for item in lennymatch2["stats"]
          if item["player_fullname"] == "Lenny Hampel"]

with open('lenny/2016/lenny2016_match (3).json') as json_file:
    lennymatch3 = json.load(json_file)

player33 = [item
          for item in lennymatch3["stats"]
          if item["player_fullname"] == "Lenny Hampel"]

with open('lenny/2016/lenny2016_match (4).json') as json_file:
    lennymatch4 = json.load(json_file)

player4 = [item
          for item in lennymatch4["stats"]
          if item["player_fullname"] == "Lenny Hampel"]

tabelle1 = pd.DataFrame.from_dict(player)
tabelle2 = pd.DataFrame.from_dict(player2)
tabelle3 = pd.DataFrame.from_dict(player33)
tabelle4 = pd.DataFrame.from_dict(player4)

tennisstats = [tabelle1, tabelle2, tabelle3, tabelle4]

result = pd.concat(tennisstats)
result

A: Well, it seems so basic knowledge that I don't understand why you ask for this.
# --- before loop ---

tennisstats = []

# --- loop ---

for filename in ["lenny/2016/lenny2016_match (1).json", "lenny/2016/lenny2016_match (2).json"]:

    with open(filename) as json_file:
         lennymatch = json.load(json_file)

    player = [item
         for item in lennymatch["stats"]
         if item["player_fullname"] == "Lenny Hampel"]

    tabele = pd.DataFrame.from_dict(player)

    tennisstats.append(tabele)

# --- after loop ---

result = pd.concat(tennisstats)

If filenames are similar and they have only different number
for number in range(1, 101):

    filename = f"lenny/2016/lenny2016_match ({number}).json"

    with open(filename) as json_file:

and rest is the same as in first version.

If all files are in the same folder then maybe you should use os.listdir()
directory = "lenny/2016/"

for name in os.listdir(directory):

    filename = directory + name

    with open(filename) as json_file:

and rest is the same as in first version.


text:
Q: Twitter oauth problem with frindship/create in api I am using Google Data API sample touch application, which is available at code.google....
I am having a problem can any one help.
Please tell me if I am doing some thing wrong.
The user who has loged in has to follow some person XYZ (just using
XYZ for security purpose).
I am using the URL
urlStr = @"http://api.twitter.com/1/friendships/create/XYZ.xml";

NSURL *url = [NSURL URLWithString:urlStr];

       NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:url];

//made post as requested in twitter API

       [request setHTTPMethod:@"POST"];

       ConnectAppDelegate *appDelegate = (ConnectAppDelegate *)
[[UIApplication sharedApplication] delegate];

       [mAouth authorizeRequest:request];
NSError *error = nil;
       NSURLResponse *response = nil;
       NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
       if (data) {
               // API fetch succeeded
               NSString *str = [[[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding] autorelease];
               NSLog(@"API response: %@", str);
       } else {
               // fetch failed
               NSLog(@"API fetch error: %@", error);
       }

In the response I get
http://api.twitter.com/1/friendships/create/XYZ.xml
2010-06-11 16:04:39.437 Connect[4265:20b] API response:
<?xml
version="1.0" encoding="UTF-8"?>
<hash>
 <request>/1/friendships/create/XYZ.xml</request>
 <error>Invalid / used nonce</error>
</hash>

A: This error can happen if your time and the server time are more than 5 mins different, check that your server / pc has the same time as the server.


text:
Q: Multiple notification wrong content on click android I receive multiple notification successfully using the notification intent below. But when i click on any notification it opened the last notification received everytime. can someone tell me how to open corresponding notification. i means each notification has its own content.
@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub

    /*
     *      Explicitly specify that GcmIntentService will handle the intent.
            ComponentName comp = new ComponentName(context.getPackageName(),
            GCMIntentService.class.getName());
            Start the service, keeping the device awake while it is launching.
            startWakefulService(context, (intent.setComponent(comp)));
            setResultCode(Activity.RESULT_OK);
     *
     */

    GCMNotificationUtility.notiMsg = intent.getStringExtra("msg");
    GCMNotificationUtility.notPubDate = chopJson(intent.getStringExtra("datepublished"));
    GCMNotificationUtility.notDescription =chopJson(intent.getStringExtra("description"));
    GCMNotificationUtility.notLink = chopJson(intent.getStringExtra("news_url"));
    GCMNotificationUtility.notCategory= chopJson(intent.getStringExtra("category"));

    int icon = R.drawable.ic_launcher; // icon from resources
    CharSequence tickerText =context.getResources().getString(R.string.app_name);//intent.getStringExtra("me"); // ticker-text

    long when = System.currentTimeMillis(); // notification time
    CharSequence xmsg =GCMNotificationUtility.notiMsg;

    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, tickerText, when);

    System.out.println("nodescription "+GCMNotificationUtility.notDescription);

    ActusNewActivity.description=GCMNotificationUtility.notDescription;
    ActusNewActivity.pudDate=GCMNotificationUtility.notPubDate;
    ActusNewActivity.Link=GCMNotificationUtility.notLink;
    ActusNewActivity.title=GCMNotificationUtility.notiMsg;

    Intent notificationIntent = new Intent(context,ActusNewActivity.class);

    Calendar c = Calendar.getInstance();

    int unique_id = (int) c.getTimeInMillis();

    //set calendar.getTimeInMillis() as  unique ID.
    PendingIntent pendingIntent = PendingIntent.getActivity(context, unique_id , notificationIntent,  PendingIntent.FLAG_ONE_SHOT);

    notification.setLatestEventInfo(context,tickerText,xmsg, pendingIntent);
    notification.flags|=notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS;
    notification.vibrate=new long[] {100L, 100L, 200L, 500L};
    notificationManager.notify(unique_id, notification);

    GCMNotificationUtility.notificationReceived=true;
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "TAG");
    wl.acquire();

}

public String chopJson(String y){

    String x = ":\"";
    int xval = y.indexOf(x)+2;

    String substring = y.substring(0, xval);
    String newElement =  y.replace(substring, "");
    int lastvalue = newElement.length()-2;
    String value = newElement.substring(0,lastvalue);

    return value;

}

A: Instead of :
notificationManager.notify(unique_id, notification);
use
notificationManager.notify((int) when , notification);

Hope this helps.


text:
Q: mat-slide-toggle : maintain color depth even disabled The mat-slide-toggle color will be paled when [disabled]=true as in the example site, but I want the color depth to be maintained even [disabled]=true.
How can I do this?

A: You can override Material style in your CSS turning off opacity like this :
.mat-slide-toggle.mat-disabled {
   opacity: 1 !important;
}

A: I end up setting (click)="$event.preventDefault();" instead of [disabled]="true".


text:
Q: What are the non-negative integers of this form? What are $( \frac{x^2-1-my}{x}, \frac{y^2-1-nx}{y} ) \in  \mathbb{Z}^2_{\ge 0}$ for $(m,n) \in \mathbb{Z}^2_{\ge 0}$, $(x,y) \in \mathbb{R}^2_{\ge 1}$ and $mx+ny=xy$?

Some investigations:

*

*According to this answer of Ivan Neretin, assuming $x,y$ integers, the only possibility is $(0,1)$ with $(m,n) = (0,1)$ and $(x,y) = (1,2)$, up to permutation.

*If $x=y$, then $(m+n)x = x^2$, so $x=m+n$ positive integer.

In general $y=mx/(x-n)$ with $x>n$. Thus we need to consider
$$ ( \frac{x^2-1-m\frac{mx}{x-n}}{x}, \frac{(mx/(x-n))^2-1-nx}{mx/(x-n)}  ) $$ $$ = (\frac{(x^2-1)(x-n)-m^2x}{x(x-n)},\frac{m^2x^2-(x-n)^2(1+nx)}{mx(x-n)}) \in  \mathbb{Z}^2_{\ge 0} $$
Let $\alpha=\alpha_{n,m}$ be the root of $$P_{n,m}(x):=(x^2-1)(x-n)-m^2x$$ when $x>n$ (show unicity). Then $$m^2\alpha^2-(\alpha-n)^2(1+n\alpha) = (\alpha^2-1)(\alpha-n)\alpha -(\alpha-n)^2(1+n\alpha) $$ $$ = (\alpha-n)((\alpha^2-1)(\alpha-n)-\alpha+n^2\alpha) = (m^2+n^2-1)\alpha(\alpha-n)$$
Let $\beta = \beta_{n,m}$ be the root of $$Q_{n,m}(x):=m^2x^2-(x-n)^2(1+nx)$$ when $x>n$ (show unicity). Note that if $n=m$ then $\beta = n \alpha/(\alpha-n)$.
We can assume (by symmetry) that $\alpha \le \beta$.
Let $(a,b) = ( \frac{x^2-1-my}{x}, \frac{y^2-1-nx}{y} )$. Then for $x=\alpha$ we get $$(a,b) = (0,\frac{m^2+n^2-1}{m}),$$ and by symmetry, for $x=\beta$, we get $$(a,b) = (\frac{m^2+n^2-1}{n},0).$$
The problem reduces to find all the $x \in [\alpha, \beta]$ such that $P_{n,m}(x)$ an $Q_{n,m}(x)$ are integers.
Remark: If $n |(m^2-1)$ or $m |(n^2-1)$, then above is at least one solution.
Example: $m=n=1$, then $\alpha=1.80193773580484...$ and $\beta=2.24697960371747...$.
Let us plot $P_{1,1}$ and $Q_{1,1}$:

It follows that $(0,1)$ and $(1,0)$ are the only solutions if $m=n=1$.
What are all the others solutions in general?

An other approach
Take $(p,q) = ( \frac{x^2-1-my}{x}, \frac{y^2-1-nx}{y} )$. Then:
$$\left\{
\begin{array}{ll}
x^2 - px-1-my = 0 \\
y^2 -qy-1-nx = 0
\end{array}
\right.$$
Because $(x,y) \in \mathbb{R}^2_{>1}$, it follows that:
$$\left\{
\begin{array}{ll}
2x = p + (p^2+4(1+my))^{1/2}\\
2y = q + (q^2+4(1+nx))^{1/2}
\end{array}
\right.$$
So $$ 2x = p + [p^2+4+2m(q + [q^2+4(1+nx)]^{1/2})]^{1/2} $$
Then
$$ [(2x-p)^2-p^2-4-2mq]^2 = q^2+4(1+nx) $$
Thus
$$ (4x^2-4xp-4-2mq)^2 = q^2+4(1+nx) $$
We got a polynomial of degree $4$, allowing us to get at most $4$ roots $x_i(m,n,p,q)$ with $i \le 4$. Then $$2y_i(m,n,p,q) = q + (q^2+4(1+nx_i(m,n,p,q)))^{1/2}$$
It remains to solve the Diophantine equation $$mx_i(m,n,p,q)+ny_i(m,n,p,q)=x_i(m,n,p,q)y_i(m,n,p,q).$$

A: A pair $(p,q) = ( \frac{x^2-1-my}{x}, \frac{y^2-1-nx}{y} )$ is achievable if and only if $p^2+q^2+4$ is the sum of two squares.

Proof. In one direction, we assume that the following three polynomials have a common zero:
\begin{split}
f(x,y)&:=x^2-1-my-px,\\
g(x,y)&:=y^2-1-nx-qy, \\
h(x,y)&:=xy-mx-ny.
\end{split} Then eliminating $x,y$ via computing resultants, we have with necessity:
$$0 = \mathrm{Res}_y(\mathrm{Res}_x(f,g),\mathrm{Res}_x(g,h)) = -(m^2-mq+n^2-np-1)^3 n^4,$$
implying that $m^2-mq+n^2-np-1=0$, which is equivalent to
$$(\star)\qquad p^2 + q^2 + 4 = (2n-p)^2 + (2m-q)^2.$$
That is, $p^2+q^2+4$ is the sum of two squares.
In the reverse direction, we assume that $p^2 + q^2 + 4 = a^2 + b^2$ for some nonnegative integers $a,b$. Without loss of generality we have $a\equiv p\pmod{2}$ and $b\equiv q\pmod{2}$. We set $n:=\frac{a+p}2$ and $m:=\frac{b+q}2$, which makes them satisfy $(\star)$.
Then we set $x_0>n$  be a zero of the polynomial:
$$F(x):=x^3-(p+n)x^2+(pn-1-m^2)x+n.$$
Such zero does exist since $F(n) = -m^2n<0$ while $F(x)\to+\infty$ as $x$ grow. Then, we set $y_0:=\tfrac{mx_0}{x_0-n}$ to get $h(x_0,y_0)=0$. Since $F(x) = (x-n)f(x,y)+mh(x,y)$, we also have $f(x_0,y_0)=0$, which together with $(\star)$ further implies that $g(x_0,y_0)=0$. That is, for $(x,y)=(x_0,y_0)$ we get $( \tfrac{x^2-1-my}{x}, \tfrac{y^2-1-nx}{y} ) = (p,q)$. QED
P.S. Similarly to $x_0$, we also have that $y_0$ is a zero of the polynomial:
$$G(y):= y^3-(q+m)y^2+(qm-1-n^2)y+m.$$
which satisfies $G(y)=(y-m)g(x,y) + nh(x,y)$.


text:
Q: Using React-Quill with Form FormItem in antd design react Actually I want to use react-quill component as a part of antd Form.item.
 <ReactQuill
   ref='editor'
   onChange={this.onChange}
 />

Above component is react-quill basic component.
I need to use like below mentioned
 <Field
   label="Departure"
   placeholder="Departure"
   name="departure"
   component={}
 />

above <Field /> , actually it is import props from redux form, which is, I am using in Antd Form as Form.Item like below
import {
  Form,
  Input,
} from 'antd'

const FormItem = Form.Item;

const makeField = Component => ({
  input,
  meta,
  children,
  hasFeedback,
  label,
  labelRight,
  ...rest
}) => {
  const hasError = meta.touched && meta.invalid;
  return (
    <FormItem
      {...formItemLayout}
      label={label}
      validateStatus={hasError ? 'error' : 'success'}
      hasFeedback={hasFeedback && hasError}
      help={hasError && meta.error}
    >
      <Component {...input} {...rest}>
        {children}
      </Component>
      {labelRight && (

          {labelRight}

      )}
    </FormItem>
  );
};

export const AInput = makeField(Input);

Usage in Form
<Field
  label="Destination"
  placeholder="Destination"
  name="destination"
  component={AInput}
/>

As shown above, how I use antd Input in Form.Item and than render in Redux-Form Field. Similarly, I need to use React-Quill Component.

A: One way to do this would be to wrap a hidden antd <Input /> in getFieldDecorator. Then, render the react-quill input and use the hidden <Input /> to manage it's state. See this example using a plain <input />:

class Form extends React.Component {
  handleChange = e => {
    const { value } = e.target;

    this.props.form.setFieldsValue({ input: value });
  };

  render() {
    const { getFieldValue, getFieldDecorator } = this.props.form;

    return (
      <Form layout="inline">
        {/* This is a hidden antd Input used to manage form state */}
        {getFieldDecorator("input")(<Input style={{ display: "none" }} />)}

        <input
          type="text"
          onChange={this.handleChange}
          value={getFieldValue("input")}
        />

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            onClick={() => console.log(getFieldValue("input"))}
          >
            test
          </Button>
        </Form.Item>
      </Form>
    );
  }
}

A: Install "react-quill": "^1.3.3" from https://www.npmjs.com/package/react-quill
I have made my one formHOC util file from where I import all form components. Similarly design this component also.
import ReactQuill from "react-quill"; // third party library "react-quill": "^1.3.3",

import {
  Form,
} from 'antd';

// customization shown below

const FormItem = Form.Item;

var formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

const makeEditorField = Component => ({
                                  input,
                                  meta,
                                  children,
                                  hasFeedback,
                                  label,
                                  labelRight,
                                  ...rest
                                }) => {
  const hasError = meta.touched && meta.invalid;
  return (
    <FormItem
      {...formItemLayout}
      label={label}
      validateStatus={hasError ? 'error' : 'success'}
      hasFeedback={hasFeedback && hasError}
      help={hasError && meta.error}
    >
      <Component {...input} {...rest}
       onBlur={(range, source, quill) => {
         input.onBlur(quill.getHTML());
       }}
      >
        {children}
      </Component>
      {labelRight && (

          {labelRight}

      )}
    </FormItem>
  );
};

export const AEditor= makeEditorField(ReactQuill); // Export it to use other files.

Usage
import {AEditor} from "../../utils/formHOC";
import { Field, reduxForm } from 'redux-form/immutable';

 <Field
            label="Departure"
            placeholder="Departure"
            name="departure"
            modules={modules}
            formats={formats}
            component={AEditor}
          />


text:
Q: Rewrite Custom Post Type(with taxonomies) URL I have a Custom Post Type with 1 taxonomy and this is the link structure:
mywebsite.com/casos-legal  (Show the post in archive-casos-legal.php)
And when I click on any post:
mywebsite.com/casos-legal/lima/this-is-the-post-title
In the case above, "lima" is a term of the taxonomy.
Is there a way to add a path before "casos-legal"? something like this:
mywebsite.com/temas/legal/casos-legal
and:
mywebsite.com/temas/legal/casos-legal/lima/this-is-the-post-title
And much better, change the post slug for just "casos" to get something like this:
mywebsite.com/temas/legal/casos/lima/this-is-the-post-title
Thank in advance!
This is how it looks the CTP
function aprodeh_casos(){

$labels = array(
    'name' => 'Casos - legal',
    'singular_name' => 'Caso',
    'add_new' => 'Agregar',
    'all_items' => 'Todos',
    'add_new_item' => 'Agregar',
    'edit_item' => 'Editar',
    'new_item' => 'Nuevo',
    'view_item' => 'Ver',
    'search_item' => 'Buscar',
    'not_found' => 'No se encontraron casos',
    'not_found_in_trash' => 'No se encontraron casos en la papelera',
    'parent_item_colon' => 'Parent Item',

);

$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => '/casos-legal/%categoria_casos%', 'with_front' => false ),
    'has_archive' => 'casos-legal',
    'capability_type' => 'post',
    'hierarchical' => false,
    'supports' => array(
        'title',
        'editor',
        'thumbnail',
    ),
    'menu_position' => 5,
    'exclude_from_search' => false,
    'taxonomies' => array('post_tag'),
);
register_post_type('casos-legal',$args);

} add_action('init','aprodeh_casos');

This is how it looks the Taxonomy:
function aprodeh_casos_taxonomia(){

$labels = array(
    'name' => 'Categorías',
    'singular_name' => 'Categoría',
    'search_items' => 'Buscar categoría',
    'all_items' => 'Todas las categorías',
    'edit_item' => 'Editar categoría',
    'update_item' => 'Actualizar categoría',
    'add_new_item' => 'Agregar categoría',
    'new_item_name' => 'Nuevo categoría',
    'menu_name' => 'Categorías',

);

$args = array(

    'hierarchical' => true,
    'labels' => $labels,
    'show_ui' => true,
    'show_admin_column' => true,
    'query_var' => true,
    'rewrite' => array( 'slug' => 'casos-legal', 'with_front' => false ),

);

register_taxonomy('categoria_casos', array('casos-legal'), $args);

}

add_action('init', 'aprodeh_casos_taxonomia');

And finally, this code in order to get this link structure:
 mywebsite.com/casos-legal/lima/this-is-the-post-title
function wpa_casos_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'casos-legal' ){
    $terms = wp_get_object_terms( $post->ID, 'categoria_casos' );
    if( $terms ){
        return str_replace( '%categoria_casos%' , $terms[0]->slug , $post_link );
    }
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_casos_permalinks', 1, 2 );

A: Try updating
'rewrite' => array( 'slug' => '/casos-legal/%categoria_casos%', 'with_front' => false ),

to
'rewrite' => array( 'slug' => '/tema/legal/casos/%categoria_casos%', 'with_front' => false ),


text:
Q: Typrom postgres connetion with typescript and docker I am trying to use typeorm in my node project. So the db is spun up via a docker. Now when the container is stopped and restarted the ip keeps changing and hence the better possibility was to make use of the container name in my configuration.
Now the real mess starts, so I tried to configure the connection options using the env variable and it seems that it cannot resolve the host (when given as a docker container).
This is my sample .env file
TYPEORM_HOST=postgres-container
TYPEORM_POSTGRES_USERNAME=postgres
TYPEORM_POSTGRES_PASSWORD=XXXXXX
TYPEORM_TYPE=postgres
TYPEORM_LOGGING=true
TYPEORM_SYNCHRONIZE=true
TYPEORM_DATABASE=XXXXX
PINO_ENABLE_LOGGING= true

This threw an error when I tried consuming it in my app stating that the host cannot be found and hence reverted back to the ip and it worked
   const databaseConfigParams = DatabaseConfigInstance.getConnectionParams();
    ......
   try {
            const connec = await createConnection({
                name: DB_CONNECTION_NAME,
                type: DatabaseConnectionEnum.POSTGRES,
                host: databaseConfigParams.getHost(),
                port: parseInt(databaseConfigParams.getPort()),
                username: databaseConfigParams.getUsername(),
                password: databaseConfigParams.getPassword(),
                database: databaseConfigParams.getDatabase(),
                logging: databaseConfigParams.isLogging(),
                synchronize: databaseConfigParams.isSynchronize(),
                entities: [XXXEntity, XXEntity, XXXEntity]

             });
             res(connec);
        } catch (err){
            console.log('error in creating connection:', err);
            rej(err);
        }

Now since the container name could not be resolved if configuration is provided as the environment var, I decided to move the configurationto ormconfig.js file.
Now where can I specify the entities to use ? . Since I use webpack to bundle my app I need the entities to be recognized even the app is bundled.
Here is my webpack config
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const dotEnvPlugin = require('dotenv-webpack');
const TerserPlugin = require('terser-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');

'use strict';

module.exports = {
  entry: './src/app/server.ts',
  mode: 'development',
  optimization: {
    minimizer: [
    new UglifyJsPlugin({
        uglifyOptions: {
          keep_classnames: true,
          keep_fnames: true
        }
      })
    ],
  },
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[name].js'
  },
  resolve: {
    extensions: ['.ts', '.js'],
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: [
          'ts-loader',
        ]
      },
      {
        test: /\.handlebars$/,
        loader: 'handlebars-loader',
        options: {
            knownHelpersOnly: false,
            inlineRequires: /\/assets\/(:?images|audio|video)\//ig,
            partialDirs: [path.join(__dirname, './src/views/email/partials')],
        },
    }
    ]

  },
  externals: [ nodeExternals() ],
  plugins: [
    new dotEnvPlugin({
        path: './config/development/.env',
        safe: true,
        systemvars: true,
        silent: true,
        defaults: false
    }),
    new webpack.DefinePlugin({
        'process.env.NODE_ENV': 'development',
        'process.env.DEBUG': 'false'
    }),

    // need this plugin for the maps to be generated
    new webpack.EvalSourceMapDevToolPlugin({
      filename: '[name].map.js'
    }),
    new webpack.WatchIgnorePlugin([
      path.join(__dirname, "node_modules")
    ]),

  ]

};

EDIT:
I tried using specifying entities in oemconfig.js. It works well for ts-node compilation but not after webpack.
module.exports = {
  name: 'postgresConnection',
  type: 'postgres',
  host: '172.17.0.3',
  port: 5432,
  username: 'postgres',
  password: 'XXX',
  database: 'XXX',
  synchronize: true,
  logging: true,
  "entities": [
      "src/app/modules/database/entities/*.ts"
  ],
};

So I have two issues. Not sure which approach should I take. I need to link the postgres-container (docker) and use it in my typeorm. Also I need to make the bundled code (after webpack bundle) to make use of the correct entity folder.

A: I didnt try linking the postgres container on my end and that was causing the issue. Apologies as I haven't tried linking the container at my end. My bad. Now it works perfectly. I can revert to declaring the typeorm connection options in the env file and have the entities declared in the ts file itself which suits the webpack configuration
Maybe if someone also faces a similar issue this would help them
my .env file
TYPEORM_HOST=postgres-container
TYPEORM_POSTGRES_USERNAME=postgres
TYPEORM_POSTGRES_PASSWORD=XXXXXX
TYPEORM_TYPE=postgres
TYPEORM_LOGGING=true
TYPEORM_SYNCHRONIZE=true
TYPEORM_DATABASE=XXXXX

My Dockerfile ( the FROM image is my own node image. Apparently the image 12.9.0 in dockerhub is having issues with concurrency and older versions doesn't seem to support atob module base64 parsing and hence created my own from UBUNTU as base and pushed to private dockerhub)
FROM vijayakumarpsg587/node-12:1.01
# install pm2 and link the image using environment variables
RUN npm install pm2 -g

# Create a seperate node user
RUN useradd -ms /bin/bash node-user

RUN mkdir -p /home/node/app
# RUN chown -R node-user:node-user /home/node/app && chmod -R u+rwx,go+rwx /home/node/app
WORKDIR /home/node/app
# USER node-user
COPY package*.json ./
RUN npm install

COPY . ./

RUN npm run build:webpack:dev
ENV PM2_PUBLIC_KEY XXX
ENV PM2_SECRET_KEY XXX

EXPOSE 3002
CMD ["pm2-runtime", "./dist/main.js"]
Its the same webpack config. Also the ts file used to retrieve the contants from .env is also the same.
The real issue is I haven't linked the postgres-container to the new app container that I built.
So first I create a new app image and spin up a container

docker build -t XXXX/XXX: .

*

*(.) instructs to build an image from the current Dockerfile location. builds an image with the given tag

Spin up a container from the image and while doing so link the postgres-container
docker run -d -p 3002:3002 --name <name of the container> --link postgres-container <image that you created earlier with the prev command>

EDIT: please follow the best practices from the dockerfile guidelines while writing a dockerfile. Instructions RUN,COPY ADD creates new image layers and they should be as minimal as possible. If needed be try to create multistage builds.


text:
Q: MathJax does not finish rendering, when hiding CKEditor too soon i'm using CKEditor 4.14.1, with the "Mathematical Formulas" Plugin, using Mathjax 2.7.8.
https://ckeditor.com/docs/ckeditor4/latest/features/mathjax.html
The user in our application is able to close and open the editor again, which in the end just sets the wrapping div to display:none or block.
The problem is that if the user closes the editor before the formulas are finished rendering, and opens the editor again, the formulas won't show.
I tried triggering the render process manually, as described here.
https://docs.mathjax.org/en/v2.7-latest/advanced/typeset.html
MathJax.Hub.Queue(["Rerender",MathJax.Hub]);
// or
MathJax.Hub.Queue(
  ["resetEquationNumbers",MathJax.InputJax.TeX],
  ["PreProcess",MathJax.Hub],
  ["Reprocess",MathJax.Hub]
);

This didn't work though.
Here is an example. It should render the five formulas seen in the html, but is rendering none or only parts:
https://jsfiddle.net/Lh1o4ckj/
I just copied the example from the official docs (https://ckeditor.com/docs/ckeditor4/latest/examples/mathjax.html), and simulated a user hiding and showing the formula with a timeout. As this problem only shows, depending on how fast the formula is rendered, it might take a few tries.


text:
Q: Redirect based on user post count I'm at a loss..
I wanna check the current users post count. If the post count is 1, the user should be redirected. I have tested the following code:
add_action( 'template_redirect', 'redirect_to_specific_page' );

function redirect_to_specific_page() {
$current_user = wp_get_current_user();
    if (empty($the_user_id)) {
        $the_user_id = $current_user->ID;
    }
$user_post_count = count_user_posts( $the_user_id );

  if ( is_page('butiktest') && $user_post_count == 1 ) {

        wp_redirect( 'enhytte', 301 );

    exit;

    }

}

However, the above code will redirect no matter the amount of posts.
What am I doing wrong?
EDIT: After pointing out my syntax error was a missing "=", it is still not working.
EDIT 2: The code is in theory working, however, once a post is added, the user_post_count is not updated, and stays at the previous value.
EDIT3: count_user_posts only count published posts, how do I check for 'pending' and 'draft'?

A:     add_action( 'template_redirect', 'redirect_to_specific_page' );

    function redirect_to_specific_page() {
    global $post;

    $current_user = $post->post_author;

    if(!empty($current_user)){
    $user_post_count = (int) count_user_posts( $current_user );

       if ( is_page('butiktest') && $user_post_count == 1 ) {

            wp_redirect( 'enhytte', 301 );

            exit;

      }
   }
   }

authorized user: $current_user = wp_get_current_user();

A: You simply have a typo, should be:
$user_post_count == 1


text:
Q: React: How to use multiple Contexts of the same type while allowing children to read data from all of them I have a certain Context setup similar to this
const DataContext = createContext({ data: null });

const getData = (key) => {
    switch(key) {
        case 1:
            return "Hello"
        case 2:
            return " World"
        default:
            return null
    }
}

export const DataProvider = ({ id, children }) => {

  const data = useMemo(() => {
    return getData(id);
  }, [id]);

  return (
    <DataContext.Provider
      value={{
        data,
      }}
    >
      {children}
    </DataContext.Provider>
  );
};

export default DataContext

And child components that use it like this
const HelloComponent = () => {
    return <DataProvider id={1}>
        {
            // children are components that useContext(DataContext) and expect data to be "Hello"
        }
    </DataProvider>
}

Now I need to do this
const HelloWorldComponent = () => {
  return (
    <DataProvider id={1}>
      <DataProvider id={2}>
        {
          // children are components that need to read both Hello and World
        }
      </DataProvider>
    </DataProvider>
  );
};

Need to provide all parent context's data of one single Context definition to a set of children
I know useContext can only read the closest parent of a given ContextType, so I'm not sure of how to proceed with this.

A: You can't use two context providers of the same type and have children receive from both. The Context API is such that children components receive the context value from the closest context provider to them in the React tree.
You can, however, use a single provider that instead returns the getData function. Here's an example using a single DataProvider and a custom React hook to provide the "id" value.
Data.Context.js
import { createContext, useContext } from "react";

const DataContext = createContext({
  getData: () => {}
});

const getData = (key) => {
  switch (key) {
    case 1:
      return "Hello";
    case 2:
      return " World";
    default:
      return null;
  }
};

export const useDataContext = (id) => useContext(DataContext).getData(id);

const DataProvider = ({ children }) => {
  return (
    <DataContext.Provider value={{ getData }}>{children}</DataContext.Provider>
  );
};

export default DataProvider;

index.js
<DataProvider>
  <App />
</DataProvider>

Child component
import { useDataContext } from "./Data.Context";

const Child = () => {
  const data1 = useDataContext(1);
  const data2 = useDataContext(2);

  return (

DataProvider 1: {data1}

DataProvider 2: {data2}

  )
}


text:
Q: Make function more re-usable I need to run a function that makes checkboxes behave like radio buttons. I know, long story. Anyway, I want to make it more re-usable and not have to rewrite it for each group. I have it working like this:
$(function() {
    var $apples = $('input.apples');
    $apples.click(function() {
        $apples.removeAttr('checked');
        $(this).attr('checked', true);
    });
});

How can I make this more global so that if I have another group of checkboxes .bannanas it will work for them as well without having to rewrite it?
thx

A: Make a plugin:
Example: http://jsfiddle.net/YbGtE/2/
(function($) {
    $.fn.makeRadios = function() {
        var $items = this;
        return this.click(function() {
            $items.removeAttr('checked');
            $(this).attr('checked', true);
        });
    };
})( jQuery );

$('input.apples').makeRadios();
$('input.bananas').makeRadios();

EDIT: As requested in the comment below, to uncheck a checkbox on a double click, do this:
Example: http://jsfiddle.net/YbGtE/3/
(function($) {
    $.fn.makeRadios = function() {
        var $items = this;
        return this.click(function() {
            $items.removeAttr('checked');
            $(this).attr('checked', true);
        }).dblclick(function() {
            $items.removeAttr('checked');
        });
    };
})( jQuery );

$('input.apples').makeRadios();
$('input.bananas').makeRadios();

A: Use the selector:
'input:checkbox'

Or, if only certain checkboxes should be changed, add a class to the selector:
'input:checkbox.makeRadio'

And add that class to the checkboxes you want changed.

A: If you assume that each group of checkboxes has the same class attribute you could automate it with:
$(function() {
    var checkboxes = $('input:checkbox.asRadio');
    checkboxes.click(function() {
        var myClass = $(this).attr('class');
        checkboxes.each(function() {
            if($(this).attr('class') == myClass) $(this).removeAttr('checked');
        });
        $(this).attr('checked', true);
    });
});

Where the checkboxes you want to behave as radio fields have the 'asRadio' class as well.


text:
Q: Emulator are not starting after updating gradle to latest version I am facing an issue while running flutter project, everything was working fine before I have added image picker library, I have tried migrating to android x, a pop up said "
No usage found for this project", Please help I am stuck for hours a go.
GRADLE FILES:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.sample_gallery"
        minSdkVersion 23
        targetSdkVersion 28
        multiDexEnabled true
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'com.android.support:multidex:1.0.3'
}

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.4-all.zip

buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        maven { url "https://jitpack.io" }
        mavenCentral()
        google()
        jcenter()

    }

    dependencies {

        classpath 'com.android.tools.build:gradle:3.6.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}

allprojects {
    repositories {
        maven {  url "https://jitpack.io" }
        mavenCentral()
        google()
        jcenter()
    }
}

ERROR:
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':flutter_plugin_android_lifecycle'.
> Could not resolve all artifacts for configuration ':flutter_plugin_android_lifecycle:classpath'.
   > Could not find gradle.jar (com.android.tools.build:gradle:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.5.0/gradle-3.5.0.jar
   > Could not find builder.jar (com.android.tools.build:builder:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/3.5.0/builder-3.5.0.jar
   > Could not find crash.jar (com.android.tools.analytics-library:crash:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/crash/26.5.0/crash-26.5.0.jar
   > Could not find lint-gradle-api.jar (com.android.tools.lint:lint-gradle-api:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/lint/lint-gradle-api/26.5.0/lint-gradle-api-26.5.0.jar
   > Could not find gradle-api.jar (com.android.tools.build:gradle-api:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle-api/3.5.0/gradle-api-3.5.0.jar
   > Could not find databinding-compiler-common.jar (androidx.databinding:databinding-compiler-common:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/databinding/databinding-compiler-common/3.5.0/databinding-compiler-common-3.5.0.jar
   > Could not find manifest-merger.jar (com.android.tools.build:manifest-merger:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/manifest-merger/26.5.0/manifest-merger-26.5.0.jar
   > Could not find sdk-common.jar (com.android.tools:sdk-common:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/sdk-common/26.5.0/sdk-common-26.5.0.jar
   > Could not find builder-test-api.jar (com.android.tools.build:builder-test-api:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/builder-test-api/3.5.0/builder-test-api-3.5.0.jar
   > Could not find ddmlib.jar (com.android.tools.ddms:ddmlib:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/ddms/ddmlib/26.5.0/ddmlib-26.5.0.jar
   > Could not find tracker.jar (com.android.tools.analytics-library:tracker:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/tracker/26.5.0/tracker-26.5.0.jar
   > Could not find sdklib.jar (com.android.tools:sdklib:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/sdklib/26.5.0/sdklib-26.5.0.jar
   > Could not find layoutlib-api.jar (com.android.tools.layoutlib:layoutlib-api:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/layoutlib/layoutlib-api/26.5.0/layoutlib-api-26.5.0.jar
   > Could not find dvlib.jar (com.android.tools:dvlib:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/dvlib/26.5.0/dvlib-26.5.0.jar
   > Could not find repository.jar (com.android.tools:repository:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/repository/26.5.0/repository-26.5.0.jar
   > Could not find shared.jar (com.android.tools.analytics-library:shared:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/shared/26.5.0/shared-26.5.0.jar
   > Could not find common.jar (com.android.tools:common:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/common/26.5.0/common-26.5.0.jar
   > Could not find jetifier-processor.jar (com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta04).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/jetifier/jetifier-processor/1.0.0-beta04/jetifier-processor-1.0.0-beta04.jar
   > Could not find bundletool.jar (com.android.tools.build:bundletool:0.9.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/bundletool/0.9.0/bundletool-0.9.0.jar
   > Could not find jetifier-core.jar (com.android.tools.build.jetifier:jetifier-core:1.0.0-beta04).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/jetifier/jetifier-core/1.0.0-beta04/jetifier-core-1.0.0-beta04.jar
   > Could not find protos.jar (com.android.tools.analytics-library:protos:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/protos/26.5.0/protos-26.5.0.jar
   > Could not find builder-model.jar (com.android.tools.build:builder-model:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/builder-model/3.5.0/builder-model-3.5.0.jar
   > Could not find apkzlib.jar (com.android.tools.build:apkzlib:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/apkzlib/3.5.0/apkzlib-3.5.0.jar
   > Could not find apksig.jar (com.android.tools.build:apksig:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/apksig/3.5.0/apksig-3.5.0.jar
   > Could not find annotations.jar (com.android.tools:annotations:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/annotations/26.5.0/annotations-26.5.0.jar
   > Could not find databinding-common.jar (androidx.databinding:databinding-common:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/databinding/databinding-common/3.5.0/databinding-common-3.5.0.jar
   > Could not find baseLibrary.jar (com.android.databinding:baseLibrary:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/databinding/baseLibrary/3.5.0/baseLibrary-3.5.0.jar
> Could not get unknown property 'android' for project ':flutter_plugin_android_lifecycle' of type org.gradle.api.Project.

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

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try using Jetifier to solve the incompatibility.
Building plugin flutter_plugin_android_lifecycle...
Running Gradle task 'assembleAarRelease'...

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'flutter_plugin_android_lifecycle'.
> Could not resolve all artifacts for configuration ':classpath'.
   > Could not find gradle.jar (com.android.tools.build:gradle:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.5.0/gradle-3.5.0.jar
   > Could not find builder.jar (com.android.tools.build:builder:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/3.5.0/builder-3.5.0.jar
   > Could not find crash.jar (com.android.tools.analytics-library:crash:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/crash/26.5.0/crash-26.5.0.jar
   > Could not find lint-gradle-api.jar (com.android.tools.lint:lint-gradle-api:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/lint/lint-gradle-api/26.5.0/lint-gradle-api-26.5.0.jar
   > Could not find gradle-api.jar (com.android.tools.build:gradle-api:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle-api/3.5.0/gradle-api-3.5.0.jar
   > Could not find databinding-compiler-common.jar (androidx.databinding:databinding-compiler-common:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/databinding/databinding-compiler-common/3.5.0/databinding-compiler-common-3.5.0.jar
   > Could not find manifest-merger.jar (com.android.tools.build:manifest-merger:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/manifest-merger/26.5.0/manifest-merger-26.5.0.jar
   > Could not find sdk-common.jar (com.android.tools:sdk-common:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/sdk-common/26.5.0/sdk-common-26.5.0.jar
   > Could not find builder-test-api.jar (com.android.tools.build:builder-test-api:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/builder-test-api/3.5.0/builder-test-api-3.5.0.jar
   > Could not find ddmlib.jar (com.android.tools.ddms:ddmlib:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/ddms/ddmlib/26.5.0/ddmlib-26.5.0.jar
   > Could not find tracker.jar (com.android.tools.analytics-library:tracker:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/tracker/26.5.0/tracker-26.5.0.jar
   > Could not find sdklib.jar (com.android.tools:sdklib:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/sdklib/26.5.0/sdklib-26.5.0.jar
   > Could not find layoutlib-api.jar (com.android.tools.layoutlib:layoutlib-api:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/layoutlib/layoutlib-api/26.5.0/layoutlib-api-26.5.0.jar
   > Could not find dvlib.jar (com.android.tools:dvlib:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/dvlib/26.5.0/dvlib-26.5.0.jar
   > Could not find repository.jar (com.android.tools:repository:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/repository/26.5.0/repository-26.5.0.jar
   > Could not find shared.jar (com.android.tools.analytics-library:shared:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/shared/26.5.0/shared-26.5.0.jar
   > Could not find common.jar (com.android.tools:common:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/common/26.5.0/common-26.5.0.jar
   > Could not find jetifier-processor.jar (com.android.tools.build.jetifier:jetifier-processor:1.0.0-beta04).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/jetifier/jetifier-processor/1.0.0-beta04/jetifier-processor-1.0.0-beta04.jar
   > Could not find bundletool.jar (com.android.tools.build:bundletool:0.9.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/bundletool/0.9.0/bundletool-0.9.0.jar
   > Could not find jetifier-core.jar (com.android.tools.build.jetifier:jetifier-core:1.0.0-beta04).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/jetifier/jetifier-core/1.0.0-beta04/jetifier-core-1.0.0-beta04.jar
   > Could not find protos.jar (com.android.tools.analytics-library:protos:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/analytics-library/protos/26.5.0/protos-26.5.0.jar
   > Could not find builder-model.jar (com.android.tools.build:builder-model:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/builder-model/3.5.0/builder-model-3.5.0.jar
   > Could not find apkzlib.jar (com.android.tools.build:apkzlib:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/apkzlib/3.5.0/apkzlib-3.5.0.jar
   > Could not find apksig.jar (com.android.tools.build:apksig:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/build/apksig/3.5.0/apksig-3.5.0.jar
   > Could not find annotations.jar (com.android.tools:annotations:26.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/tools/annotations/26.5.0/annotations-26.5.0.jar
   > Could not find databinding-common.jar (androidx.databinding:databinding-common:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/androidx/databinding/databinding-common/3.5.0/databinding-common-3.5.0.jar
   > Could not find baseLibrary.jar (com.android.databinding:baseLibrary:3.5.0).
     Searched in the following locations:
         https://dl.google.com/dl/android/maven2/com/android/databinding/baseLibrary/3.5.0/baseLibrary-3.5.0.jar

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

DEPENDENCIES:
environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter_staggered_grid_view: ^0.3.4
  image_picker: ^0.6.0+10
  flutter:
    sdk: flutter

EDIT
The error was disappeared after updating gradle and android plugin to latest version, now the build is successful but emulator ca not be launched.
SOLVED
The errors was gone after I updated Android SDK platform tools, Android Emulator and Intel packages, then I have created new project using flutter and it worked like charm!


text:
Q: Using onEdit trigger, is there a way to make sure the last row in a Sheet is visible to users? I have a Google Sheet that accumulates up to 100 entries per day. As users add new entries, the script puts new data into the last row (see snippet below). However, there are only 12 rows visible on the screen, so once those are filled, the user can't see new entries.
How can I make the last row visible to the user each time data is entered?
I am new to google-apps-script, so thanks for any ideas. I believe onEdit trigger no longer works with sheet.setActiveRange(), so I am looking for a work-around.  If there's no simple solution, I'll take a clunky one. For example, can a script be used to hide rows above the last row?
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var SHEET_NAME = 'Sheet1' // Name of current sheet
    var sheet = ss.getSheetByName(SHEET_NAME);
    var dataCell = sheet.getRange('A1');
    var lastRowNumber = sheet.getDataRange().getNumRows();
    var newData = dataCell.getValue().split(",");
    var lastRow = ss.getLastRow();

    sheet.appendRow(newData);

A: Found a solution: setActiveRange(lastRow+2, lastColumn).  Scrolls down far enough, without the need to get the range of the appended row. Added advantage is it scrolls before the row is appended, so user sees data as it goes in.
function onEdit(e) { // Puts csv user data into Sheet1
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var SHEET_NAME = 'Sheet1' // Name of current sheet
    var sheet = ss.getSheets()[0];
    var dataCell = sheet.getRange('A1');
    var newData = dataCell.getValue().split(",");

     // Gets the address of the very last cell of this sheet
     var lastRow = sheet.getLastRow();
     var lastColumn = sheet.getLastColumn();

     // Scrolls to make sure user can see 2 rows below the current last cell
     var lastCell = sheet.getRange(lastRow+2, lastColumn);

    // Puts user entered data into a new row at the bottom of the spreadsheet
    sheet.appendRow(newData);
    sheet.setActiveRange(lastCell);
}

A: You could get the newly added range by adding 1 to the lastrow and activate it:
var lastRow = ss.getLastRow();
sheet.appendRow(newData);
sheet.getRange("A" + (lastRow+1)).activate();//activate the newly appended row's A cell


text:
Q: Catch HTTP requests (including ajax) from the client I would like to write code that can catch:

*

*(1) Clicking on links or changing the window.location programmaticly

*(2) The user changes the url via the location bar

*(3) AJAX requests

Is it even possible? How do I do that?

A: *

*Yes, thats a simple step. Just give the button an action which access the server via AJAX.

*What do you mean exactly? Do you want to know where the user heading to when he do that over the location bar?

*Do you want to track every AJAX request or your goal is to send them via AJAX?

A: I don't get completely what you are trying to achieve and at what point you want to instrument the code. But in case this helps, this something that can be achieved through HTTP Proxy . On a network you can redirect the traffic trough a Proxy server where in you can have your plugged in modules that can scan the outgoing requests and take some action(action could be reporting to some other server). Of course you won't need to instrument anything here. Most of the internet firewalls peg on this I guess.


text:
Q: Insert into wordpress database - Call to a member function insert() Im having an issue with inserting data into the wordpress database through my plugin.
My plugin uses a shortcode to display a form from which some calculations are made and then that information is the then supposed to be inserted into the database but I end up getting this message.
I can't seem to get it to work?.. Any help would be appreciated greatly.
PLUGIN CODE used for the insert:
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-config.php' );
$wpdb->insert(
    'wp_wine_bookings',
    array(
        'name' => $_POST['name'],
        'last_name' => $_POST['lname'],
        'phone_number' => $_POST['phone_num'],
        'email' => $_POST['email'],
        'booking_status' => "Booked",
        'tour_name' => $_POST['tourname'],
        'tour_date' => $_POST['tourdates'],
        'number_of_people' =>  $_POST['num_ppl'],
        'price' => $_POST['priceget'],
        'state' => $_POST['state'],
        'city' => $_POST['city'],
        'country' => $_POST['country'],
        'mobile' => $_POST['mobile'],
        'preffered_pickup_point' => $_POST['locationpickup'],
        'arrival_date' => $_POST['arrivaldate'],
        'name_on_credit_card' => $_POST['cn'],
        'credit_card_type' => $_POST['type'],
        'payment_date' => date("d-m-y"),
        'occasion' => $_POST['occasion'],
        'requirementsO' => $_POST['requirementsO'],
        'requirementsP' => $_POST['requirementsP']
    ),
    array(
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s',
        '%s'
    )
);

PHP ERROR:

Fatal error: Call to a member function insert() on a non-object in
  /home/user/public_html/wp-content/plugins/BookingWT/booknow.php
  on line 52

A: First:
Why you have included the file wp-config.php? you don't need to include this at all.
Second:
You're accessing the instance of wpdb class ($wpdb). Which is in local scope.
You have to make $wpdb global:
global $wpdb;        // <--- making $wpdb as global
$wpdb->insert(
...
...


text:
Q: SyntaxError: Unexpected token T in JSON at position 0 I'm coding a Typescript application. In This application I'ld read some json file with the function d3.json, but the code doesn't work. The error is this:

SyntaxError: Unexpected token T in JSON at position 0
     at JSON.parse ()
     at Object. (d3-request.node.js:176)
     at respond (d3-request.node.js:39)
     at exports.XMLHttpRequest.onload.xhr.onreadystatechange (d3-request.node.js:30)
     at exports.XMLHttpRequest.dispatchEvent (XMLHttpRequest.js:591)
     at setState (XMLHttpRequest.js:610)
     at exports.XMLHttpRequest.handleError (XMLHttpRequest.js:532)
     at module.exports.errorHandler (XMLHttpRequest.js:459)
     at module.exports.EventEmitter.emit (events.js:81)
     at request.js:142

The code is this:
export async function setSelectConfiguration(
filenameJson: string, storeData: (str: string) => void, element: JQuery,
listenerFunction:(e: JQueryEventObject) => void) {
await d3.json("filename2.json", function(error, data) {
    if(error) {
        console.log(error);
    } else {
        console.log(data);
        storeData(data.toString())
    }
});
 element.on("change", listenerFunction);
    }

The json is this:
{
"files": [
{
        "name": "time_sensitive_test.json",
        "type": "user",
        "owner": "Master",
        "data_type": "linear data",
        "description": "Utenti master (Enrica) periodo 20/05/2014-16/10/2014",
    "ids_description": "accesso risorse",
    "ods_description": "chat/forum",
    "bds_description": "login/logout"
}
]}

the gulpfile.js:
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var tsify = require('tsify');
var sourcemaps = require('gulp-sourcemaps');
var buffer = require('vinyl-buffer');

var paths = {
    pages: ['src/*.html']
};

gulp.task('copyHtml', function () {
    return gulp.src(paths.pages)
        .pipe(gulp.dest('dist'));
   });

   gulp.task('default', ['copyHtml'], function () {
    return browserify({
       basedir: '.',
        debug: true,
        entries: ['src/main.ts'],
       cache: {},
       packageCache: {}
   })
   .plugin(tsify)
    .transform('babelify', {
        presets: ['env','stage-0'],
       extensions: ['.ts'],
        plugins: ['transform-runtime','transform-async-to-generator']
   })
    .bundle()
    .pipe(source('project.js'))
    .pipe(buffer())
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('dist'));
  });

the package.json:
    {
  "name": "project",
  "version": "1.0.0",
  "description": " Project",
  "main": "./dist/project.js",
  "directories": {
    "example": "example"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": " ... "
  },
  "author": "  ",
  "license": "ISC",
  "bugs": {
    "url": "... "
  },
  "homepage": "...",
  "devDependencies": {
    "@types/d3": "^4.10.0",
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-async-to-generator": "^6.24.1",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-stage-0": "^6.24.1",
    "babelify": "^8.0.0",
    "browserify": "^14.5.0",
    "gulp": "^3.9.1",
    "gulp-sourcemaps": "^2.6.3",
    "gulp-typescript": "^3.2.3",
    "gulp-uglify": "^3.0.0",
    "gulp-util": "^3.0.8",
    "tsify": "^3.0.4",
    "typescript": "^2.6.2",
    "vinyl-buffer": "^1.0.1",
    "vinyl-source-stream": "^2.0.0",
    "watchify": "^3.9.0"
  },
  "dependencies": {
    "@types/node": "^8.5.7",
    "babel-polyfill": "^6.26.0",
    "babel-runtime": "^6.26.0",
    "d3": "^4.12.2",
    "webpack": "^3.10.0"
  }
}

the tsconfig.json:
{
"files": [
  ...
],
"compilerOptions": {
    "module": "commonjs",
    "removeComments": true,
    "preserveConstEnums": true,
    "sourceMap": true,
    "noImplicitAny": true,
    "target": "es2015",
    "lib": ["es2015", "es2016", "dom", "es2017", "es6", "es5"],
    "experimentalAsyncFunctions": true,
    "typeRoots": [
        "./node_modules/@types"
    ]
},
"exclude": [
    "node_modules",
    "dist"
]
}

the webpack.config.json:
    module.exports = {
    context: __dirname + '/src',
    entry: ['babel-polyfill', './main.ts'],
    output: {
        path: 'dist',
        filename: 'project.js'
    },
    module: {
        loaders: [
            {
                test: /\.js/,
                exclude: /node_modules/,
                loader: 'babel',
                query: {
                    presets: ['es2015']
                }
            }
        ]
    }
};

I ran the code compiled outside the IDE, but the error appeared equally; so it should not be some strange fault of the IDE.
I've tried to  read the file with in a pure javascript app and all works fine; so the problem is not to be found in the files.
What could be the problem? for example: does it need any special modules or configurations?


text:
Q: How to run Ubuntu in VirtualBox more smoothly? How can I speed up Ubuntu in virtual box? I've allocated 2 cores, 2gb ram, 128mb vram, 3d acceleration, installed guest additions, but it's still pretty slow. Moving windows around is really choppy, launching programs is fairly slow. It's not like my main computer's bad, the VM's just not using much cpu or ram at all. I don't know what the problem is. It runs about as good as it did on my old computer, which was much worse. I thought a far better computer would run a VM more smoothly.
Edit: I have tried running the vm with 4gb of memory assigned, but it made no difference at all, it's still choppy, and the experience was pretty identical. I'm not running games or anything, just simple things like terminal for most things. But when I want to use firefox, or something similar, or even just moving a terminal window around, it's just really sluggish and choppy.

A: If you only want 19.04 feeling (e. g. apps, repositories) I'd say go for lighter flavor like Lubuntu or Xubuntu, those will work great with only 2 GB RAM.
Ubuntu 19.04 needs more than 2 GB RAM to ran smoothly—3-4 GB is decent enough, also you can try enabling Hardware Virtualization to improve your guest OS performance.
Thus, assigning more RAM might help improve overall performance—other than that you're good to go.
Related:
How do I improve the performance of my VirtualBox guest?
How do I resolve slow and choppy performance in virtualbox?
How do I enable hardware virtualization technology (VT-x) for use in Virtualbox?
Will be Ubuntu 18.04 work fine on 2GB of RAM


text:
Q: Angular access routing parameter from parent I have this Routing:
{ path: 'item/:id',
  component: parentComponent,
  children: [
    { path: 'edit', component: childComponent }
  ]
}

To navigate to this Location I use this:
this.router.navigate(['/item/' + item.id + '/edit']);

Now my Question is:
How can now my childComponent know the id? What Code do I need to get the id in the child.component.ts? (parentComponent also Needs to know the id, thats why I dont have the Parameter at the end)

A: In the child component you can add the following line.
You need to target the parent route snapshot because the current snapshot is the current route, which is the child component
constructor(private route: ActivatedRoute) {
  this.id = this.route.parent.snapshot.paramMap.get('id')
  console.log('got the id', this.id);
}

Or if you want to subscribe the param in the child component you can use instead
 constructor(private route: ActivatedRoute) {
    this.route.parent.params.subscribe(params => console.log('params id', params.id));
  }


text:
Q: git delta compression and its uses When I executed git push, it displayed following output
Counting objects: 214, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (213/213), done.
Writing objects:  26% (57/214), 27.44 MiB | 60.00 KiB/s

According to this it is clear that Git uses delta compression method. How does delta compression work ? can it be used for other applications as well ? If yes, please suggest such applications.

A: I didn't go into the details of the algorithms, but you can find useful information in the manual CH 10 and here.
Asking google, I also found this
I hope that helps!


text:
Q: How to create single JSON for all matching results? I am fetching data from the database, and while I'm fetching, I check for each result if it matches certain criteria, if it does, I want it to add the row with all the details as a new object inside the same JSON, so that I end up with a single JSON that holds all the matching rows
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if (matching criteria){
        //add row to the JSON
    }
}

Right now I can add each row and echo it, but it overwrites the previous row:
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if (matching criteria){
         $firstColumn = $result['firstColumn'];
         $secondColumn= $result['secondColumn'];
         //more columns if necessary. . .
         $myObj->firstColumn = $firstColumn ;
         $myObj->secondColumn= $secondColumn;
         $myJSON = json_encode($myObj);
         echo $myJSON;
    }
}

A: you can use PDO::fetch_object for ever row and add them to assoc array/another object and then use the json_encode on it.
something like (pseudocode not tested) it will create json array with object for every row:
$out = [];
while($result = $stmt->fetch(PDO::FETCH_OBJ)
{
    if(matching){
        $out[] = $result;
    }
}
echo json_encode($out);

A: Try this way create a array assign value to that array with myObj Data and after get collection of array convert into Json object
$data = array(array());
$i = 0;
$j = 0;
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
    if (matching criteria){
         $firstColumn = $result['firstColumn'];
         $secondColumn= $result['secondColumn'];
         //more columns if necessary. . .
         $myObj->firstColumn = $firstColumn ;
         $myObj->secondColumn= $secondColumn;
         $data[i][j]=$firstColumn;
         $j++;
         $data[i][j]=$secondCoulmn;
         $i++;
         $j--;
    }
}
$myJSON = json_encode($data);
echo $myJSON;


text:
Q: replace text with url in twitter feed I have this code:
public function linkify($status_text)
    {
      $status_text = preg_replace('/(https?:\/\/\S+)/','\1', $status_text);
      $status_text = preg_replace('/(^|\s)@(\w+)/','\1@\2',$status_text);
      $status_text = preg_replace('/(^|\s)#(\w+)/','\1#\2',$status_text);
      return $status_text;
    }

and display feeds from twitter like this
        foreach($feed as $feed_item) {
            $html .= '
';
            $html .= '' . $this->linkify($feed_item->text) . '';
            $html .= '' . $this->relativedate((strtotime($feed_item->created_at))) . '';
            $html .= '
';
        }
        echo $html;

result of this code is

Twitter Feed Text http://t.co/TnkNfxCdRu

if anyone can help me, how can I add text inside tag . for example, to be exactly like this:

Twitter Feed Text

Thank you so much

A: Just change your first preg_replace to:
  $status_text = preg_replace('~(https?://(\S+))~','$2',$status_text);


text:
Q: bedrock wordpress, Nginx proxy & node.js Problem: a server behind proxy unreachable for api listening port 3050 with bedrock wordpress.
I had deployed wordpress with Trellis to my VMs. Everything is up and running perfectly.
The wordpress site is accessible to the http://example.com but it won't able access through IP address like http://192.168.1.157
I had setup a node api that listening on port 3050. but when I try to browse/curl it with http://192.168.1.157:3050 or http://192.168.1.157/api
Chrome is return: This site can't be reached ; ERR_CONNECTION_REFUSED
I only able to reach the site with http://example.com/api
I have an Nginx reverse proxy that helps me route to my Proxmox VMs.
Here are the routing rules written on my reverse proxy:
location ~* /api/ {
    client_max_body_size 500M;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto http;
    rewrite ^/api/(.*) /$1 break;
    proxy_pass http://192.168.1.157:3050;
}

I am looking for a way, that my Trellis Wordpress can be accessed through http://192.168.1.157 . I think it will help me solve the problem.
Any advice is appreciated
Thanks


text:
Q: SwiftUI : Display preview in canvas with conditional layout I'm building a layout with some conditional controls, depending on user preference.
For example, I'm displaying a Picker (segmented) only if the user has chosen to see it (user sets a Bool to true in UserDefaults on the settings page of the app).
I tried setting that Bool as a var or constant in my preview struct, and I managed to have my Picker displayed in the canvas, but I get an error : "Argument passed to call that takes no arguments" :

Here's how I declare my Bool :
private var isBiqualif: Bool = UserDefaults.standard.bool(forKey: kbiQualif) // kbiQualif is constant string set in a separate file to avoid typos

Here's how I display my Picker :
if isBiqualif { // User has activated this in settings
                Picker("", selection: $typeSelectorIndex) {
                        ForEach(0 ..< types.count) { index in
                            Text(self.types[index]).tag(index)
                          }
               }
                .pickerStyle(SegmentedPickerStyle())
                    Divider()

                } //  End of if statement for dual rating Picker

And my latest preview attempt :
struct CreateTakeoffView_Previews: PreviewProvider {
    static var previews: some View {

     let myBool = true
        return CreateTakeoffView(isBiqualif: myBool)
    }
}

Any ideas what's going on here ?
Thanks

A: Don't make it private, such you hide var, so instead use
var isBiqualif: Bool = UserDefaults.standard.bool(forKey: kbiQualif)


text:
Q: Finding equation of circle knowing 1 point, radius and that it touches the x-axis I'm currently studying circle co-ordinate geometry, and this problem has puzzled me.
Find the equations of the circles of radius $5$, which touch the x-axis, and pass through the point $(3,1)$.
I would imagine if you drew this out, there would be two circles on either side. Also, because we know that they touch the x-axis, then another point A would be $(a - 5, 0)$, where $a$ is the centre of the circle.
The equations I've been using is:
$r^2 = (x - a)^2 + (y - b)^2$, as well as the distance formula based on Pythagoras.
Where do I go from here?

A: Draw a picture. The circle cannot go below the $x$-axis, for if it did and touched the $x$-axis, it could not go through point $(3,1)$.
So the centre $(a,b)$ is above the $x$-axis. The distance from $(a,b)$ to the $x$-axis is the radius $5$ of the circle, so $b=5$. It follows that the circle has equation of the shape
$$(x-a)^2+(y-5)^2=25.$$
Plug in $x=3$, $y=1$. We get an equation in $a$. Solve for $a$. There will be two solutions, both "nice."


text:
Q: How to change button color based on background? I write in React. On the page I have a scroll up button.

When scrolling on some blocks, it is not visible due to the fact that the colors match.

How to make it so that when it touches certain blocks of the same color as the button, it turns white.

How to track the contact of a button with a specific block? What listeners to put?

A: Since the button is probably position: fixed or position: absolute, the easiest solution would be to give CSS property mix-blend-mode a try, instead of listeners, as there is no accurate way of telling the position w.r.t to background.
Check this
Try to give mix-blend-mode: difference; for the scroll to top button.
Although I think in this case you will have the color yellow for the button when it overlaps blue.

A: Although Sanjay's answer "works", you really don't have much control over the styles you get, unless that blend-mode:difference is the look you're going for.
For more fine grained control, you need to use the IntersectionObserver API.
There's really three steps to this process:
1. Get the required options for IntersectionObserver constructor
This means you need to find out the negative margins to set as the rootMargin key. This key is part  of the configuration object of your IntersectionObserver instance.
In practice you would have to find the distance of your trigger element(in your case the floating action button) to the edges of the viewport. In the code snippet below, this is done using the getDistanceToEdge() function.
It's better to do it this way instead of statically setting your margins, since it dynamically infers the margins from the position set from your styles.
2. Tell the observer what you wish to when triggered
This is the callback which will trigger the new styles on your floating button. You need to check whether your elements are intersecting with the button using the entry.isIntersecting key, and then conditionally render the style.
3. Setup the observer with elements you wish to cause the trigger
The elements that scroll up causing your floating button to change color, should be passed to the observer, using the observer.observe() function.
The following code snippet really does all the setup you need. It won't trigger unless the element is actually underneath the button (the API internally checks vertical and horizontal overlaps).
For some reason I can't get it to work on iframes embedded in browsers. It could be something to do with the negative margins and multiple viewports.
It works perfectly on normal full page websites, as shown in this hosted link.
One little caveat is that consecutive elements that trigger the observer, will cause each other to cancel out, since the button enters the second area before fully leaving the first one. I'll leave it to someone else to figure out the specifics there.

// get the element that reacts to background elements
const fabElement = document.getElementById("fab");

// what do you want to do when it overlaps?
function reactToOverlap(entries) {
  entries.forEach((entry) => {
    if (entry.isIntersecting) fabElement.classList.add("triggered");
    else fabElement.classList.remove("triggered");
  });
}

const observerOptions = {
  rootMargin: getDistanceToEdge(fabElement)
    .map((val) => `-${val}px`)
    .join(" "), // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#rootmargin for syntax
};

const observerInstance = new IntersectionObserver(
  reactToOverlap,
  observerOptions
);

// what elements do you want to trigger the change?
const elementsToTriggerFab = document.querySelectorAll(".triggeringContent");
elementsToTriggerFab.forEach((el) => observerInstance.observe(el));

/* Represents how far the element is from the edge of the browser, in all directions. */
function getDistanceToEdge(element) {
  const elementBounds = element.getBoundingClientRect();

  // top and left margins are identical to the pixel coordinates
  const top = elementBounds.top;
  const left = elementBounds.left;

  // bottom and right need to be subtracted from the viewport bounds
  const bottom = window.innerHeight - elementBounds.bottom;
  const right = window.innerWidth - elementBounds.right;

  return [top, right, bottom, left];
}
body {
  font-size: 3rem;
  background-color: white;
  margin: 0;
  padding: 0;
}

#fab {
  background-color: blue;
  color: white;
  border-radius: 50%;
  position: fixed;
  padding: 1rem;
  bottom: 50px;
  right: 50px;
  transition-property: background-color, color;
  transition-duration: 0.5s
}

#fab.triggered {
  background-color: white;
  color: blue;
}

.normalContent {
  color: green;
  border: 10px solid green;
  height: 100vh;
}

.triggeringContent {
  height: 300px;
  background-color: blue;
  color: white;
}

.triggeringContent.avoidFab {
  margin-right: 200px;
}

Up

Other Content

Triggerring Content

Triggerring Content

Problems coming up

Triggerring Content

Triggerring Content(Error)

Other Content

Triggerring Content

Shoutout to cloned's comment for giving the idea for the solution.


text:
Q: How to use JSON+Patch with BackboneJS nested model/collection? My data model is look like the following JSON structure (just example):
var post = {
  id: 123,
  title: 'Sterling Archer',
  comments: [
    {text: 'Comment text', tags: ['tag1', 'tag2', 'tag3']},
    {text: 'Comment test', tags: ['tag2', 'tag5']}
  ]
};

In Backbone side it represented as nested model that looks likes the following:
var PostModel = Backbone.Model.extend({
   parse: function (response) {
       if (response.comments) {
          response.comments = new Backbone.Collection(response.comments);
       }
       return response;
   }
});

var post = new PostModel(post, {parse: true});

I want to apply rfc6902 (JSONPatch) specification to my structure. But the problem here is that my structure is not pure JSON but nested model/collection units.
I need best practices about how could I patch my nested backbonejs structure like in official documentation examples:
Does anybody has experience in using JSON+Patch specification in your BackboneJS applications? Please share with us.
Thanks.
EDIT: here is the short example. Let's say I need to make some modifications on my post model like comment adding:
var op = [
  { "op": "add", "path": "/comments/2", "value":  {text: 'Comment test3', tags: ['tag4']}" }
]

How could I do it with backbone:
post.appyPatch(op);

Is there any best practices or/and backbone extensions for do it?

A: I've created a working app here in Plunker using the shared code and json-patch.js library for applying the patch. I've extended PostModel with applyPatch method which applies the patch. Here is the applyPatch method code:
var PostModel = Backbone.Model.extend({
    ...
    applyPatch: function(op) {
        var postStringify = JSON.stringify(this); // JSON string
        var postAttributesJSON = JSON.parse(postStringify); // JSON object. This is same as postAttributes
        var postPatched = jsonpatch.apply_patch(postAttributesJSON, op); // Patch applied
        var changed = this.changedAttributes(postPatched); // Changed attributes
        var self = this;
        _.each(_.keys(changed), function(key) {
            if(key == 'comments') {
                self.get('comments').set(changed[key], {merge: true});
            }
        });
    }
});


text:
Q: Two inserts in one trigger casues the second insert to fail I have a triggerHandler on the Opportunity object which inserts other objects on afterInsert if it meets the criteria (Opportunity Line Item and Payment). The objects are added to a list before inserting but when the first list is inserted the next list is emptied/nulled so nothing is being inserted on the next list.
The instantiation of the lists looks like this:
static List<Membership__c> membershipsToUpdate;
static List<Case> casesToUpdate;
static List<OpportunityLineItem> oppItemsToInsert;
static List<npe01__OppPayment__c> paymentsToInsert;

public TRG_OpportunityHandler(){
    membershipsToUpdate = new List<Membership__c>();
    casesToUpdate = new List<Case>();
    oppItemsToInsert = new List<OpportunityLineItem>();
    paymentsToInsert = new List<npe01__OppPayment__c>();
}

And the inserts look like this:
  if(paymentsToInsert.size() > 0) {
        insert paymentsToInsert;
    }
    if(oppItemsToInsert.size() > 0) {
        insert oppItemsToInsert;
    }
    if(membershipsToUpdate.size() > 0) {
        update membershipsToUpdate;
    }
    if(casesToUpdate.size() > 0 ){
        update casesToUpdate;
    }

If I switch place and insert oppItemsToInsert before paymentsToInsert then oppItems are inserted but not payments. Is it really not possible to do 2 DML transactions in one trigger? How else can I do this?

A: Moving the instantiation from the constructor of the handler to inside the afterInsert trigger method solved it. Since the trigger was firing again with an update it reinstatiated the lists and nulled them: http://prntscr.com/oxnuhp


text:
Q: Highcharts Get legend "icon" in tooltip Is there any way to get the legend "icon" in tooltip? I need to show the legend "icon" in the tooltip so i can identify what series I'm referring to.
I'll try to explain it better.
When you create a chart, in the legend, next to the name of the series, there is a "mini" line, that represent the line of the series, the color, and the style.
That what I need to show in the tooltip.
I'm not referring to the dot marker but the small lines that appears in the legend.
Is that possible?
Edit:
I'm using the formatter that the tooltip api provides. There I have a reference of the point that I'm hovering on, and all the data associated to that point.
I can get the value, the chart, the series, the series to which it belongs, que point marker, almost everything.
But I can't figure how to get the little coloured line that appears next to every series name in the legend.
I guess is as simple as get one of the values that appears in the point data, but I don't know what I should look for, there are a lot of properties.

A: I found a solution.
You can look for the point.series.legendLine.
There you have all the info required for the legend svg, even you can get the outerHTML and paste directly to show the legend icon.