text:
Q: Suddenly unable to SSh and FTP into my Linux VPS I am having a very strange problem whereas I am suddenly unable to login to my VPS via SSH and FTP.
I have accessed the VPS through a control panel and restarted it. I have also checked that the ssh service is running and it's working fine.
I have checked SSH process on the local machine as well and it seems all fine too. It claims it is running.
The problem I am having is that when I try and run the command:
ssh root@*******.io

the terminal hangs and times out. This has never happened before and is also happening when I attempt to FTP in. One thing I did do earlier that may have something to do with it is run a:
sudo apt-get autoremove

on the local machine. I would assume this wouldn't uninstall anything that would be needed by the machine?
I am at a loss here and not sure where I start start to diagnose this problem so any help is appreciated. It has only started having this problem today and has never had it before.
Thanks

A: There are many reasons to block FTP and SSH
1) If your system is full. Means there is no space and other thing CPU utilisation or RAM is complete used so you cannot ssh or FTP.
2) Check Firewall rules
3) check if IP is pinged and hostname is not? It means problem is with DNS assigning provision. Check /etc/resolve.conf for that.
4) Perhaps this one is not good solution but you can try to restart system. ( Sometimes it works)
Thanks HTH

A: Did you check your IP address is blocked on the server?
Try to login from another ISP provider  and check the IP address block.
To view the blocked IP address please run the following command
iptables -L INPUT -v -n | less

A: If you recently updated, newer OpenSSH in most distros have the login with a password option disabled.  Also just prior to that, most of them deprecated DSS keys, so if you are using an old style key (not keyboard) to login either re-enable the DSS keys (in both client and server) or regenerate a new RSA key.

A: Did you test with another account ? Maybe, you are not permitted anymore to login through SSH with root.
Do you have access to a console in your VPS panel ? If so, try to look at /etc/ssh/sshd_config and check the line PermitRootLogin.

A: So, this issue has been resolved and it was nothing to do with either the VPS or my local machine.
At my work we have two gateways that allow requests in and out of the network. Yesterday, we had some internet issues and the default gateway was switched. This gateway had differing rules (stupidly) than the default one and was causing the problems that were occurring with my SSH and FTP requests.
To solve this, I changed the default gateway IP address on my local Linux machine to the original one and voila, I am able to make requests again.
Thanks for all your help.


text: Q: How to Show Data which comes from API in lightning UI page salesforce . I get the Data in the debug can any one suggest me how to what can i do to show data in UI . because i get into the login successfully but don't understand that that now how the data i will show on UI eg. Name , emai ID , profile picture etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Material mat-chips not setting to be removable Problem Statement
My problem is that when I am using Angular Material's mat-chip, it seems it cannot be set as removable even though I set it to true.

Code
<mat-form-field>
 <input matInput [matChipInputFor]="chipList" (matChipInputTokenEnd)="addOption($event)"
type="number" maxlength="4" placeholder="Enter an amount here">
 </mat-form-field>

<mat-chip-list>
<mat-chip #chipList *ngFor="let option of options" [removable]="true"
(removed)="removeOption(option)">{{option}}
</mat-chip>
</mat-chip-list>

RemoveOption Method
removeOption(option: String) {
    const index = this.options.indexOf(option);

    if (index >= 0) {
      this.options.splice(index, 1);
    }
  }

Explanation of Code
As you can see, I have set [removable] to true and (removed) with a removeOption method. These things do not work for some strange reason.
I copied the example from here: https://material.angular.io/components/chips/examples, the section with the example is named: "Chips with Input"

Actual Output
The chips show no little remove button on the right:

Expected Output
The chips with a little remove button on the right:

A: You're not able to see the icon because the section <mat-icon matChipRemove>cancel</mat-icon> is missing from the code.
Your code should look like this:
<mat-chip-list>
<mat-chip #chipList *ngFor="let option of options" [removable]="true"
(removed)="removeOption(option)">{{option}}
<mat-icon matChipRemove>cancel</mat-icon>
</mat-chip>
</mat-chip-list>

A: you are missing the icon tag.
<mat-chip-list>
<mat-chip #chipList *ngFor="let option of options" [removable]="true"
(removed)="removeOption(option)">{{option}}
<mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
</mat-chip>
</mat-chip-list>

A: You have to add the mat-icon to trigger the removal. In the material example you have:
   <mat-chip
      *ngFor="let fruit of fruits"
      [selectable]="selectable"
      [removable]="removable"
      (removed)="remove(fruit)">
      {{fruit}}
      <mat-icon matChipRemove *ngIf="removable">cancel</mat-icon>
    </mat-chip>

This contains the action to trigger matChipRemove inside the mat-icon.
Link for demo: https://stackblitz.com/angular/mjygopomxvq?file=src%2Fapp%2Fchips-autocomplete-example.html

A: Noticed that if the mat-icon or any other element that does matChipRemove has style "pointer-events: none;" then click on the mat-icon (X) doesn't remove the chip. The chip still can be removed by the keyboard backspace button. Solution - set "pointer-events: auto;"


text:
Q: Cast object to int[] I have a array (with type of Object) which I'm extracting from a System.Collections.ArrayList. And I'm now trying to cast this object to a int[] so i can use it to compare it with another int[].
Note: I'm currently using .Net Framework 7.0.0
var query = (from el in l
                     where el.ID_Seal_From != "" && el.ID_Seal_From != null
                     select new
                     {
                         conn = el.Conn_from,
                         seal = el.ID_Seal_From
                     }).ToList();

        var query2 = (from el in l
                      where el.ID_Seal_To != "" && el.ID_Seal_To != null
                      select new
                      {
                          conn = el.Conn_to,
                          seal = el.ID_Seal_To
                      }).ToList();

        var res = query.Concat(query2).ToList();

        ArrayList arrLi = new();
        List<int> indexOfEqualElements = new();
        for (int i = 0; i < res.Count; i++)
        {
            for (int j = 0; j < res.Count; j++)
            {
                if (res[i].seal.CompareTo(res[j].seal) == 0)
                {
                    indexOfEqualElements.Add(j);
                }
            }

            if (Contains(arrLi, indexOfEqualElements.ToArray()) == -1) //to avoid multiple entries
            {
                arrLi.Add(indexOfEqualElements.ToArray());
            }
            indexOfEqualElements.Clear();
        }

In the "contains" call I'm trying to compare the Elements. For this case i need to avoid, that two equal arrays get added to the list. Because afterwards i need this distinct dataset to continue

A: I'm sorry for not trying to understand all the code above, but you simply can cast all the values of an ArrayList to an IEnumerable like this:
var arrayList = new ArrayList(2)
{
    1,
    2
};

var integerEnumerable = arrayList
    .Cast<int>();

Feel free to add an .ToArray(), if you like an int[] instead.

A: ArrayList is deprecated. If you wanted a list you should use List<int>. In this instance, it seems you actually need something like a HashSet<int>.
But to just get distinct elements you can simply use DistinctBy.
var query = (
    from el in l
    where el.ID_Seal_From != "" && el.ID_Seal_From != null
    select new
    {
        conn = el.Conn_from,
        seal = el.ID_Seal_From
    });

var query2 = (
    from el in l
    where el.ID_Seal_To != "" && el.ID_Seal_To != null
    select new
    {
        conn = el.Conn_to,
        seal = el.ID_Seal_To
    });

var res = query.Concat(query2).DistinctBy(el => el.seal);


text:
Q: Matplotlib: Secondary axis shares values with both of the main axes I have added a secondary x-axis to my plot. The aim is just to provide another snippet of information to the data shown by the primary x and y axes. As you can see from the attached image, I have used twiny() command to share the y-axis and get_shared_x_axes().join(ax1,ax2) to align the secondary axis with the primary x-axis.
However, this results in plotting duplicate data. What I really need is in fact for the rectangular markers to provide another scale of information given by the circular markers in the attached image. Matplotlib examples handle this situation by writing a function for instance to convert Celsius degrees to Fahrenheit. In my case, there is no apparent relationship, just scatter data points. Could you please point me towards to the right direction? Many thanks!


text:
Q: Advanced custom field for each on range I would like to echo out an unordered list when i set my Range slider to a number. In example when i put the range slider in ACF to 4 i want my page to echo out:

*

* Flywheel 1

* Flywheel 2

* Flywheel 3

* Flywheel 4

Is this possible?
--> Edit:
I cant get this to work:
<?php
$flywheelnumber = get_field('flywheels');
if( $flywheelnumber ) {
    echo '<form class="checklist-list">';
        echo '
';
        foreach($flywheelnumber) {
            echo '
';
                echo ( $numbers );
            echo '
';
        }
        echo '
';
    echo '</form>'
}
?>


text:
Q: Lock screen does not unlock with correct password Gnome and Ubuntu 14.04 I had to reinstall recently. I installed normal Ubuntu 14.04. I then installed gnome/gnome shell/gdm. I then logged in my user to gnome. Since then I have been configuring my system.
Yesterday, unlock was working fine. Today, the automatic lock screen is not accepting my password as valid. It just takes the input like it's processing it, then takes me right back to the same password prompt. If I click the 'login as a new user' link, it takes me right back to the lock screen. Ctrl+Alt+F1, etc, does nothing.
I had to resort to a hard boot. I've tried this more then once. (first time was from automatic, idle time lock, second time was from my triggering the lock screen with the keyboard command).
I'm certain I have my password right, as I am able to get logged in after the cold boot.

A: I could resolve this issue with the following permission changes:
sudo chown root:shadow /etc/gshadow
sudo chown root:shadow /etc/gshadow-
sudo chown root:shadow /etc/shadow
sudo chown root:shadow /etc/shadow-

Found here: http://ubuntuforums.org/showthread.php?t=1006366
Check also this question: Lock screen - password incorrect

A: Neither of the other two answers solved the problem for me, but some additional searching led to this bug report:
sudo chown root:shadow /sbin/unix_chkpwd
sudo chmod 2755 /sbin/unix_chkpwd

which solved the issue for me.

A: Open a terminal and type ll | grep '.Xauthority' and make sure it is owned by you and not root.
You can chown it or just remove it, it'll come back! Now just log out and log back in.
This is one of the main reasons why you shouldn't use sudo to open GUIs, as root will take ownership of some of your files in your home directory.

A: I had a similar issue after upgrading to 20.04. If I suspended the computer and tried to log back in I could not enter my password at the login screen.
I was able to fix this by purging and then reinstall lightdm the issue was solved.
So
sudo apt purge lightdm
sudo apt install lightdm

A: I had an issue like this, my password was not getting accepted from the GUI login page. Then I logged through the recovery mode and did following:
su # followed by root password
mount -o remount,rw /
mv .bashrc bashrc_old
mv .profile profile_old
reboot

Now logging in with password will work again.

A: I faced the same problem. As I found out, it was caused by setting the DISPLAY variable in my user's .bashrc (and .profile) to 'localhost:0.0'. After commenting this definition out, I was able to log in to GUI. Otherwise, only terminal login (ctrl-alt-F1 or ssh) was possible.

A: Neither of the 5 answers solved my problem, but this did on Ubuntu 18.04:
I remembered what language/keyboard layout I have used last before letting the screen locked, then I entered my password in that language, despite what language was shown in the lock-screen app.
There is a bug in the lock-screen app which doesn't change the keyboard layout despite it shows it was changed.


text:
Q: Unable to get my ul to align properly with another div Currently i have a css for a banner at the top of my html:
    #three-d
    {
    width: 80%;
    height: 100px;
    align: center;
    border: 1px solid #424242;
    background-color: #7ca0b6;
    margin: 20px auto;
    background-image: url('three-d.jpg');
    background-repeat:no-repeat;
    background-size:100% 100%;

    color: #fff;
    text-shadow: 0px 1px 0px #999, 0px 2px 0px #888, 0px 3px 0px #777, 0px 4px 0px #666, 0px 5px 0px #555, 0px 6px 0px #444, 0px 7px 0px #333, 0px 8px 7px #001135;
    font: 80px 'ChunkFiveRegular';
    text-align:center;

and the div tag:

Banner

I have been trying to align the left of my ul layer with the banner but just seem to be unable to do it. All i get is the topbarsize div too left. The following is my code:

 Title

A

B

 Type

A

B

 Format

A

B

Here is my css for topbar and topbarsize:
#topbarsize{
width:80%;
}

#topbar{
    width: 80%;
    list-style-type: none;
}
#topbar > li:hover ul { display: inline;}

#topbar > li {
    float: left;
    margin-left: 20px;
    margin-right: 20px;
    font-family:"Georgia";
}
#topbar > li > ul {
    display: none;
    top:32px;
    position: absolute; border-style:solid; padding-left:10px; padding-right:10px;
    border-width:1px; background-color:white;list-style-type: none;}
}

.clear {
    clear: both;
}

I tried to adjust the width to 80% in both #topbar and #topbarsize but can't get a solution.

A: You have your topbarsize width set to 80% but you never center it with margin:20px auto; like you did on the #three-d. Also you are sizing the UL to 80% of 80%. You probably want the topbar to have a width:100%;
So to fix it just add
topbarsize { margin:20px auto; }
#topbar { width:100%; }

Also, in this case you do not need all those > between selectors

A: Your "topbarsize" and "three-d" containers have the same size; that's good.
To align them, you just need to center the "topbarsize" wrapper like your banner:
#topbarsize{
    width:80%;
    margin:0 auto;
}

Example: http://jsfiddle.net/fparent/bxKMf/


text:
Q: Communication between Javascript and the server I've been developing a "Form Builder" in Javascript, and coming up to the part where I'll be sending the spec for the form back to the server to be stored. The builder maintains an internal data structure that represents the fields, label, options (for select/checkbox/radio), mandatory status, and the general sorting order of the fields.
When I want to send this structure back to the server, which format should I communicate it with?
Also, when restoring a server-saved form back into my Javascript builder, should I load in the data in the same format it sent it with, or should I rebuild the fields using the builder's createField() functions?

A: When making and processing requests with JavaScript, I live and breath JSON.  It's easy to build on the client side and there are tons of parsers for the server side, so both ends get to use their native tongue as much as possible.

A: This seems like a perfect scenario for using JSON as a serialization format for the server. If you study a few examples it is not too difficult to understand.

A: Best practice on this dictates that if you are not planning to use the stored data for anything other than recreating the form then the best method is to send it back in some sort of native format (As mentioned above) With this then you can just load the data back in and requires the least processing of any method.

A: I'd implement some sort of custom text serialization and transmit plain text. As you say, you can rebuild the information doing the reversed process.

A: There's a lot of people who will push JSON. It's a lot lighter weight than XML.  Personally, I find XML to be a little more standard though.  You'll have trouble finding a server side technology that doesn't support XML. And JavaScript supports it just fine also.
You could also go a completely different route. Since you'll only be sending information back when the form design is complete, you could do it with a form submit, for a bunch of hidden fields. Create your hidden fields using JavaScript and set the values as needed.
This would probably be the best solution if didn't want to deal with JSON/XML at all.


text:
Q: TypeError: iteration over a 0-d array import numpy as np
data = np.load('fff.npy')
for line in data:
    print(line)

I am trying to open .npy file which is containing image features.
File "/home/savithri/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "/home/savithri/anaconda3/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/home/savithri/Documents/MSRIT_MTECH_2018/MTECH_PROJECT_MAIN/data/Flicker30k_Dataset/rr.py", line 3, in <module>
    for i,line in data:

TypeError: iteration over a 0-d array


text:
Q: IE8 facebook app "Navigation to the webpage was canceled" On IE8, when I go to my facebook page I get the below warning. If I hit "No" everything works, but if I hit yes I get "Navigation to the webpage was canceled" (see 2nd SS). From what I understand the warning is unavoidable in IE8, but I have seen other apps that still load okay after hitting "Yes". For example Candy crush: (https://apps.facebook.com/candycrush/?fb_source=search&ref=ts&fref=ts)
Anyone know how to resolve the "...webpage was canceled" issue?

A: Your page is on https (as required by Facebook), but you're using an iframe to load content from an insecure location (http). By clicking yes, you've effectively blocked any non-secure asset from loading on that page, including the target of that iframe (resulting in the canceled message).
So all you have to do is
<iframe src="https://domain.com/yourpage.php"></iframe>

And you should be good to go.


text:
Q: Why is this free statement causing a heap corruption error? I wrote some code but am not sure how to properly free memory dynamically allocated inside of a function.
What is the proper way to free memory without causing a heap corruption, or better yet, what is causing the corruption when trying to free `returnedAry``
  #include <stdio.h>
#include <stdlib.h>
#define MAX_NUM_DIGITS 10

void displayMainMenu(void);
int* extractUncommonDigit(int*, int);

int main() {
    displayMainMenu();

    return 0;
}

void displayMainMenu() {
    int* userAry = NULL;
    int* returnedAry = NULL;
    int menuOption;
    int numOfInts;
    int i;

    do {
        printf("\n\n*********************************************\n"
            "*                     MENU                  *\n"
            "* 1. Calling extractUncommonDigit()         *\n"
            "* 2. Quit                                   *\n"
            "*********************************************\n"
            "Select an option (1 or 2): ");
        scanf_s("%d", &menuOption);

        switch (menuOption) {
        case 1:
            printf("\n  How many integers? ");
            scanf_s("%d", &numOfInts);
            userAry = (int*)malloc(numOfInts * sizeof(int));

            for (i = 0; i < numOfInts; i++) {
                printf("    Enter integer #%d: ", i + 1);
                scanf_s("%d", &userAry[i]);
            }

            printf("\n  The original array: \n");
            for (i = 0; i < numOfInts; i++) {
                printf("    %d\n", userAry[i]);
            }

            printf("\n  Calling extractUncommonDigit() -\n");
            returnedAry = extractUncommonDigit(userAry, numOfInts);
            printf("\n  Displaying after returning the array"
                " -- The uncommon digits: ");

            if (returnedAry[0] != 0) {
                printf("\n    There is/are %d uncommon digit(s)", returnedAry[0]);
                for (int i = 1; i < returnedAry[0] + 1; i++) {
                    printf("\n      %d", *(returnedAry + i));
                }
            } else {
                printf("\n   There is/are no uncommon digit(s)");
            }
            break;
        case 2:
            free(userAry);
            /* This line causes heap corruption error
            -----------------------------------------
            free(returnedAry);
            -----------------------------------------
            */
            printf("\n  Fun Excercise ...");
            break;
        default:
            printf("\n  WRONG OPTION!");
            break;
        }
    } while (menuOption != 2);

    free(userAry);

    return;
}

int* extractUncommonDigit(int* ary, int size) {
    int* assembledAry = 0;
    int tmp;
    int** digitInfoAry = (int**)malloc(size * sizeof(int*));
    int i, j;
    int digitAry[10] = { 0 };
    int uncommonCount = 0;

    for (i = 0; i < size; i++) {
        *(digitInfoAry + i) = (int*)calloc(MAX_NUM_DIGITS, sizeof(int));
    }

    for (i = 0; i < size; i++) {
        tmp = *(ary + i) < 0 ? -(*(ary + i)) : *(ary + i);

        do {
            *(*(digitInfoAry + i) + tmp % 10) = 1;
            tmp /= 10;
        } while (tmp != 0);
    }

    for (i = 0; i < MAX_NUM_DIGITS; i++) {
        for (j = 0; j < size; j++) {
            digitAry[i] += *(*(digitInfoAry + j) + i);
        }
    }

    for (i = 0; i < MAX_NUM_DIGITS; i++) {
        if (digitAry[i] == 1) {
            uncommonCount++;
        }
    }

    assembledAry = (int*)malloc(uncommonCount * sizeof(int) + 1);
    *assembledAry = uncommonCount;

    if (uncommonCount != 0) {
        for (i = 0, j = 1; i < MAX_NUM_DIGITS; i+=2) {
            if (digitAry[i] == 1) {
                assembledAry[j] = i;
                j++;
            }
        }
        for (i = 1; i < MAX_NUM_DIGITS; i+=2) {
            if (digitAry[i] == 1) {
                assembledAry[j] = i;
                j++;
            }
        }
    }

    free(digitInfoAry);

    return assembledAry;
}

The commented text displays where the program crashes after running the debugger.
What am i doing wrong?

A: I expect the problem is here, where you don't allocate enough memory and then later write off the end of the block, invoking undefined behaviour:
assembledAry = (int*)malloc(uncommonCount * sizeof(int) + 1);

You actually want (uncommonCount + 1) * sizeof(int) bytes.
Unrelated, but you also have a leak when freeing digitInfoAry (because you don't free all the allocated pointers it contains), and you are double-freeing userAry just before leaving main.

A: If the user inputs a '1' more than once, memory leaks occur
If the user inputs a '2' after previously entering '1', one ERROR occurs
If the user inputs a '2' without having previously entered '1', two ERRORS occur
do {
    switch (menuOption) {
    case 1:
        userAry = (int*)malloc(...);    //may not get executed
        returnedAry = extractUncommonDigit(...); //may not get executed
        break;
    case 2:
        free(userAry);    //can produce ERROR
        free(returnedAry);//can produce ERROR
        break;
    default:
        break;
    }
} while (menuOption != 2);
free(userAry);            //ERROR, tried to free 'userAry' twice

and the function called:
int* extractUncommonDigit(...) {...}


text:
Q: Cocos2d 2.x Orientation issues with Kamcord framework I am using latest cocos2d 2.x with latest Kamcord version.
My application is in portrait mode, but I have some scenes where I use landscape mode by just rotating the portrait to 90 degrees.
My application is built for portrait only mode. I want to take the video of landscape screen, but when I share it on facebook/email it appears at 90 degrees to line of view.
Can I tell Kamcord where to take video in portrait mode and where to take in landscape mode, irrespective of my application orientation?

A: Are you using glRotate to rotate your OpenGL view? If so, then Kamcord won't know about your rotation. You can also email us directly at support@kamcord.com with your setup.


text:
Q: how to sort a list of tuples by two items toghether python mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]
i have a list of tuples like that:
Action: 1
Horror: 2
Adventure: 0
History: 2
Romance: 1
Comedy: 1

i want to sort this by two elements (name(Alphabetically) & value)
my result should be :
History: 2
Horror: 2
Action: 1
Comedy: 1
Romance: 1
Adventure: 0

A: The following should work:
from operator import itemgetter

sorted_list = sorted(mylist, key=itemgetter(0,1), reverse=True)

You can read more about this approach in the "Operator Module Functions" section of this doc:
https://wiki.python.org/moin/HowTo/Sorting/

A: from collections import defaultdict

mylist = [('Action',1) , ('Horror',2) , ('Adventure',0) , ('History',2) , ('Romance',1) ,('Comedy',1)]

category = defaultdict(list)

for item in mylist:
    category[item[1]].append(item[0])

sorted(category.items())
keylist = category.keys()
for key in sorted(keylist, reverse = True):
    valuelist = category[key]
    valuelist.sort()
    category[key] = valuelist
    for v in valuelist:
        print(str(v),str(key))

Output is below:
History 2
Horror 2
Action 1
Comedy 1
Romance 1
Adventure 0


text:
Q: useEffect is not called when dependencies change import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [minus, setMinus] = useState(3);
  const ref = useRef(null);

  const handleClick = () => {
    setMinus(minus - 1);
  };

  console.log(
    "--> ref and state",
    ref.current?.innerHTML ?? ref.current,
    minus
  );

  // first useEffect
  useEffect(() => {
    console.log(`denp[ref.current] >`, ref.current?.innerHTML ?? ref.current);
  }, [ref.current]);

  // second useEffect
  useEffect(() => {
    console.log(`denp[minus]>`, ref.current?.innerHTML ?? ref.current);
  }, [minus]);

  return (

      {(minus >= 0 || minus <= -5) &&
num: {minus}
}
      <button onClick={handleClick}>minus</button>

  );
}

export default App;

On the first render: the first useEffect is run and log out: denp[ref.current] > num: 3
I press the button, the state minus is updated to 2, the component is re-rendered
On the second render: the first useEffect is run and log out: denp[ref.current] > num: 2
I press the button, the state minus is updated to 1, the component is re-rendered
On the third render: the first useEffect is not run anymore
Why the first useEffect does not run on the third render?
Live code here: https://codesandbox.io/s/brave-mayer-3f8zsl

A: if you really want to use ref as a dependency, so use ref.current.innerHTML instead of ref.current.
I teseted It with ref.current.innerHTML and it worked for me
hope helping you

A: I guess you should not rely on the ref as a dependency, since it is not triggering updates, as it is said here.

A: If you are using Next.JS (maybe applies to any SSR), I would suggest also setting the dependency to ref.current?.innerHTML and then it will work.


text:
Q: Chart JS - Line chart with days in x-axis I need to draw chart with the x-axis to be in day with 12.00 AM. It is using quite alot of point
This is my desire output

But this is the output I am getting:

I am getting this weird "Object object" in the x-axis
        //I have truncated the stats as it exceeded the max length in SO
        let response = '{"stats":[ { "time":"2018-10-24 13:30:02", "occupation":"54", "liveness":"78", "efficiency":"48", "pms":"up" }, { "time":"2018-10-24 13:45:02", "occupation":"55", "liveness":"78", "efficiency":"50", "pms":"up" }, { "time":"2018-10-24 14:00:01", "occupation":"56", "liveness":"76", "efficiency":"51", "pms":"up" }, { "time":"2018-10-24 14:15:02", "occupation":"56", "liveness":"77", "efficiency":"52", "pms":"up" }, { "time":"2018-10-24 14:30:01", "occupation":"56", "liveness":"78", "efficiency":"53", "pms":"up" }, { "time":"2018-10-24 14:45:01", "occupation":"57", "liveness":"79", "efficiency":"56", "pms":"up" }, { "time":"2018-10-24 15:00:02", "occupation":"57", "liveness":"79", "efficiency":"56", "pms":"up" }]}';
        let parsedResponse = ($.parseJSON(response));

        let stats = parsedResponse.stats;
        let arrayDays = [];
        $.each(parsedResponse.days, function(key, value) {
            arrayDays.push(moment(value).toDate());
        });

        let statLength  = stats.length;
        let occupation  = [];
        let liveness    = [];
        let efficiency  = [];
        let labels      = [];

        parsedResponse = undefined;

        let dataDateTime        = '';
        let dataDateTimeFormat  = 'MMM DD HH:mm A';
        for(let index = 0; index < statLength; index++) {
            dataDateTime = moment(stats[index]['time']).format(dataDateTimeFormat);

            // occupation.push({'x': dataDateTime, 'y': stats[index]['occupation']});
            // liveness.push({'x': dataDateTime, 'y': stats[index]['liveness']});
            // efficiency.push({'x': dataDateTime, 'y': stats[index]['efficiency']});

            occupation.push(stats[index]['occupation']);
            liveness.push(stats[index]['liveness']);
            efficiency.push(stats[index]['efficiency']);
            labels.push({dataDateTime});
        }

        let fill = false;
        let color = Chart.helpers.color;
        let data = {
            labels: labels,
            datasets: [{
                label: 'Screens',
                pointRadius: 0,
                tension: 0,
                backgroundColor: color(window.chartColors.green).alpha(0.5).rgbString(),
                borderColor: window.chartColors.green,
                fill: fill,
                data: liveness
            },{
                label: 'Occupation',
                pointRadius: 0,
                tension: 0,
                backgroundColor: color(window.chartColors.blue).alpha(0.5).rgbString(),
                borderColor: window.chartColors.blue,
                fill: fill,
                data: occupation
            },{
                label: 'Efficiency',
                pointRadius: 0,
                tension: 0,
                backgroundColor: color(window.chartColors.orange).alpha(0.5).rgbString(),
                borderColor: window.chartColors.orange,
                fill: fill,
                data: efficiency
            }]
        };

        let chartOptions = {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true,
                        stepSize: 10,
                        max: 100
                    },
                    scaleLabel: {
                        display: true,
                        labelString: 'Percentage'
                    }

                }],
                xAxes: [{
                    //editing this will mess it up pretty bad
                }]
            },
            tooltips: {
                callbacks: {
                    label: function(value, index) {
                        return index.datasets[value.datasetIndex].label + ": " + value.yLabel;
                    },
                }
            }
        };

The thing is, I tried several times to edit the x-axis option but it keeps messing the output

A: Your variable dataDateTime, for some reason, you are pushing it as an object in the label value, right here:
labels.push({dataDateTime});
That's why you are getting an X-axis label with [Object object]... You have two possible solutions:
1.Change the push:
labels.push(dataDateTime);
2.Add a callback to the xAxes[0].ticks property:
xAxes: [{
  ticks: {
    callback: function(value, index, values) {
       return value.dataDateTime
    }
  }
}]

Both will work well (I tested), you also can check this fiddle that I made, to check it working (using the first solution)


text:
Q: Is there anything wrong with java-package? There is a question about How can I install Sun/Oracle's proprietary Java JDK 6/7/8 or JRE? There are 23 answers at the moment, most of them are either explaining how to do it manually (unpack, move file, create links, ...) or how to add a PPA and install a package, and none of them mentions using java-package to create your own deb package.
Creating your own deb package is very easy:
You install java-package
sudo apt-get install java-package

You download the Oracle tar.gz archive.
You create your deb package
fakeroot make-jpkg jdk-7u79-linux-x64.tar.gz

An you install it
sudo dpkg -i oracle-java7-jdk_7u79_amd64.deb

Am I missing something? Is there any reason not to use java-package? Something wrong with it?


text:
Q: How can one create a countdown timer in NetLogo? I am trying to make a Frogger-like game in NetLogo and I need to create a timer that counts down. However, I looked in Frogger and used the same procedures that create the timer but it does not work. Please advise.

A: How to create a count-down timer in NetLogo
This is a general outline of how to implement a count-down timer. This applies both to a real-time count-down, or a simulation-time count-down.

*

*Implement a variable to contain the remaining time or elapsed time.

*

*The variable is usually a global variable, unless each agent must have its own count-down. Then the variable will be a -own'd variable of the agent.
globals [ count-down ]
;; or
turtles-own [ count-down ]

*I think it's generally best to track time-remaining. The count-down variable is initialized with the duration of the count-down. This makes it easy (in a game) to implement bonuses that extend the count-down, and penalties that reduce it, by simply adding to or subrtacting from the time remaining. Tracking the "actual" time that the count-down expires (using timer + duration or something similar) is generally less useful, especially if your game can be paused. Undesired effects could occur that you would have to code around.

*Implement a procedure to initialize the count-down.
to setup-timer
   set count-down 30 ;; a 30 tick timer
   ;; if you have a display of the remaining time,
   ;; you might want to initialize it here, for example:
   ask patch max-pxcor max-pycor
   [ set plabel-color white
     set plabel count-down
   ]
end
;; this example is for global count-down.
;; for a per-agent count-down, each agent would need
;; to initialize its own count-down variable

*Implement a procedure to decrement the remaining time.
to decrement-timer
   set count-down count-down - 1
end

*Implement a procedure to test whether the count-down has expired.
to-report timer-expired?
   report ( count-down <= 0 )
end

*Implement a way to display the time remaining or elapsed time. For example:

*

*Use a patch label to show the time:
to update-timer-display
   ask patch max-pxcor max-pycor [ set plabel count-down ]
end

*use a specially defined turtle with a clock shape to show the time elapsing. Examples of this exist in the NetLogo Models Library

*Implement the action that occurs when the timer expires.

*

*This is entirely up to you.

*This may involve resetting the timer for another count-down.
To use the count-down timer in your program you must:

*

*Initialise the count-down timer where appropriate (such as when the game, or a round of the game, begins).

*Change and test the timer.

*

*This might be once per "tick", or a calulation based on real time.

*

*Decrement the count-down on whatever shedule is appropriate.

*Update the display of the timer, if desired.

*Test the timer to see if it has expired.

*Act on the expired timer.
;; a "once-per-tick" count-down
decrement-timer
update-timer-display
if timer-expired? [ act-on-expired-timer ]
;; rest of the go procedure, then...
tick

;; a "once-per-second" count-down
every 1 ;; this block runs only once per second
[ decrement-timer
  update-timer-display
  if timer-expired? [ act-on-expired-timer ]
]
;; the rest of the go procedure
tick

Recurring Events
If what you need is a way to trigger recurring events every N ticks, you may be able to simply use themodoperator with thetickscounter in yourgoprocedeure:
if ticks mod 30 = 0 [ perform-recurring-event ]

The above code line would cause the procedureperform-recurring-eventto run every time thetickscounter reached 0 or a multiple of 30. In other words, it would run every 30ticks.


text:
Q: Force CREATE PROC when table in the SQL does not exist yet (VB.NET) I am converting a lot of projects from VB6 to VB.NET. Many of these projects use the DAO method CreateQueryDef, something ADO.NET does not. I know there is a way to replicate this method in ADOX using Catalogs, but I wanted to stay with pure ADO.NET. I have been using CREATE PROC to do this, but some of the query def's in the VB6 version mention tables/queries that are not created until later. For example,
CreateQueryDef(a, "SELECT ... FROM b")
...
CreateQueryDef(b, "SELECT ...")

The way the projects are, it is not possible to simply flip these two lines. I was wondering if there is a way to force CREATE PROC a AS SELECT ... FROM b even though b does not exist yet, or if there is a different option in ADO.NET to replicate the CreateQueryDef functionality.
Thanks!

A: MS SQL Server allows you to define procedures that use tables that have not yet been created.  As long as they are present when the procedure is executed, it works.


text:
Q: How can i make a time counter using QTime() I am trying to do a time counter in python using QTime and show this time in a QLabel using PyQt. I need to do this, to show how many time has passed since my program started to work, using this format of time: 00:00:00. I read the docs of QTime and tried another code that I have searched for on the internet, but I can not make it work.
This is part of my code:
class MyApplication(QtGui.QApplication):
  def __init__(self, *args, **kwargs):
    super(MyApplication, self).__init__(*args, **kwargs)

    self.t = QTime()                      #I start QTime at the same time
    self.t.start()                        # the program starts.

    self.label_1 = QtGui.QLabel("Time since the program started:")

    self.time_label = QtGui.QLabel("00:00:00")

    self.tmr = QTimer()                   #I use QTimer because I need it
                                          #for another part of the code
    self.tmr.timeout.connect(self.clock)

  def clock(self):
    self.m = 0
    self.elapsed = self.t.elapsed()

    self.s = int((self.elapsed)/1000)
    if self.s == 60:
        self.m += 1
        self.s = 0

    self.time_sec = str(self.s)
    self.time_min = str(self.m)
    self.time = self.time_min + ":" + self.time_sec

    self.time_label.setText(self.time)     #I show the time in this QLabel()

When I build this, I get this format of time: 0:0 and after 60 seconds (it shows the seconds) I get this result: 1:0, and nothing else happens.
How can I make the time counter that I need with this format: 00:00:00. Can I do it using QTimer? Hope you can help me.
------ EDIT ------
Thanks to @amicitas and @linusg answer, I´ve tried the datetime module, and wrote this simple code:
class MyApplication(QtGui.QApplication):
  def __init__(self, *args, **kwargs):
    super(MyApplication, self).__init__(*args, **kwargs)

    self.t0 = datetime.now()

    self.tmr = QTimer()
    self.tmr.timeout.connect(self.clock)

  def.clock(self):
    self.t1 = datetime.now()

    self.hour = self.t1.hour - self.t0.hour
    self.minute = self.t1.minute - self.t0.minute
    self.second = self.t1.second - self.t0.second

    print self.hour, self.minute, self.second

But, when I build this, at the moment the counter reaches 45 seconds, it turns 45 to -15 and "1 minute" appears. This is:
When it reaches 0:0:44, it turns to 0:1:-15.
What could be the problem? And how can I show the time format that I need? This is 00:00:00. Hope you can help me.

A: I have written and tested the following code for you:
from datetime import datetime
import time

if __name__== '__main__':

    initTimeObj = datetime.now()
    nullRef = datetime(initTimeObj.year, initTimeObj.month, initTimeObj.day, 0, 0, 0)

    print("Initial time:")
    print(str(initTimeObj.hour) + ':' + str(initTimeObj.minute) + ':' + str(initTimeObj.second))
    print("")

    while(True):
        time.sleep(1)
        myDiff = datetime.now() - initTimeObj
        myTimeObj = nullRef + myDiff

        print(str(myTimeObj.hour) + ':' + str(myTimeObj.minute) + ':' + str(myTimeObj.second))

        # Now you get a counting as follows:
        # 0:0:1
        # 0:0:2
        # 0:0:3
        # ...
        # 0:0:59
        # 0:1:0
        # 0:1:1
        # 0:1:2
        # ...

This code does exactly what you need. It starts counting from 0:0:0and continues doing so. Some more tweaks might be necessary if you really want to have a double-digit format, like 00:00:00. If you want, I can look into that further.
I hope this helped you out. Please let me know if it worked for you.

A: import datetime
import time

start = datetime.datetime.now()

while True:
    elapsed_seconds = (datetime.datetime.now() - start).total_seconds()
    hour = int(elapsed_seconds // 3600)
    min = int(elapsed_seconds % 3600 // 60)
    seconds = int(elapsed_seconds % 60)
    print '{:02d}:{:02d}:{:02d}'.format(hour, minute, second)
    time.sleep(1)


text:
Q: Stepper driver reverse polarity I would like to use a MKS TB6600 4.5A drivers together with an E-cut break out board to drive Nema 23 stepper motors (3A).
My problem is that I cannot figure out how to connect the drivers to the board. Before I fry both the BOB and the driver I would like to ask for some help.
On the driver I see there are four connections: EN, DIR, CLK, GND.

On the BoB electrical diagram I see they have used a different type of driver. The break out board has 3 connections for the driver: XD ( think is the DIR on the driver), XP (I thinks the CLK on the driver) but then I have +5V and not the GND. I will not use the Enable.

I am tempted to connect the driver to the board as following:

but I am not sure if this will work or cause the board or the driver to burn.
Some advice is be appreciated.


text:
Q: core data retrieving data from sets with many to many relationships I am new to core data and am still trying to get my head around it. I have a problem that I have spent hours on trying to solve. I just can't seem to solve it and was hoping someone could help me.
I can't post images yet so here is a link to my data model:
http://yourpcsolution.net/model.png
Each relationship has an inverse. A Game can have many Periods and a Period can have many Players. A Player can be in more than one Period.
Here is my code for populating DB:
- (void) prepareDB {
Games *game = [NSEntityDescription insertNewObjectForEntityForName:@"Games" inManagedObjectContext:self.managedObjectContext];
game.date = [NSDate date];
game.name = @"Game 1";

Periods *period = [NSEntityDescription insertNewObjectForEntityForName:@"Periods" inManagedObjectContext:self.managedObjectContext];

period.date = [NSDate date];
period.name = @"1st Period";

NSMutableSet *gameSet = [[NSMutableSet alloc] initWithObjects:period, nil];

game.periods = gameSet;

Players *player = [NSEntityDescription insertNewObjectForEntityForName:@"Players" inManagedObjectContext:self.managedObjectContext];

player.name = @"Player1";

NSMutableSet *playerSet = [[NSMutableSet alloc] initWithObjects:player, nil];

period.players = playerSet;

NSError *error;
if (![self.managedObjectContext save:&error]) {
    NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}

I think that's the correct way to add data because when looking at the sql db the data is there. My problem is in trying to retrieve the players that belong to each period. Because Periods is a set in Games and Players is a set in Periods in core data. So I can't retrieve players by going:  game.periods.players
Here is my code for retrieving a Period and in the xcode log i am getting a fault:
"Relationship 'players' fault on managed object (0x8e72bc0) <Periods: 0x8e72bc0>
(entity: Periods; id: 0x8e727c0 <x-coredata://7F63902B-FCB6-4ACA-BB40-904755D37A4A/Periods/p1>;
data: {\n    date = \"2013-07-09 19:35:48 +0000\";\n
games = \"0x8e6d760 <x-coredata://7F63902B-FCB6-4ACA-BB40-904755D37A4A/Games/p1>\";\n
name = \"1st Period\";\n    players = \"<relationship fault: 0x9840330 'players'>\";\n})"

My Code for retrieving a Period:
NSString *firstPeriod = @"1st Period";
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", firstPeriod];
[request setEntity:[NSEntityDescription entityForName:@"Periods" inManagedObjectContext:self.managedObjectContext]];
[request setPredicate:predicate];

NSArray *period = [self.managedObjectContext executeFetchRequest:request error:&error];

I'm not sure how to proceed from here to retrieve the players. I know how to retrieve what Periods belong to each game but I don't know how to retrieve the players that belong to a period.  I have been trying for days to figure this out and it's just not working.
Is my data model correct?  How should I be retrieving the data?  Any help or advice is appreciated.

A: To fetch all players of a given period, the following should work:
NSString *firstPeriod = @"1st Period";

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Players" inManagedObjectContext:self.managedObjectContext]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY periodsin.name == %@", firstPeriod];
[request setPredicate:predicate];

NSArray *players = [self.managedObjectContext executeFetchRequest:request error:&error];

"ANY" in the predicate is necessary because each player is connected to multiple Periods.
Remark: The data type of a to-many relationship is NSSet, not NSMutableSet.
ADDED: To fetch all periods for a given player, you can use the following fetch request:
Players *givenPlayer = ... ; // the given player
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Periods" inManagedObjectContext:self.managedObjectContext]];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY players == %@", givenPlayer];
[request setPredicate:predicate];
NSArray *periods = [self.managedObjectContext executeFetchRequest:request error:&error];

Alternatively, you can access the relationship directly:
Players *givenPlayer = ... ; // the given player
NSArray *periods = [givenPlayer.periodsin allObjects]; // "allObjects" converts NSSet to NSArray


text:
Q: Wordpress removing slashes from shortcode output I've got a problem, what I'm trying to do is passing a url through a shortcode and use it as a background image, the problem is that the url gets processed and all the slashes gets removed. I tried removing the wordpress filter remove_filter( 'the_content', 'wpautop' );) but it doesn't seem to make any difference.
Here's my code:
function section_shortcode_func( $atts, $content = null ){
    $atts = shortcode_atts(
        [
        'bgimage' => '',
        ], $atts, 'section'
    );
    $return = '
';
}

A: Here is the correct shortcode function
function section_shortcode_func( $atts, $content = null ){

    $atts       = shortcode_atts( array( 'bgimage' => '' ), $atts);
    $bgimage    = isset( $atts['bgimage'] ) ? $atts['bgimage'] : '';

    ob_start();
    echo "
";
    return ob_get_clean();
}

Now you can call it this way
[section bgimage="xxx.xxx/wp-content/uploads/2017/10/xxx.jpg"]


text:
Q: WPF Autocomplete Textbox I have seen this question come up in a couple forums and threads but i have never seen anyone provide code to solve the question, just links to places to get toolkits that may or may not be worth dealing with.
I wanted to put a more current question with the results of my work. See my answer below.

A: First you need a handler for your normal TextChanged event handler for the TextBox:
    private bool InProg;
    internal void TBTextChanged(object sender, TextChangedEventArgs e)
                {
                var change = e.Changes.FirstOrDefault();
                if ( !InProg )
                    {
                    InProg = true;
                    var culture = new CultureInfo(CultureInfo.CurrentCulture.Name);
                    var source = ( (TextBox)sender );
                    if ( ( ( change.AddedLength - change.RemovedLength ) > 0 || source.Text.Length > 0 ) && !DelKeyPressed )
                        {
                         if ( Files.Where(x => x.IndexOf(source.Text, StringComparison.CurrentCultureIgnoreCase) == 0 ).Count() > 0 )
                            {
                            var _appendtxt = Files.FirstOrDefault(ap => ( culture.CompareInfo.IndexOf(ap, source.Text, CompareOptions.IgnoreCase) == 0 ));
                            _appendtxt = _appendtxt.Remove(0, change.Offset + 1);
                            source.Text += _appendtxt;
                            source.SelectionStart = change.Offset + 1;
                            source.SelectionLength = source.Text.Length;
                            }
                        }
                    InProg = false;
                    }
                }

Then make a simple PreviewKeyDown handler:
private static bool DelKeyPressed;
internal static void DelPressed(object sender, KeyEventArgs e)
{ if ( e.Key == Key.Back ) { DelKeyPressed = true; } else { DelKeyPressed = false; } }

In this example "Files" is a list of directory names created on application startup.
Then just attach the handlers:
public class YourClass
  {
  public YourClass()
    {
    YourTextbox.PreviewKeyDown += DelPressed;
    YourTextbox.TextChanged += TBTextChanged;
    }
  }

With this whatever you choose to put in the List will be used for the autocomplete box. This may not be a great option if you expect to have an enormous list for the autocomplete but in my app it only ever sees 20-50 items so it cycles through very quick.


text:
Q: How do I get lines with a range of number? I have a text file like this:
    1.1    2.4   10.1
    5.6   10.5    2.9
   10.8   29.2   -2.1
   12.7   29.1   -2.1
   15.2   38.5   -5.2
   25.0   41.1  -19.1

Now, I would like to obtain the lines which its 1st-column has number less than 15 using awk, sed, or any other commands. Anybody knows?
It must produce:
  1.1    2.4   10.1
  5.6   10.5    2.9
 10.8   29.2   -2.1
 12.7   29.1   -2.1

A: awk '$1<15' input_file

Test:
[jaypal:~/Temp] cat f
1.1    2.4   10.1
5.6   10.5    2.9
10.8   29.2   -2.1
12.7   29.1   -2.1
15.2   38.5   -5.2
25.0   41.1  -19.1
[jaypal:~/Temp] awk '$1<15' f
1.1    2.4   10.1
5.6   10.5    2.9
10.8   29.2   -2.1
12.7   29.1   -2.1

A: Awk is simplest:
awk '$1 < 15' filename

A: perl -lane 'print if($F[0] <15)' your_file


text:
Q: The Picker not visible in the view hierarchy warming I tried to make a Picker in swiftui with below code.
import SwiftUI

struct AddUserUIView: View {
    @Environment(\.managedObjectContext) var moc
    @Environment(\.presentationMode) var presentationMode
    @State private var type = 1
    let types = ["type1", "type2"]

    var body: some View {
        NavigationView {
            Form {
                Section {
                    Picker("The type is", selection: $type) {
                        ForEach(0 ..< types.count) {
                            Text("\(self.types[$0])")
                        }
                    }
                }
            }
            .navigationBarTitle("Add user")
        }
    }
}

This UIView is in sheet and I pass core data context into it so that it can be save in it. But it print a warming if I change the Picker value.

[TableView] Warning once only:
    UITableView was told to layout its visible cells and other contents without being in the view hierarchy (the table view or one of its superviews has not been added to a window).
    This may cause bugs by forcing views inside the table view to load and perform layout without accurate information (e.g. table view bounds, trait collection, layout margins, safe area insets, etc),
  and will also cause unnecessary performance overhead due to extra layout passes.


text:
Q: Invoke method based on list I have object in scala, where I have defined functions. I have Seq where all the functions are listed as the elements as below:
object ABC {

  def abc(a: Int, b: Int): Int = a+b
  def pqr(p: Int, q: Int): Int = p - q
  val listFunction: Seq[(Int, Int) => Int] = Seq(abc, pqr)

}

Now, I want to call the list which I defined as string and execute all the functions inside it, by taking the parameters. Similar to the below:
val listName = "listFunction"
val method = example.ABC.getClass.getMethod(listName,1,2)

Can someone help me, how to invoke the listFunction list and execute all the functions inside it.

A: To call the methods do this:
val result: Seq[Int] = ABC.listFunction.map(_(1, 2))

This calls each function in turn and puts the result in a new Seq.
If you want multiple lists indexed by name, use a Map like this:
object ABC {
  def abc(a: Int, b: Int): Int = a+b
  def pqr(p: Int, q: Int): Int = p - q

  private val functions = Map(
    "listFunction" -> Seq(abc _, pqr _),
    "listReverse" ->  Seq(pqr _, abc _),
  )
  def apply(name: String) = functions(name)
}

val listName = "listFunction"
val result: Seq[Int] = ABC(listName).map(_(1, 2))

A: Try
val listName = "listFunction"
example.ABC.getClass.getMethod(listName).invoke(example.ABC).asInstanceOf[Seq[(Int, Int) => Int]].map(_.apply(1, 2)) // List(3, -1)


text:
Q: How can i get delphi to create/open the form just like the first time I have this code:
the first time i open it does exactly what i need it to do... a student answers the questions and depending on how many right/wrong, it displays a smiley face.... the first time i open the form it works and it does that, but the second time everything runs fine but the smiley face is not displayed
procedure TFUNIDAD1_ACTIVIDAD_COMPLETA.Ipregunta1Click(Sender: TObject);
var
  x: Integer;
begin
  for x := 1 to 6 do
    if Sender = Preguntas[x] then // Valida el panel que generó el evento
    begin
      // para Moverlo
      Respuestas[vCodigo].Top := Preguntas[x].Top; // Mueve el boton ubicado en la posicion capturada
                                      //en la variable codigo
      Respuestas[vCodigo].Left := Preguntas[x].Left;/////////
      //para validar

      if x = vCodigo then // Valida si la posicion del panel que genero el evento
      begin       //es igual a la que esta almacenada en Codigo
        Imagenes[x].Picture.LoadFromFile('C:\Educso\Imagenes\Actividades\accept.bmp');
        // si son iguales pone Correcto
        vBuenas := vBuenas + 1;
      end
      else
      begin
        Imagenes[x].Picture.LoadFromFile('C:\Educso\Imagenes\Actividades\delete.bmp');
        // De lo Contrario pone Incorrecto
        vMalas := vMalas + 1;
      end;
    end;

  if vMalas + vBuenas = 6 then
  begin
    if vBuenas = 6 then
      icarita1.Visible := True
    // ICarita.Picture.LoadFromFile('C:\Educso\Imagenes\Actividades\Muy Bien.png')
    else
    if (vbuenas < 6) and (vBuenas <> 0)  then
      icarita2.Visible := True
    // ICarita.Picture.LoadFromFile('C:\Educso\Imagenes\Actividades\Bien.png')
    else
    if vBuenas = 0 then
      icarita3.Visible := True;
    // ICarita.Picture.LoadFromFile('C:\Educso\Imagenes\Actividades\Malo-1.png');
  end;
end;

Could it be because of the way i am calling the form?
if assigned (ACTIVIDAD_COMPLETA)
ACTIVIDAD_COMPLETA.free;
ACTIVIDAD_COMPLETA.close;
ACTIVIDAD_COMPLETA:=TFUNIDAD1_ACTIVIDAD_COMPLETA.CREATE(APPLICATION);
ACTIVIDAD_COMPLETA.show;

vMalas and vBuenas count how many right/wrong questions are there.
var FUNIDAD1_ACTIVIDAD_COMPLETA: TFUNIDAD1_ACTIVIDAD_COMPLETA;
Respuestas:Array [1..6] of TIMAGE;
//Respuestas Preguntas:Array[1..6] of TIMAGE;
//Preguntas Imagenes:Array[1..6] of TIMAGE;
//Cotejos vCodigo:integer;
vBuenas:Integer=0;
vMalas:Integer=0;


text:
Q: Android Studio doesn't want to open project (macOS) Android Studio 3.4.2 can't open  project on macOS 10.15 Beta (19A526h)
Open Android Studio -> press Open an existing Android Studio project -> select folder with project -> NOTHING happens
I can create new project though, but can't open existing one.
Is there anything i missing here? Any help is appreciated.

A: I have met the same problem. It works by dragging folder onto AndroidStudio directly.

A: I made it easier to open projects with Finder by associating all settings.gradle files with Android Studio and then launching that file to open a project.  (I'm on Android Studio 4.2.2)
I find that Android Studio's behavior with launching project files is inconsistent.  If you don't have any project open and you launch a project's gradle.properties file with Android Studio, then it will open the whole project, BUT if you do this when another project is open then it will just open the gradle.properties text file in the already open project!  However, for some reason this issue is avoided with settings.gradle -- it always opens the whole project even if another project is already open.

A: This problem occurs with macbook M1 macOS monterey. I solved this by,

*

*Open Settings in Android Studio

*Select Edit Custom VM options..

*Add this line to it: -Dide.mac.file.chooser.native=false

*Restart Android Studio


text:
Q: How do I start the process of debugging raw php code from a Wordpress site after an update? I need to debug some errors and formatting within a professional wordpress site. I need to do the debugging from the raw code. It is mostly php and JS. I have ended up with more than 2million lines of code after the most recent update. There are some empty box space on the home page and a list of bugs from the WP_DEBUG log.
This is my first time working with Wordpress at all. I am overwhelmed by the amount of code, and can't figure out where any of the bugs and issues are. I have worked with Angular Typescript in the past.
I would assume, to an extent, that some of these issues would be able to be fixed within the 'drag and drop' API of wordpress, but I have no idea how to use that either, when there is an already several million lined website code, and like I said, I was given the raw php code of over 2 mil lines to debug with.
I have been using VS code for the editor and MAMP as a live server.
I have no idea where to start, and I have not been able to find any useful tutorials online. Any help is greatly appreciated. I could really just use some guidance on how this process might work. Or if it even is something that people do, ever. It looks like according to the internet, this may not be the way to go about debugging. Feel free to ask questions I'll try to answer anything I can without giving away any confidential info.
Here are the bugs that show up on the site from WP_Debug:
Warning: preg_match(): No ending delimiter '*' found in C:\repos\website\wp-content\mu-plugins\no-cache.php on line 8
Warning: preg_match(): Empty regular expression in C:\repos\website\wp-content\mu-plugins\no-cache.php on line 8
Notice: Trying to get property 'Location' of non-object in C:\repos\website\wp-content\themes\Child-Theme\functions.php on line 45
Notice: Trying to get property 'Subrole' of non-object in C:\repos\website\wp-content\themes\Child-Theme\functions.php on line 46

Update: I am still having issues with these same errors. I am looking for assistance on how the process of debugging raw WP php code works, and if I am trying the right things. I can provide the code that a few errors are pointing to, but I do have to adjust the variables to maintain confidentiality.
\Child-Theme\functions.php (35-50):
if(class_exists(\RoleList\RoleList::class)) {
  wp_localize_script('site-name', 'SiteName', [
    'RoleList' => [
      'categories' => $role_categories,
      'locations' => \RoleList\Categories::getLocations(),
      'category_counts' => \RoleList\Listings::getCategoryCounts(),
    ],
    'CurrentRole' => [
      'is_role_page' => ($listing ? true : false),
      'current_category' => ($current_category ? $current_category : null),
      'current_location' => ($listing->Location ? $listing->Location : null),
      'current_subrole' => ($listing->Subrole ? $listing->Subrole : null),
      'home_url' => home_url(),
    ]
  ]);
}


text:
Q: JWT Authentication Laravel I'm trying to install jwt authentication in laravel, but I'm using laravel 5.8 and JWT, following this https://tutsforweb.com/restful-api-in-laravel-56-using-jwt-authentication/ , but display me this error.
There is any problem in my vendor/tymon/jwt-auth/src/jwt.php
between line 182 200
public function parseToken()
    {
        if (! $token = $this->parser->parseToken()) {
            throw new JWTException('The token could not be parsed from the request');
        }

        return $this->setToken($token);
    }

well and I found this suggestion and I followed this Laravel - JWT Auth The token could not be parsed from the request
public function parseToken($method = 'bearer', $header = 'authorization', $query = 'token')
{
    if (! $token = $this->parseAuthHeader($header, $method)) {
        if (! $token = $this->request->query($query, false)) {
            throw new JWTException('The token could not be parsed from the request', 400);
        }
    }

    return $this->setToken($token);
}

/**
 * Parse token from the authorization header.
 *
 * @param string $header
 * @param string $method
 *
 * @return false|string
 */
protected function parseAuthHeader($header = 'authorization', $method = 'bearer')
{
    $header = $this->request->headers->get($header);

    if (! starts_with(strtolower($header), $method)) {
        return false;
    }

    return trim(str_ireplace($method, '', $header));
}

how can I change this?

ErrorException  : Undefined property: Tymon\JWTAuth\JWTAuth::$request
  at C:\laragon\www\ecommerce\vendor\tymon\jwt-auth\src\JWT.php:203

A: Try this step to set up your JWT Login,

*

*Install JWT package in you Laravel App
documentation: https://jwt-auth.readthedocs.io/en/docs/laravel-installation/
composer require tymon/jwt-auth:dev-develop
or
composer require tymon/jwt-auth:1.0.0-rc.5

*Add JWTMiddleware in you App\Http\Middleware
https://github.com/kennethtomagan/laravel-5-api-boilerplate/blob/master/app/Http/Middleware/JWTMiddleware.php

*Register this middleware in $routeMiddleware of App\Http\kernel.php file.
protected $routeMiddleware = [
      ....
      ....
      'jwt' => \App\Http\Middleware\JWTMiddleware::class,
  ];

*Setup your controller

sample:
  https://github.com/kennethtomagan/laravel-5-api-boilerplate/blob/master/app/Http/Controllers/Auth/AuthController.php

*Setup your API route

Route::group(['middleware' => [ 'jwt', 'jwt.auth']], function () {
    ....
    ....
    });

Hope it helps,
Working example: https://github.com/kennethtomagan/laravel-5-api-boilerplate


text:
Q: How Should Custom Functions Be Called For Single Posts? I have been trying to find the answer to this. I want to use the best method performance wise, but also want to make this solution portable as possible.
I have created a plugin that adds multiple post types and custom meta fields for each of these post types. Reviews is an example of this. I have a large database that isn't a part of wordpress that contains lots of video game information. When writing a review I have a box to add the name of the game being reviewed.
I have written a function displayGameInfo($gameID) as part of my plugin. In single.php i have the following code.This will output some information for the game just after the end of the main text body of a post.
 $postid =  get_the_ID();
 $gameid = get_post_meta($postid,'nb_gameids_key', true);

 if(function_exists("displayGameInfo")) echo displayGameInfo($gameid);

People seem to be discouraging this method though and I agree with them in a way as this requires me to place a lot of custom programming within the theme. I would like if this was more portable across themes.
How should I approach this?

A: Use the_content filter to add data to a post's content without having to touch the template.


text:
Q: Python - dataframe conditional index value selection I have a dataframe similar to the below:
                       close_price  short_lower_band  long_lower_band
Equity(8554)               180.530        184.235603       183.964306
Equity(2174)               166.830        157.450404       157.160282
Equity(23921)              124.670        127.243468       126.072039
Equity(26807)              117.910        108.761587       107.190081
Equity(42950)              108.070         97.491851        96.868036
Equity(4151)                97.380         98.954371        98.335786

I want to generate a list of index values where 'close price' is less than 'short_lower_band' and less than 'long_lower_band'. So from the sample dataframe above we would get:
long_secs = [Equity(8554), Equity(23921), Equity(4151)]

Any help in figuring out how to do this would be appreciated.

A: try this:
In [334]: df
Out[334]:
               close_price  short_lower_band  long_lower_band
Equity(8554)        180.53        184.235603       183.964306
Equity(2174)        166.83        157.450404       157.160282
Equity(23921)       124.67        127.243468       126.072039
Equity(26807)       117.91        108.761587       107.190081
Equity(42950)       108.07         97.491851        96.868036
Equity(4151)         97.38         98.954371        98.335786

In [335]:

In [335]: df[(df.close_price < df.short_lower_band) & \
   .....:    (df.close_price < df.long_lower_band)].index.values
Out[335]: array(['Equity(8554)', 'Equity(23921)', 'Equity(4151)'], dtype=object)

or if you need a plain list instead of numpy array:
In [336]: df[(df.close_price < df.short_lower_band) & \
   .....:    (df.close_price < df.long_lower_band)].index.tolist()
Out[336]: ['Equity(8554)', 'Equity(23921)', 'Equity(4151)']


text:
Q: Inset images into plot I have an image (image1) in which I am detecting bright objects and showing them in image2.
Now I am determining the number of objects versus the horizontal position x inside of sliding window of dx. The resut (Transpose[{x,number}]) is stored in data.
I would like to show in a single plot

*

*data curve of number of objects versus x

*image1 above image2 above the data curve, preserving the aspect ratio of the images
Question:
How can I inset (! from knowing the plot range, size of images, ... )

*

*image1 starting directly from the upper left corner of the plot

*image2 directly below image1 (without gap)

In principle it is not necessary to inset the images into the plot, but instead somehow to produce a graphics containing in one column from top to bottom image1, image2, and the data curve, whereby the images have the same width as the frame of the plot of data.
What I did:
data = << "https://pastebin.com/raw/rgtKLSE9";

image1 = Import["https://i.imgur.com/EGkUvfU.png"];
image2 = Import["https://i.imgur.com/672v5NF.png"];

ylabel = "object number per dx=2.84 mm";

xPixelSize = 0.01420; (* in mm *)

xmax = ImageDimensions[image1][[1]]*xPixelSize;

plot = ListLinePlot[data, InterpolationOrder -> 0, PlotStyle -> {Blue},
 Epilog -> {Inset[image1, {0, 450}, {0, 0}, Scaled[1]],
   Inset[image2, {0, 350}, {0, 0}, Scaled[1]]},
 Frame -> True, FrameLabel -> {{ylabel, ""}, {"x (mm)", ""}},
 PlotRange -> {{0, xmax}, {100, 550}},
 BaseStyle -> {FontWeight -> "Bold", FontSize -> 20,
   FontFamily -> "Calibri"}, ImageSize -> 800,
 PlotStyle -> {Blue, Thick}, AxesStyle -> Thick, FrameStyle -> Thick,
 AspectRatio -> 1.5]

A: ImageAssemple  the images and use it in Inset:
inset = Inset[ImageAssemble[{{image1}, {image2}}], Scaled@{0, 1}, {Left, Top}, Scaled@1];
ListLinePlot[data, InterpolationOrder -> 0, PlotStyle -> {Blue}, Epilog -> inset,
 Frame -> True, FrameLabel -> {{ylabel, ""}, {"x (mm)", ""}},
 PlotRange -> {{0, xmax}, {100, 550}}, ImageSize -> 500,
 BaseStyle -> {FontWeight -> "Bold", FontSize -> 20, FontFamily -> "Calibri"},
 PlotStyle -> {Blue, Thick}, AxesStyle -> Thick, FrameStyle -> Thick, AspectRatio -> 1.5]

A: Use:
ListLinePlot[data, InterpolationOrder -> 0, PlotStyle -> {Blue},
Epilog -> {Inset[
GraphicsColumn[{image1, image2}, Spacings -> {0,
-360*(1. - ImageDimensions[image1][[2]]/ImageDimensions[image1][[1]])}],
Scaled[{0., 1}], {0, 0}, Scaled[1.1]]}, Frame -> True,
FrameLabel -> {{ylabel, ""}, {"x (mm)", ""}},
PlotRange -> {{0, xmax}, {100, 550}},
BaseStyle -> {FontWeight -> "Bold", FontSize -> 20,
FontFamily -> "Calibri"}, ImageSize -> 800,
PlotStyle -> {Blue, Thick}, AxesStyle -> Thick, FrameStyle -> Thick,
AspectRatio -> 1.5]


text:
Q: JavaFX Change text under Progress Indicator I want to change the text under Progress Indicator. By default, when the ProgressIndicator has completed its Progress the text is Done, I want to be able to edit this text with any user-defined text or text depending on the locale.
When I run the program output shows that text has been changed, but on the GUI it doesn't change. Please look at the following pictures :

MCVE
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Main extends Application {
    Task copyWorker;
    public static void main(String[] args) {
        Application.launch(args);
    }
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Background Processes");
        Group root = new Group();
        Scene scene = new Scene(root, 330, 120, Color.WHITE);

        BorderPane mainPane = new BorderPane();
        root.getChildren().add(mainPane);

        final Label label = new Label("Files Transfer:");
        final ProgressIndicator progressIndicator = new ProgressIndicator(0);
        progressIndicator.progressProperty().addListener(new ChangeListener<Number>() {
        @Override
        public void changed(ObservableValue<? extends Number> ov, Number t, Number newValue) {
            progressIndicator .applyCss();

            // If progress is 100% then show Text
            if (newValue.doubleValue() >= 1.0) {
                // Apply CSS so you can lookup the text
                Text text = (Text) progressIndicator .lookup(".percentage");//also I checked .lookup(.text.percentage) version
                System.out.println(text.getText());
                // This text replaces "Done"
                text.setText("some text");
                //for testing
                Text x= (Text) progressIndicator .lookup(".percentage");
                System.out.println(x.getText());//output shows that the text under progress indicator is changed
                }
      }});
        final HBox hb = new HBox();
        hb.setSpacing(5);
        hb.setAlignment(Pos.CENTER);
        hb.getChildren().addAll(label, progressIndicator);
        mainPane.setTop(hb);

        final Button startButton = new Button("Start");
        final Button cancelButton = new Button("Cancel");
        final HBox hb2 = new HBox();
        hb2.setSpacing(5);
        hb2.setAlignment(Pos.CENTER);
        hb2.getChildren().addAll(startButton, cancelButton);
        mainPane.setBottom(hb2);

        startButton.setOnAction(new EventHandler<ActionEvent>() {

            public void handle(ActionEvent event) {
                startButton.setDisable(true);
                progressIndicator.setProgress(0);
                cancelButton.setDisable(false);
                copyWorker = createWorker();

                progressIndicator.progressProperty().unbind();
                progressIndicator.progressProperty().bind(copyWorker.progressProperty());

                copyWorker.messageProperty().addListener(new ChangeListener<String>() {
                    public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                        System.out.println(newValue);
                    }
                });

                new Thread(copyWorker).start();
            }
        });
        cancelButton.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent event) {
                startButton.setDisable(false);
                cancelButton.setDisable(true);
                copyWorker.cancel(true);
                progressIndicator.progressProperty().unbind();
                progressIndicator.setProgress(0);
                System.out.println("cancelled.");
            }
        });
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public Task createWorker() {
        return new Task() {
            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(100);
                    updateMessage("100 milliseconds");
                    updateProgress(i + 1, 10);
                }
                return true;
            }
        };
    }
}

A: You need to change the text of the ProgressIndicator as well as set the width of the ProgressIndicator to the new width of the Text.
progressIndicator.progressProperty().addListener((ov, oldValue, newValue) -> {
     Text text = (Text) progressIndicator.lookup(".percentage");
     if(text!=null && text.getText().equals("Done")){
        text.setText("New Text");
        progressIndicator.setPrefWidth(text.getLayoutBounds().getWidth());
     }
});

Complete Code
import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class Main extends Application {
    Task copyWorker;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Background Processes");
        Group root = new Group();
        Scene scene = new Scene(root, 330, 120, Color.WHITE);

        BorderPane mainPane = new BorderPane();
        root.getChildren().add(mainPane);

        final Label label = new Label("Files Transfer:");
        final ProgressIndicator progressIndicator = new ProgressIndicator(0);

        final HBox hb = new HBox();
        hb.setSpacing(5);
        hb.setAlignment(Pos.CENTER);
        hb.getChildren().addAll(label, progressIndicator);
        mainPane.setTop(hb);

        final Button startButton = new Button("Start");
        final Button cancelButton = new Button("Cancel");
        final HBox hb2 = new HBox();
        hb2.setSpacing(5);
        hb2.setAlignment(Pos.CENTER);
        hb2.getChildren().addAll(startButton, cancelButton);
        mainPane.setBottom(hb2);

        startButton.setOnAction(event -> {
            startButton.setDisable(true);
            progressIndicator.setProgress(0);
            cancelButton.setDisable(false);
            copyWorker = createWorker();

            progressIndicator.progressProperty().unbind();
            progressIndicator.progressProperty().bind(copyWorker.progressProperty());

            new Thread(copyWorker).start();
        });

        cancelButton.setOnAction(event -> {
            startButton.setDisable(false);
            cancelButton.setDisable(true);
            copyWorker.cancel(true);
            progressIndicator.progressProperty().unbind();
            progressIndicator.setProgress(0);
        });

        primaryStage.setScene(scene);
        primaryStage.show();

        progressIndicator.progressProperty().addListener((observable, oldValue, newValue) -> {
            Text text = (Text) progressIndicator.lookup(".percentage");
            if (text != null && text.getText().equals("Done")) {
                text.setText("New Text");
                progressIndicator.setPrefWidth(text.getLayoutBounds().getWidth());
            }
        });
    }

    public Task createWorker() {
        return new Task() {
            @Override
            protected Object call() throws Exception {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(500);
                    updateMessage("2000 milliseconds");
                    updateProgress(i + 1, 10);
                }
                return true;
            }
        };
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

A: It's posiible to change ProgressIndicator label (and all other default labels, like TextField context menu labels) by overwrite controls bundle file. In this file you have field:
ProgressIndicator.doneString=YourTextHere

How to overwrite ResourceBundle file you'll find here:
https://stackoverflow.com/a/48773353/7746751


text:
Q: Can geom_vline be connected across facet_grid? I am using geom_facet to visualize data across different samples. I calculate a set of percentiles beforehand for every sample and supply these values to geom_vline via a separate tibble.
This allows to plot the percentiles of every sample correctly.
However, for our purpose, I would like to have the vertical lines connected across the plots. A co-worker of mine is mapping the percentiles as geom_point and geom_line across the function geom_density_ridges(), but this plotting routine is very slow compared to facet_grid, so I would like to reproduce a similar look as seen on the right-hand picture here. Thank you so much for any advice as how to connect the geom_vlines:

Edit: Here is the code to create the lefthand plots:
First create a tibble to supply the pecentiles for the vlines:
percentiles.tibble.facetplotting <- data %>%
         group_by(Batch) %>%
         summarize(p60 = unique(p60),
                   p80 = unique(p80),
                   p85 = unique(p85),
                   p90 = unique(p90),
                   p95 = unique(p95),
                   p99 = unique(p99)
                              )

Then use geom_area and facet_grid to plot:
 ggplot(data  , aes( x= data[[channel]] )  ) +
    facet_grid(Batch ~ . , scales = "free_y", switch = "y")+ # this brings the facet tag to the left

    geom_area( alpha = 0.15 ,   color = 'black', fill = 'grey',
              stat = "bin",
               binwidth = function(x) 2 * IQR(x) / (length(x)^(1/3)),
             size = 0.5    )+

    geom_vline(data=percentiles.tibble.facetplotting, aes(xintercept = p60), colour = "#a361c7"   ) +
    geom_vline(data=percentiles.tibble.facetplotting, aes(xintercept = p80), colour = "#5ba962"   ) +
    geom_vline(data=percentiles.tibble.facetplotting, aes(xintercept = p85), colour = "#c75a87"   ) +
    geom_vline(data=percentiles.tibble.facetplotting, aes(xintercept = p90), colour = "#ab973d"   ) +
    geom_vline(data=percentiles.tibble.facetplotting, aes(xintercept = p95), colour = "#648ace"   ) +
    geom_vline(data=percentiles.tibble.facetplotting, aes(xintercept = p99), colour = "#cb6342"   )+

    theme_minimal() +
    theme(axis.title.y = element_blank(), #take "count" away

      strip.text.x = element_text(size=15,  face="bold"),
      strip.background = element_rect(colour="black", fill="grey90", size=1, linetype="solid"),
      strip.text.y.left = element_text(angle = 0), # and once the tag is on the left, keep it horizontal
      panel.border=element_blank(),
      axis.line=element_line(), # turn off the x-axis line on the bottom of the facet

          panel.spacing = unit(1.2, "lines"),

    )

The graph on the right hand side is a code written by my co-worker and uses:
      ggplot(temp_set, aes(x=temp_set[, channel], y=sample_name))+
        geom_density_ridges(fill='grey', scale = 1, alpha = 0.4, quantile_lines = FALSE, quantiles = c(0.6, 0.8, 0.85, 0.90, 0.95, 0.99))+
        geom_line(data=temp_set, mapping=aes(x=p60, group = 1, color= 'p60'), orientation = 'y', size=1, alpha=0.7)+
        geom_point(data=temp_set, mapping=aes(x=p60, group = 1), color= 'black' )+
        geom_line(data=temp_set, mapping=aes(x=p80, group = 1, color= 'p80'), orientation = 'y', size=1, alpha=0.7)+
        geom_point(data=temp_set, mapping=aes(x=p80, group = 1), color= 'black' )+
        geom_line(data=temp_set, mapping=aes(x=p85, group = 1, color= 'p85'), orientation = 'y', size=1, alpha=0.7)+
        geom_point(data=temp_set, mapping=aes(x=p85, group = 1), color= 'black' )+
        geom_line(data=temp_set, mapping=aes(x=p90, group = 1, color= 'p90'), orientation = 'y', size=1, alpha=0.7)+
        geom_point(data=temp_set, mapping=aes(x=p90, group = 1), color= 'black' )+
        geom_line(data=temp_set, mapping=aes(x=p95, group = 1, color= 'p95'), orientation = 'y', size=1, alpha=0.7)+
        geom_point(data=temp_set, mapping=aes(x=p95, group = 1), color= 'black' )+
        geom_line(data=temp_set, mapping=aes(x=p99, group = 1, color= 'p99'), orientation = 'y', size=1, alpha=0.7)+
        geom_point(data=temp_set, mapping=aes(x=p99, group = 1), color= 'black' )


text:
Q: Show different value if cell is different from the one above in Excel The issue Im dealing with is that I want Excel to recognize in a range when the next cell is different from the one above and display a different value.
For example, the first four rows are the same (Apple) so the values are increasing. However, A6 (Orange) is different than A5, so I want the values to start again showing (1:1).
Value I've got  -Value I want
Apple   - (1:1)
Apple   - (2:2)
Apple   - (3:3)
Apple   - (4:4)
Orange  - (1:1)
Pear    - (1:1)
Pear    - (2:2)
Pear    - (3:3)
Grapefruit  - (1:1)
Banana  - (1:1)
Banana  - (2:2)
Hopefully you can help me out!

A: Anna you can use the below code assuming that the fruits are in column A and the required code will be in column B.
=IF(IFERROR(LEFT(A2,FIND("-",A2,1)-2),A2)=IFERROR(LEFT(B1,FIND("-",B1,1)-2),B1),IFERROR(LEFT(A2,FIND("-",A2,1)-2),A2)&" - ("&IFERROR(MID(B1,(FIND("(",B1,1)+1),1),0)+1&":"&IFERROR(MID(B1,(FIND("(",B1,1)+1),1),0)+1&")",IFERROR(LEFT(A2,FIND("-",A2,1)-2),A2)&" - (0:0)")

Also make sure to begin in column 2 not 1 (your data must has header).

A: If you want to let it begin with (1:1) not (0:0) then use the below code:
=IF(IFERROR(LEFT(A2,FIND("-",A2,1)-2),A2)=IFERROR(LEFT(B1,FIND("-",B1,1)-2),B1),IFERROR(LEFT(A2,FIND("-",A2,1)-2),A2)&" - ("&IFERROR(MID(B1,(FIND("(",B1,1)+1),1),0)+1&":"&IFERROR(MID(B1,(FIND("(",B1,1)+1),1),0)+1&")",IFERROR(LEFT(A2,FIND("-",A2,1)-2),A2)&" - (1:1)")


text:
Q: App store approval process for apps that need environment setup I am submitting an app to the App Store that interacts with a server component that each customer who buys the app has installed.
Is it appropriate to send Apple the server component and instructions for setting it up? Or should we give Apple a test account that is directed to a test server that we host.
Thanks.

A: The correct solution was to setup a test account for Apple.

A: You should always support everything your application does, so Apple can fully test it. You should also keep it simple and short: usually just the credentials so they just can login and probably some instructions if you think its necessary. This assumes that a fully testing environment should be ready for them.


text:
Q: CEPH's raw space usage I can't understand ceph raw space usage.
I have 14 HDD (14 OSD's) on 7 servers , 3TB each HDD ~ 42 TB raw space in total.
ceph -s
     osdmap e4055: 14 osds: 14 up, 14 in
      pgmap v8073416: 1920 pgs, 6 pools, 16777 GB data, 4196 kobjects
            33702 GB used, 5371 GB / 39074 GB avail

I created 4 block devices, 5 TB each:
df -h
 /dev/rbd1       5.0T  2.7T  2.4T  54% /mnt/part1
/dev/rbd2       5.0T  2.7T  2.4T  53% /mnt/part2
/dev/rbd3       5.0T  2.6T  2.5T  52% /mnt/part3
/dev/rbd4       5.0T  2.9T  2.2T  57% /mnt/part4

df shows that 10,9 TB is used in total, ceph shows that 33702 GB is used. If I have 2 copies, it must be ~ 22 TB, but now I have 33,7 TB used - 11 TB missed.
ceph osd pool get archyvas size
size: 2

ceph df
GLOBAL:
    SIZE       AVAIL     RAW USED     %RAW USED
    39074G     5326G       33747G         86.37
POOLS:
    NAME          ID     USED      %USED     MAX AVAIL     OBJECTS
    data          0          0         0         1840G           0
    metadata      1          0         0         1840G           0
    archyvas      3      4158G     10.64         1840G     1065104
    archyvas2     4      4205G     10.76         1840G     1077119
    archyvas3     5      3931G     10.06         1840G     1006920
    archyvas4     6      4483G     11.47         1840G     1148291

Block devices and OSD FS -  XFS

A: One possible source of confusion is GB vs. GiB/TB vs. TiB (base 10/base 2), but that cannot explain all of the difference here.
Ceph/RBD will try to "lazily" allocate space for your volumes.  This is why although you created four 5TB volumes, it reports 16TB used, not 20.  But 16TB is more than the sum of the "active" contents of your RBD-backed filesystems, which is only around 11TB, as you say.  Several things to note:
When you delete files in your RBD-backed filesystems, the filesystems will internally mark the blocks as free, but usually not try to "return" them to the underlying block device (RBD).  If your kernel RBD version is recent enough (3.18 or newer), you should be able to use fstrim to return freed blocks to RBD.  I suspect that you have created and deleted other files on these file systems, right?
There is also some file system overhead beyond the net data usage that is shown by df.  Besides "superblocks" and other filesystem-internal data structures, some overhead is to be expected from the granularity at which RBD allocates data.  I think RBD will always allocate 4MB chunks, even when only a portion of that is used.

A: I am no ceph expert but let me guess a little.
The block devices are not mounted without discard option. So any data you write and delete does not show up on the filesystem (/mnt/part1), but as it was once written and not trimmed, it stays on the underlying filesystem.
If you look at USED for your pools and add those together, you get 16777GB, which equals to what ceph -s shows. And if you multiply that by two (two copies), you get 33554GB, which is pretty much the space used.


text:
Q: What is the size above depth of BST This is what I have so far. I need to computes the size of the tree above at depth k.
public static int above(Node t, int k) {
    if (t == null) { return 0; }
    if (t.key > k)
       return (above(t.left, k - 1) + above(t.right, k - 1) + 1);
    else {
       return above(t.left, k - 1) + above(t.right, k - 1);
    }
}

EDIT: This code works and computes the size of the tree at depth k.
  public static int at(Node t, int k) {
     if(t == null) return 0;
     if(k == 0) return 1;
     return at(t.left, k - 1) + at(t.right, k - 1);
  }

A: I would of thought something more like this would do it... but maybe I don't understand the problem correctly.
public static int above(Node t, int k) {
    if (t == null) { return 0; }
    if (k > 0) {
        return (above(t.left, k - 1) + above(t.right, k - 1) + 1);
    } else {
        return 1;
    }
}

A: This code computes the tree size till depth k where root is at depth 1.
static int depth=0;
static int tree_size=0,k=3;
private static void inorder(Node head) {
    if(head!=null){
        depth++;
        inorder(head.left);
        if(depth<=k)
            tree_size++;
        inorder(head.right);
        depth--;
    }
}


text:
Q: Illegal instruction when trying to write linked list pointers in memory buffer I've got a block of memory I allocated, and I'm trying to divide it into blocks of a specific size, using a linked list to track them. The block size is arbitrary, so I'm using a unsigned char* as my buffer pointer.
The problem is when I get to the start of a block, and I try to cast the pointer to anything larger than that unsigned char* in order to write a pointer value. Every variation I try leads to a runtime Illegal instruction. The only variation that didn't fail is when I change my buffer pointer to be a struct containing a next pointer field, and then set that next pointer directly. But that leads to iterating over the buffer in chunks of that struct size, which doesn't line up with the desired block size.
What is the "correct" way to do this without running into these cast issues?
Edit: Added simplified code to show issue.
uint32_t maxMessageSize = 123;
uint32_t maxMessages = 5000;

uint8_t* messageBuffer;
uint32_t messageBufferSize = maxMessageSize * maxMessages;

messageBuffer = (uint8_t*)malloc( messageBufferSize );
memset( messageBuffer, 0, messageBufferSize );
uint32_t bufferOffset = 0;
while ( bufferOffset < messageBufferSize - maxMessageSize ) {
    uint32_t nextOffset = bufferOffset + maxMessageSize;
    intptr_t** messagePointerToNext = (intptr_t**)&messageBuffer[bufferOffset];
    *messagePointerToNext = (intptr_t*)&messageBuffer[nextOffset];
    bufferOffset = nextOffset;
}

A: C 2018 6.2.8 1 says:

Complete object types have alignment requirements which place restrictions on the addresses at which objects of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type…

From your description, it sounds like you are not maintaining the alignment required for the objects being used with your allocator. This results in attempting to access an object without the alignment it requires, resulting in a hardware exception.
Memory allocators often deal with this by ensuring that every pointer they return is allocated to a multiple of some fundamental alignment that serves for all supported objects, such as 16 bytes. (Or, for allocations smaller than the fundamental alignment, this may be relaxed to an alignment suitable for all possible objects that might fit in the requested space.)
Another approach is for the allocator to accept both a requested size and a requested alignment, such as mymalloc(10 * 8, 4) to request space for 10 items of size 8 bytes each of which requires alignment to a multiple of 4 bytes.
You can obtain the alignment required for an object type with _Alignof(type), such as _Alignof(double).


text:
Q: mirror the full PCB in Altium Designer I need to flip/mirror the full PCB along the Y axis. Is there any option to do that in Altium Designer?
I only find info about how to mirror a single component but no the full PCB

A: I think the following should work.

*

*Make sure all layers are visible.

*edit-select all.

*start dragging the selection.

*press y (or was it x, I can't remember what convention altium uses for flipping).

*click yes to the warning.

*drop the selection back down

You may need to fix up things like board outline afterwards.

A: You can select all the items you want to mirror on the PCB (it could be a few things or it could be everything), and then press M and then select Flip Selection. This will mirror everything but keep the board position the same. It will not mirror the board.
If you want to mirror the board itself too, then you can select everything you want including the board press M, then Move Selection, then press X.


text:
Q: Excel seeks many text strings in a cell by a list and returns an equivalent value So, I have the problem that is search some strings in a cell by the list.
For example:
sheet 1:
    A                                     B     C
   ---                                   ---   ---
1 | Cash in deposit (Branch A t/t)
2 | Borrowed from Corp. A
3 | Interest payment
4 | Int.panalty pmt
5 | Prin. Pmt
6 | Salary Pmt on April
7 | Sales abroad
8 | Branch C t/t
9 | Transferred from Company AA
10| Mortgages to DD ltd
11| Sal. Pmt on May

And at B1 cell, I enter the formula like this:
=IF(COUNT(SEARCH({"branch","corp.","company"},A1))>0,"Precol.",IF(COUNT(SEARCH({"interest","int.","prin."},A1))>0,"lo.",IF(COUNT(SEARCH("sales",A1))>0,"Sa.",IF(COUNT(SEARCH({"sal.","Salary","wage","payroll"},A1))>0,"Se.","Others"))))

The formula is too long and too many parentheses, this is not good if I have a long list to sort.
So, could you help me to shorten or create another formula more effectively than it?

A: My old formula will be long if there has many arguments.
Finally, I used lookup function to solve my question, that is such below:
IFERROR(LOOKUP(2^5,SEARCH(keyword,A1),keystring),"others")
In which:
- keyword includes Branch, corp, company ... and sales
- keystring includes Precol., Lo., Se., Sa.
But i'm not still satisfied, I want to have other solutions besides them.

A: Oh, I've just seek a new solution like this: if I name the range for "branch, corp., company ... and sales" into keyword; the range for "Precol., Lo., Se., Sa." into keystring. My formula will be =IFERROR(INDEX(keystring,MATCH(TRUE,ISNUMBER(SEARCH(keyword,A1)),0)),"Others") and Ctrl-shift-enter. I will have the similar result.


text:
Q: Convert and Split Latlong Google Map flutter List I have Latlong Google Maps Flutter response like this:
I/flutter (21690): [LatLng(-6.435887849941857, 106.85601130127908), LatLng(-6.4333171563046, 106.85805916786194), LatLng(-6.434791741881702, 106.8591035529971), LatLng(-6.436753407158089, 106.85817148536444)]

I want to convert and split like this:
[ [ -6.435887849941857, 106.85601130127908 ],[ -6.4333171563046, 106.85805916786194 ],[ -6.434791741881702, 106.8591035529971 ],[ -6.436753407158089, 106.85817148536444 ] ]

Thanks for all comments.

A: The easiest way thank to pskink is mapping:
listOfLatLng.map((e) => [e.lat, e.lng]).toList()

the other solutions:
You can loop in your list and add to new list:
List finalList = [];
for (final element in listOfLatLng) {
  finalList.add([element.lat, element.lng]);
}

or forEach instead:
List finalList = [];
listOfLatLng.forEach((element) {
  finalList.add([element.lat, element.lng]);
});