text:
Q: javascript onclick in html confusion I was going through some java code(which uses playframework) that provides some shopping cart functionality.The html page contains some javascript  (it uses jquery) which is something I have very little knowledge of.Looking through the html,I found a table like this

...

buy

...

(The template uses ${} to get dynamic values thru playframework template language)
In the entire code ,the only addItem(itemId) method I could find was in the ShoppingCart class which has this signature
public void addItem(Item item) {
...
}

When I searched for onclick ,I found this page
onclick doc,which gives the syntax of onclick as
onclick="SomeJavaScriptCode"

Going thru all the javascript code(it uses jquery and ejohn-templating)I couldn't find any method like 'addItem'
So,how does the onclick work?How would it know which method to invoke?Will it look in the entire code (javascript and java)to find a matching method?

A: somewhere you have an addItem method in your javascript code.  The code in the html is executing that method, not the addItem method you found in the java code.

A: First is it would only look for javascript methods and not java methods. Second is you can use debugging in firebug to reach to the method called.

A: It is relatively simple.
It looks like your Java code is executed on the server side, and the JavaScript (including jQuery) is executed on the client side. So the ${item.id} is executed on the server, and onClick executes whatever javascript code you provide for it on the client side.

A: I do not know playframework, but the addItem should be javascript, and public void addItem(Item item) is java code. Both are not related
This addItem javascript function is somewhere. If you are unable to find it in your code base, you can use the console of your browser (or firebug on Firefox) to see this javascript function. Go to the Script tab and search for addItem.

A: Javascript can't access server side functions unless is via AJAX or something like it. Even then, it doesn't have direct access to the funcions, but to a page that access that.
Look more carefully for that function in your Javascript using firebug, or the google chrome console. It should be there.


text:
Q: Memory Leak in plugin action I made a plugin that basically reads a CSV file and imports data to relevant tables.
However, the action seems to create an error:

Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 65015808 bytes) in /var/www/proj/wp-includes/functions.php on line

which led me to this code in functions.php:
function wp_ob_end_flush_all() {
    $levels = ob_get_level();
    for ($i=0; $i<$levels; $i++)
        ob_end_flush();
}

I did a Google and came across two popular solutions, both of which didn't seem to work.

Solution 1: disabling zlib - this is already disabled.
  Solution 2: remove_action('shutdown', 'wp_ob_end_flush_all', 1);

Solution 2 still errors  but with no message, which, isn't exactly ideal.
This is the script that's causing the error:
<?php
    ini_set('display_startup_errors', 1);
    ini_set('display_errors', 1);
    error_reporting(-1);

    # load core wp fnc
    require_once $_SERVER['DOCUMENT_ROOT']. '/wp-load.php';
    # load db functions
    require_once $_SERVER['DOCUMENT_ROOT']. '/wp-admin/includes/upgrade.php';
    # load admin fnc
    require_once $_SERVER['DOCUMENT_ROOT']. '/wp-content/plugins/vendor-module/admin/inc/admin-functions.php';

    global $wpdb;

    $admin_functions = new vendor_module_admin_functions();

    # get csv
    $file = $_FILES['csv'];

    $name = $file['name'];
    $dir = $file['tmp_name'];

    # rm spaces, replace with _
    $name = str_replace(' ', '_', $name);

    $file_location = $_SERVER['DOCUMENT_ROOT']. '/wp-content/plugins/vendor-module/uploads/import/'. $name;

    # if successfully moved, carry on, else return
    $moved = ($file['error'] == 0 ? true : false);

    $error = false;

    if (!$moved) {
        echo 'Error! CSV file may be incorrectly formatted or there was an issue in reading the file. Please try again.';
    } else {
        move_uploaded_file($dir, $file_location);

        $id = $_POST['val'];
        $type = $_POST['type'];

        $table = ($type == 1 ? 'vendor_module_type_one' : 'vendor_module_type_two');

        $handle = fopen($file_location, 'r');

        $parts = array();
        $components = array();

        $i = 0;

        while (($data = fgetcsv($handle, 1000, ',')) !== false)
        {
            if (is_array($data)) {
                if (empty($data[0])) {
                    echo 'Error! Reference can\'t be empty. Please ensure all rows are using a ref no.';
                    $error = true;

                    continue;
                }

                # get data
                $get_for_sql = 'SELECT `id` FROM `'. $wpdb->prefix. $table .'` WHERE `ref` = %s';
                $get_for_res = $wpdb->get_results($wpdb->prepare($get_for_sql, array($data[0])));

                if (count($get_for_res) <= 0) {
                    echo 'Error! Reference has no match. Please ensure the CSV is using the correct ref no.';
                    $error = true;

                    exit();
                }

                $get_for_id = $get_for_res[0]->id;

                # create data arrays
                $parts[$i]['name'] = $data[1];
                $parts[$i]['ref'] = $data[2];
                $parts[$i]['for'] = $get_for_id;

                $components[$i]['part_ref'] = $data[2];
                $components[$i]['component_ref'] = $data[3];
                $components[$i]['sku'] = $data[4];
                $components[$i]['desc'] = utf8_decode($data[5]);
                $components[$i]['req'] = $data[6];
                $components[$i]['price'] = $data[7];

                unset($get_for_id);
                unset($get_for_res);
                unset($get_for_sql);

                $i++;
            }
        }

        fclose($handle);
        unlink($file_location);

        # get unique parts only
        $parts = array_unique($parts, SORT_REGULAR);

        # check to see if part already exists, if so delete
        $search_field = ($type == 1 ? 'id_field_one' : 'id_field_two');

        $check_sql = 'SELECT `id` FROM `'. $wpdb->prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d';
        $delete_parts_sql = 'DELETE FROM `'. $wpdb->prefix .'vendor_module_parts` WHERE `'. $search_field .'` = %d';
        $delete_components_sql = 'DELETE FROM `'. $wpdb->prefix .'vendor_module_components` WHERE `part_id` = %d';

        $check_res = $wpdb->get_results($wpdb->prepare($check_sql, array($id)));

        if ($check_res) {
            $wpdb->query($wpdb->prepare($delete_parts_sql, array($id)));
        }

        $part_ids = $admin_functions->insert_parts($parts, $type);

        unset($parts);
        unset($delete_parts_sql);
        unset($search_field);
        unset($check_sql);
        unset($check_res);
        unset($i);

        # should never be empty, but just as a precaution ...
        if (!empty($part_ids)) {
            foreach ($components as $key => $component)
            {
                $components[$key]['part_id'] = $part_ids[$component['part_ref']];
            }

            # rm components from assoc part id
            foreach ($part_ids as $id)
            {
                $wpdb->query($wpdb->prepare($delete_components_sql, array($id)));
            }

            # insert components
            $admin_functions->insert_components($components);
        } else {
            echo 'Error!';
        }

        echo (!$error ? 'Success! File Successfully Imported.' : 'There be something wrong with the import. Please try again.');
    }

it's triggered through a button press and uses AJAX to handle it etc.
I'm not sure why a memory leak is occurring or why WordPress doesn't offer more useful error messages. I don't call that function.. so I'm guessing it's something WordPress is doing in the background when things are run.
My info:

PHP 7.2.10
  Apache 2.4
  Linux Mint 19

Also happens on my server:

PHP 7.1.25
  Apache 2.4
  CentOS 7.6.1810

WordPress running version: 4.9.8

A: Depending on what exactly you're trying to achieve, I agree with Tom's comment, that a WP-CLI command might be better. The advantage is that the command runs from php directly on the server (usually has no max execution time, loads different php.ini, etc.) and you don't need to involve the webserver.

If that is not possible, the next best way is probably to create a custom REST endpoint. WordPress has a class WP_REST_Controller, usually I write classes that extend this and work from there. For simplicity the following example is not using inheritence, but I try to keep to the same lingo.
1. Register new route
New/custom routes are registered via register_rest_route() like so
$version = 1;
$namespace = sprintf('acme/v%u', $version);
$base = '/import';

\register_rest_route(
    $namespace,
    $base,
    [
        [
            'methods' => \WP_REST_Server::CREATABLE,
                         // equals ['POST','PUT','PATCH']

            'callback' => [$this, 'import_csv'],
            'permission_callback' => [$this, 'get_import_permissions_check'],
            'args' => [],
            // used for OPTIONS calls, left out for simplicity's sake
        ],
    ]
);

This will create a new route that you can call via
http://www.example.com/wp-json/acme/v1/import/
   default REST start-^       ^       ^
       namespace with version-|       |-base

2. Define permissions check
Maybe you need authentication? Use nonces?
public function get_import_permissions_check($request)
{
    //TODO: implement
    return true;
}

3. Create your actual endpoint callback
The method previously defined gets passed a WP_REST_Request object, use that to access request body, etc. To stay consistent, it is usually best to return a WP_REST_Response instead of custom printing of JSON or similar.
public function import_csv($request)
{
    $data = [];
    // do stuff
    return new \WP_REST_Response($data, 200);
}

If you do all of this in OOP style, you'll get the following class
class Import_CSV
{

    /**
     * register routes for this controller
     */
    public function register_routes()
    {
        $version = 1;
        $namespace = sprintf('acme/v%u', $version);
        $base = '/import';

        \register_rest_route(
            $namespace,
            $base,
            [
                [
                    'methods' => \WP_REST_Server::CREATABLE,
                    'callback' => [$this, 'import_csv'],
                    'permission_callback' => [$this, 'get_import_permissions_check'],
                    'args' => [],
                ],
            ]
        );
    }

    /**
     * endpoint for POST|PUT|PATCH /acme/v1/import
     */
    public function import_csv($request)
    {
        $data = [];
        // do stuff
        return new \WP_REST_Response($data, 200);
    }

    /**
     * check if user is permitted to access the import route
     */
    public function get_import_permissions_check($request)
    {
        //TODO: implement
        return true;
    }

}

But .. still 404? Yes, simply defining the class sadly doesn't work (no autoloading by default :( ), so we need to run register_routes() like so (in your plugin file)
require_once 'Import_CSV.php';
add_action('rest_api_init', function(){
    $import_csv = new \Import_CSV;
    $import_csv->register_routes();
});

A: In your functions file do something like this:
add_action('wp_ajax_import_parts_abc', 'import_parts_abc');
function import_parts_abc() {
    include_once('/admin/inc/scripts/import-parts.php');
    exit();

}

Then in your js file something like this:
jQuery(document).ready(function() {
     jQuery('.my-button').click(function() {
jQuery.ajax({
            type: 'GET',
            url: ajaxurl,
            data: {
                action : 'import_parts_abc'
            },
            success: function(textStatus){
                alert('processing complete')
            },
            error: function(MLHttpRequest, textStatus, errorThrown){
                console.log(errorThrown);
            }
      });
});

});

redpajama_set_name: RedPajamaStackExchange


text:
Q: web scraping data from tables I want to scrape the annual income statement, balance sheet and cash flow of this page. https://www.google.com/finance?q=NYSE%3AIBM&fstype=ii&ei and put it into a dataframe. As you can see you can change the data by clicking on different parts of the page. Can someone show me how to scrape the annual income statement? This what I have so far. I can see the data in the soup, but I don't know how to get to it.
from bs4 import BeautifulSoup
import requests
import pandas as pd

df =pd.DataFrame()
url = 'https://www.google.com/finance?q=NYSE%3AIBM&fstype=ii&ei'
headers = {'User-Agent': 'Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46 Safari/536.5'}
r = requests.get(url,headers=headers)
soup = BeautifulSoup(r.text,'html.parser')

A: why don't you just use pandas's read_html() function? As a result you get a list of data frames (df), one for each table that can be displayed by clicking on the options (among them the annual income statement):
import pandas as pd
df = pd.read_html("https://www.google.com/finance?q=NYSE%3AIBM&fstype=ii&ei")

A: The pandas read_html should so what you want but since you asked about bs4if you were to create the tables yourself  it can be done quite easily with bs4:
from bs4 import BeautifulSoup
import requests
import pandas as pd

url = 'https://www.google.com/finance?q=NYSE%3AIBM&fstype=ii&ei'

def get_rows(table):
    # pull the data from each row, ignoring rows with no text
    for row in table.select("tr"):
        row = [x.text.strip() for x in row.select("td")]
        if row:
            yield row

def get_tables():
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    # get all the tabes using the id selector
    for table in soup.select("#fs-table"):
        # create columns from th tags in the thead and get rows from helper
        yield pd.DataFrame(list(get_rows(table)), columns=[x.text.strip() for x in table.find("thead").find_all("th")])

Which will give you six table, you can see the first  if we call next(get_tables()):
In [4]: next(get_tables())
Out[4]:
     In Millions of USD (except for per share items)  \
0                                            Revenue
1                               Other Revenue, Total
2                                      Total Revenue
3                             Cost of Revenue, Total
4                                       Gross Profit
5             Selling/General/Admin. Expenses, Total
6                             Research & Development
7                          Depreciation/Amortization
8           Interest Expense(Income) - Net Operating
9                           Unusual Expense (Income)
10                   Other Operating Expenses, Total
11                           Total Operating Expense
12                                  Operating Income
13       Interest Income(Expense), Net Non-Operating
14                     Gain (Loss) on Sale of Assets
15                                        Other, Net
16                                 Income Before Tax
17                                  Income After Tax
18                                 Minority Interest
19                              Equity In Affiliates
20                    Net Income Before Extra. Items
21                                 Accounting Change
22                           Discontinued Operations
23                                Extraordinary Item
24                                        Net Income
25                               Preferred Dividends
26      Income Available to Common Excl. Extra Items
27      Income Available to Common Incl. Extra Items
28                     Basic Weighted Average Shares
29           Basic EPS Excluding Extraordinary Items
30           Basic EPS Including Extraordinary Items
31                               Dilution Adjustment
32                   Diluted Weighted Average Shares
33         Diluted EPS Excluding Extraordinary Items
34         Diluted EPS Including Extraordinary Items
35  Dividends per Share - Common Stock Primary Issue
36                    Gross Dividends - Common Stock
37        Net Income after Stock Based Comp. Expense
38         Basic EPS after Stock Based Comp. Expense
39       Diluted EPS after Stock Based Comp. Expense
40                        Depreciation, Supplemental
41                               Total Special Items
42                    Normalized Income Before Taxes
43           Effect of Special Items on Income Taxes
44          Income Taxes Ex. Impact of Special Items
45                     Normalized Income After Taxes
46                 Normalized Income Avail to Common
47                              Basic Normalized EPS
48                            Diluted Normalized EPS

   3 months ending 2015-12-31 3 months ending 2015-09-30  \
0                   22,059.00                  19,280.00
1                           -                          -
2                   22,059.00                  19,280.00
3                   10,652.00                   9,844.00
4                   11,407.00                   9,436.00
5                    5,101.00                   4,465.00
6                    1,362.00                   1,287.00
7                       80.00                      73.00
8                           -                          -
9                       12.00                     112.00
10                    -519.00                     -32.00
11                  16,962.00                  15,659.00
12                   5,097.00                   3,621.00
13                          -                          -
14                          -                          -
15                       2.00                          -
16                   5,099.00                   3,621.00
17                   4,461.00                   2,962.00
18                          -                          -
19                          -                          -
20                   4,461.00                   2,962.00
21                          -                          -
22                          -                          -
23                          -                          -
24                   4,464.00                   2,950.00
25                          -                          -
26                   4,460.00                   2,962.00
27                   4,463.00                   2,950.00
28                          -                          -
29                          -                          -
30                          -                          -
31                          -                       0.00
32                     972.84                     978.96
33                       4.58                       3.03
34                          -                          -
35                       1.30                       1.30
36                          -                          -
37                          -                          -
38                          -                          -
39                          -                          -
40                          -                          -
41                          -                          -
42                          -                          -
43                          -                          -
44                          -                          -
45                          -                          -
46                          -                          -
47                          -                          -
48                       4.87                       2.98

   3 months ending 2015-06-30 3 months ending 2015-03-31  \
0                   20,813.00                  19,590.00
1                           -                          -
2                   20,813.00                  19,590.00
3                   10,423.00                  10,138.00
4                   10,390.00                   9,452.00
5                    4,923.00                   5,022.00
6                    1,300.00                   1,298.00
7                       72.00                      79.00
8                           -                          -
9                      178.00                     285.00
10                    -190.00                     -20.00
11                  16,716.00                  16,762.00
12                   4,097.00                   2,828.00
13                          -                          -
14                          -                          -
15                     127.00                     173.00
16                   4,224.00                   3,001.00
17                   3,526.00                   2,416.00
18                          -                          -
19                          -                          -
20                   3,526.00                   2,416.00
21                          -                          -
22                          -                          -
23                          -                          -
24                   3,449.00                   2,328.00
25                          -                          -
26                   3,526.00                   2,416.00
27                   3,449.00                   2,328.00
28                          -                          -
29                          -                          -
30                          -                          -
31                          -                          -
32                     986.70                     992.30
33                       3.57                       2.43
34                          -                          -
35                       1.30                       1.10
36                          -                          -
37                          -                          -
38                          -                          -
39                          -                          -
40                          -                          -
41                          -                          -
42                          -                          -
43                          -                          -
44                          -                          -
45                          -                          -
46                          -                          -
47                          -                          -
48                       3.56                       2.52

   3 months ending 2014-12-31
0                   24,113.00
1                           -
2                   24,113.00
3                   11,251.00
4                   12,862.00
5                    5,375.00
6                    1,320.00
7                       93.00
8                           -
9                      578.00
10                    -317.00
11                  17,018.00
12                   7,095.00
13                          -
14                          -
15                          -
16                   7,095.00
17                   5,516.00
18                          -
19                          -
20                   5,516.00
21                          -
22                          -
23                          -
24                   5,485.00
25                          -
26                   5,514.00
27                   5,483.00
28                          -
29                          -
30                          -
31                          -
32                     995.30
33                       5.54
34                          -
35                       1.10
36                          -
37                          -
38                          -
39                          -
40                          -
41                          -
42                          -
43                          -
44                          -
45                          -
46                          -
47                          -
48                       6.65

Or using lxml with xpaths:
 url = 'https://www.google.com/finance?q=NYSE%3AIBM&fstype=ii&ei'

from lxml.etree import fromstring, HTMLParser
import pandas as pd

def get_rows(table):
    for row in table.xpath(".//tr"):
        row = row.xpath("./td/text()")
        if row:
            yield row

def get_tables():
    r = requests.get(url)
    xml = fromstring(r.content, HTMLParser())
    for table in xml.xpath("//table[@id='fs-table']"):
        yield pd.DataFrame(list(get_rows(table)), columns=[x.strip() for x in table.xpath(".//th/text()")])


text:
Q: Building Dropdown component I'm having a problem building a dropdown component. In the function to get the selected item I'm having this error :

Too many re-renders. React limits the number of renders to prevent an
  infinite loop.

The code for the component :
import React, { useState } from 'react';
import PropTypes from 'prop-types';

import '../../../App.css'

function Dropdown({ items }) {

    //const [list, setList] = useState(items);

    const [selectedItem, setSelectedItem] = useState(items[0]);
    const [showItems, setShowItem] = useState(false);
    const [setExpand, setExpandState] = useState("");

    function toggleDropdown() {
        setExpandState(setExpand === "" ? "dropdown-expanded dropdown-expanded-down" : "");
        setShowItem(showItems === false ? true : false);
    };

    const Changed = (item) => {

        setShowItem(false);
        setSelectedItem(item);

    }

    return (

        <div data-dropdown="" className={`dropdown-container dropdown ${setExpand}`} onClick={toggleDropdown} >

                     {selectedItem.value}

                    {items.map(item =>

 {item.value}

                    )}

    );

}

Dropdown.propTypes = {
    items: PropTypes.array,

}

export default Dropdown;

A: The problem is on here onClick={Changed(item)}
You are calling this on each render, and it's modifying the state every render, so it gets called again recursively.
You can solve it by doing:

 Changed(item)}>
  {item.value}


text:
Q: Help with restricted domain of a function to find inverse Restrict the domain of $f(x)$ to find inverse:
\begin{align}
f(x) & = x^2+6x+9 = (x+3)^2 \\
g(x) & = \sqrt{x} - 3
\end{align}

A: The function $f$ is not one-to-one on $\Bbb R$, so in order to find an inverse for $f$, you need to find a subset $D$ of $\Bbb R$ on which $f$ is one-to-one. The graph of $y=(x+3)^2$ is symmetric about the line $x=-3$. This means that values of $x$ equidistant from $-3$ have the same image under $f$: for any $a$,
$$f(-3+a)=\big((-3+a)=3\big)^2=a^2=(-a)^2=\big((-3-a)+3\big)^2=f(-3-a)\;.$$
Thus, $D$ cannot contain both $-3+a$ and $-3-a$ for any $a$. The simplest ways to arrange this are to take $D$ to be either $$[-3,\to)=\{x\in\Bbb R:x\ge -3\}\tag{1}$$ (also written $[-3,\infty)$) or $$(\leftarrow,-3]=\{x\in\Bbb R:x\le -3\}\tag{2}$$ (also written $(-\infty,-3]$).
$$D=[-3,\to)=\{x\in\Bbb R:x\ge -3\}\;.$$
Now go back to $y=(x+3)^2$ and solve for $x$ in terms of $y$: $x+3=\pm\sqrt y$, and $x=\pm\sqrt y-3$. If we choose the positive square root, we get the function $g(x)=\sqrt x-3$; if we choose the negative square root, we get the function $h(x)=-\sqrt x-3$. Each of these is an inverse of $f$ on some domain, and it's not hard to check that $g$ goes with the domain $(1)$ and $h$ with the domain $(2)$: for any $x\ge 0$, $g(x)=\sqrt x-3\ge-3$ and $h(x)=-\sqrt x-3\le-3$.
In most contexts it's more natural to choose the function $g$ and the domain $(1)$: the function $g(x)=\sqrt x-3$ is the inverse of the restriction of $f$ to the domain $[-3,\to)$.


text:
Q: Determine which server is the best choice for high resource-consuming task I have a time and resource consuming task I am running every once in a while (make), which can be run on any one of a servers pool.
Problem is, I am not the only user running make, and when two or more unaware users run make simultaneously, it takes forever, and sometimes the server even crashes.
So we decided that whenever someone wants to run make, he or she must first ssh into one of the servers, make sure make is not already running on it by other user (using linux's w), and only then does he or she start make.
In my attempts to automate the process of choosing a server, I wrote a simple script, that loops on the servers pool, ssh into every one of them, and chooses the first server for which the output of w has no make in it, but this approach is too naive because it ignores the following:

*

*Each server has different attributes (e.g. one with 12 CPUs, and the other with 80 CPUs)

*make is not the only task that these servers run

*w only shows processes of users that are logged through ssh, and while make is run using ssh most of the time, it may well be that someone is running make from the server itself.

I want to change the criteria for choosing a server, but not sure what it should be.
I looked online and found the top command, but again, I am not sure what should be considered.
For example, I thought about using the criteria: $(top -bn 1 | grep 'Cpu\(s\)' | gawk '{print $2+$3+$4+$6+$7+$8}') to determine which one is the least busiest right now, but this ignores the server's attributes. There could be a busier server with considerably more CPUs.

A: You should look for a distributed task/job scheduler, cluster management system, or cloud management. A lot of these already exist; cas pointed to several in his comments and Google will turn up plenty more.
I suspect you all will be much happier once you've deployed one, and no longer have to worry about stepping on each others' toes all the time. Also, you should fix your servers so that mistakes just cause the task to fail, not bring down the machine.
If you insist on building your own (something I confess I've done—though it was 15 years ago), tasks broadly speaking consume several different types of resources, and you probably want to consider which ones your tasks take:

*

*memory (RAM) [from your goes really slow or crashes, I'd guess this is a big one for your make task]

*disk I/O bandwidth

*disk I/O operations per second (seeks)

*disk space

*CPU time

*GPU time

*network bandwidth

You can check memory usage via free, disk I/O via iostat, space with free, CPU usage via cat /proc/loadavg (on Linux) or uptime, top, ps, etc.
But of course, checking the current numbers has a problem—maybe your make job first does a few simple things taking a few minutes, then fires off the huge process that takes gigs of RAM. This could happen:

*

*Alice runs the script to start a "make" task.

*Script checks serverA, sees it has tons of free RAM, low CPU usage, starts task on serverA.

*Short while later, Bob runs the script to start some other RAM-intensive task.

*Alice's task hasn't gotten to the resource intensive phase yet. So when the script checks serverA, it still has tons of free RAM. Starts Bob's task on serverA as well.

*Bob's task eats up most of the free RAM on serverA

*Alice's task finally gets to the RAM-intensive part, but there is no RAM available now. Uh-oh! ServerA thrashes to death.

Yeah, the above comes from experience writing one (though for what I was using mine for, it was CPU time).


text:
Q: How can I remove plot margins between the axes of the plot and the plot contents in R? I want to remove the space between the axes of the plot and the plot contents themselves. Any ideas?

A: Look at the parameters xaxs and yaxs (under ?par).  By default the axis contains the data range plus 4% on either side.  If you override the parameter, then you can get an axis exactly equal to the data range.  Cf:
> curve(x^2)

> curve(x^2, xaxs="i", yaxs="i")


text:
Q: mysql/mariadb - create table column index not working So I'm trying to create my table as follows:
CREATE TABLE company
  (
    id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    name TEXT UNIQUE NOT NULL,

    INDEX(name(20))
  );

It's giving me this error:
ERROR 1170 (42000): BLOB/TEXT column 'name' used in key specification without a key length

I'm not sure why it's not working as I'm following the guide here: https://dev.mysql.com/doc/refman/5.5/en/column-indexes.html

A: You're focusing on the wrong line.
name TEXT UNIQUE NOT NULL,

Indexes on BLOB and TEXT columns must be prefix indexes, therefore, it's not possible to impose a UNIQUE constraint on a TEXT column.  You also can't make such a column part of the primary key or of a foreign key constraint.
Two common solutions:

*

*Don't use an TEXT column, use VARCHAR.

*If you really need a long column to be unique, create a second column of type CHAR, COLLATE ascii_bin, add a unique constraint to it, and size it appropriately for the base64 representation of a chosen cryptographic hash (md5, sha).  Use BEFORE INSERT and BEFORE UPDATE triggers to force this column to contain the hash of the long column, thus indirectly enforcing uniqueness.  Data type CHAR because all hashes are the same length, and ascii_bin because this is the most appropriate collation for base64.  Why base64?  It's a tradeoff of storage space for readability, using 24 characters to store an md5 hash, which is about halfway between binary (16 characters for md5, efficient) and hex (32 characters for md5, inefficient) encoding in terms of storage space.

A: I have found the error. You didn't specify the length of attribute name. Use varchar(length) instead of TEXT, where length is a number.
So your code would be if you want the name of maximum 50 letters :

CREATE TABLE company
    (
      id INT UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
      name varchar(50) UNIQUE NOT NULL,
      INDEX(name(20))
    );

You can give any value in varchar() but it should be integer.


text:
Q: What's wrong with my Timer thread? I'm updating a picture by using timer, but it causes fatal performance problem. Then I print logs and find out my timer runs faster rather than 1500.
So what's the problem?
schedule at wrong rate:

startToDraw().353: System.currentTimeMillis() = 1332742387400
  startToDraw().353: System.currentTimeMillis() = 1332742387410
  startToDraw().353: System.currentTimeMillis() = 1332742387438
  startToDraw().353: System.currentTimeMillis() = 1332742387449
  startToDraw().353: System.currentTimeMillis() = 1332742387472

timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        while (!isDestroyed) {
            try {
                Log.i(getClass().getName(), "startToDraw().353: System.currentTimeMillis() = " + System.currentTimeMillis());
                handler.sendMessage(new Message());
            } catch (Exception e) {
            }
        }
    }
}, 0, 1500);

A: I think the problem is that you are entering a while loop that runs repeatedly.  You probably just want to make a check if you are in an invalid state and then if you are, don't perform the task.  So I would change:
while (!isDestroyed) {
    try {
        Log.i(getClass().getName(), "startToDraw().353: System.currentTimeMillis() = " + System.currentTimeMillis());
        handler.sendMessage(new Message());
    } catch (Exception e) {
}

to:
if (!isDestroyed) {
    try {
        Log.i(getClass().getName(), "startToDraw().353: System.currentTimeMillis() = " + System.currentTimeMillis());
        handler.sendMessage(new Message());
    } catch (Exception e) {
}


text:
Q: python subprocess run a remote process in background and immediately close the connection The task is to use python to run a remote process in background and immediately close the ssh session.
I have a remote script name 'start' under server:PATH/, the start script does nothing but lunch a long-live background program. 'start' script which has one line:
nohup PATH/Xprogram &

When I use python subprocess module to call my remote 'start' script, it does start OK. But the issue is: it seems the SSH connection is persist, meaning I am getting stdout from the remote Xprogram (since it is a long live program which has output to stdout). Does this indicating ssh connection is still there ?
All I need is call the start script without blocking and forget about it (leave the long-live program running, close ssh, release resources).
my python function call looks like this:
ret = subprocess.Popen(["ssh", "xxx@servername", "PATH/start"])

if I use ret.terminate() after the command, it then will kill the long-live program too.
I have also tried spur module. basically the same thing.
=====update====
@Dunes' answer solves the problem. Based on his answer, I did more digging and found this link very helpful.
My understanding of this is: basically, if any file descriptor is still held by your process (e.g. stdout held by my XProgram), then SSH session won't exit. However redirect stdout/stderr to NULL effectively close those file descriptor and let SSH session exit normally.
solution
ret = subprocess.Popen(["ssh", "xxx@servername", "PATH/start >dev/null 2>&1"])

A: After playing about a bit I found that nohup doesn't seem to be properly disconnecting the child process from the parent ssh session (as it should be). This means you have to manually close stdout or point it at a file, e.g.
Using bash:
ssh user@host "nohup PATH/XProgram >&- &"

Shell agnostic (as far as I know):
ssh user@host "nohup PATH/XProgram >/dev/null 2>&1 &"

In python:
from shlex import split
from subprocess import Popen

p = Popen(split('ssh user@host "nohup PATH/XProgram >&- &"'))
p.communicate() # returns (None, None)

A: Try
subprocess.Popen(["ssh", "xxx@servername", "nohup PATH/start & disown"])

For me,
subprocess.Popen(["ssh", "xxx@servername", "nohup sleep 1000 & disown"])

lets my script exit immediately while leaving sleep running on the server awhile.
When your script dies, an ssh process is left on your system, but killing it doesn't kill the remote process.


text:
Q: Query to find out the second Saturday of each month of the year I need help to write one query:
How do I find out the second Saturday of each month of the year?

A: There is a good technique demonstrating how to do this here. Scroll down to Tip #23. It will have you create a small table to facilitate the query. Once you have the table created, your query is something like this:
SELECT monthdate AS first_day_of_month,
    DATE_ADD(monthdate,
        INTERVAL( ( 10 - DAYOFWEEK(monthdate) ) % 7 ) + 7 DAY) AS second_saturday_of_month
FROM monthdates

A: This is workout from orbman idea, thanks orbman.
First your table is like this,
CREATE TABLE `monthdates` (
  `monthdate` date NOT NULL,
  PRIMARY KEY  (`monthdate`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci;

INSERT INTO `monthdates` VALUES ('2010-02-01');
INSERT INTO `monthdates` VALUES ('2010-03-01');
INSERT INTO `monthdates` VALUES ('2010-04-01');
INSERT INTO `monthdates` VALUES ('2010-05-01');
INSERT INTO `monthdates` VALUES ('2010-06-01');
INSERT INTO `monthdates` VALUES ('2010-07-01');

In this table, your providing the first date of month.
Then use this query for second saturday,
    SELECT monthdate AS first_day_of_month, DATE_ADD(monthdate, INTERVAL( ( 14 - DAYOFWEEK(monthdate) ) % 7 ) + 7 DAY) AS second_saturday_of_month, DAYNAME(DATE_ADD(monthdate, INTERVAL( ( 14 - DAYOFWEEK(monthdate) ) % 7 ) + 7 DAY)) as dayy
 FROM monthdates

Output Is :
first_day_of_month  second_saturday_of_month    dayy
2010-02-01  2010-02-13  Saturday
2010-03-01  2010-03-13  Saturday
2010-04-01  2010-04-10  Saturday
2010-05-01  2010-05-08  Saturday
2010-06-01  2010-06-12  Saturday
2010-07-01  2010-07-10  Saturday


text:
Q: How to handle the SAMLResponse from OKTA? I am trying to implement the SSO via OKTA. And I can get the SAMLResponse text by
string rawSamlData = Request["SAMLResponse"];

Convert the string to XML Format by
     if (rawSamlData.Contains("%"))
        {
            rawSamlData = HttpUtility.UrlDecode(rawSamlData);
        }
        byte[] samlData = Convert.FromBase64String(rawSamlData);
        string samlAssertion = Encoding.UTF8.GetString(samlData);

The information of the user is included in the string samlAssertion, Such as X509Certificate, FirstName, LastName, Email etc. The question is how to check whether it is validate or not?

A: Don't parse SAML data on your own, unless you are willing to invest a lot of time in getting the security right.
Kentor.AuthServices is an open source .NET SP implementation that is compatible with Okta. There's even specific documentation for it.

A: Any reason not to use WS-Federation for SSO in .NET? Check out https://msdn.microsoft.com/en-us/library/hh291061(v=vs.110).aspx. To use Okta for Step 2, you can create a Template WS-Fed app in Okta and use the provided web.config provided under the Sign On tab.
If SAML is absolutely required, there are some frameworks you can use to help such as http://www.componentpro.com/saml.net/. Also check out http://www.twobotechnologies.com/blog/2014/01/sp-init-with-wif.html for SP init SAML and http://travisspencer.com/blog/2010/09/idp-initiated-sso-using-wif.html for IdP init SAML.

A: Instead of integrating with okta and handling SAML response your self, you can use an apache module called mod_auth_mellon.
Here are simple steps to install it in ubuntu


text:
Q: How to display the name of who chatted me in react native gifted chat It looks like this is my backend for the chat messaging app any idea of this problem? I wanted to display the name of who chatted me
 loadMessages(callback) {
    this.messagesRef = firebase.database().ref("messages");
    this.messagesRef.off();
    const onReceive = data => {
      const message = data.val();
      callback({
        id: data.key,
        text: message.text,
        createdAt: message.createdAt,
        user: {
          _id: message.user._id,
          name: message.user.Uemail,
        }
      });
    };

A: You can use renderUsernameOnMessage props for this.

Doc : renderUsernameOnMessage (Bool) - Indicate whether to show the user's
  username inside the message bubble; default is false

In other hand you can customize this component and change whatever you want!
maybe related to this

A: you nee to pass props renderUsernameOnMessage={true} and pass name inside user
in my case
  <GiftedChat
                messages={messages}
                onSend={messages => onSend(messages)}
                renderAvatar={null}            // remove avtar
                renderUsernameOnMessage={true} // default is false
               user={{
                    _id: userId,
                    name:name                  // display name
                }}
            />


text:
Q: Python Selenium Unable to Locate element by xpath Hi I am trying to use selenium to make a website bot. Everyone talks about them nowdays and I am curious about how they work. So this is my code:
from selenium import webdriver

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)

print("Opening Window")
driver.get("https://store.nvidia.com/de-de/geforce/store/?page=1&limit=9&locale=de-de&search=geforce%20rtx%203060%20ti")
driver.implicitly_wait(5)
button = driver.find_element_by_xpath('/html/body/app-root/product/div[1]/div[1]/div[2]/div/product-details/div/ul/li[1]/ul[1]/div[3]/div[2]/div[2]/button')

driver.implicitly_wait(10)
print("Closing Window")
driver.quit()

I get the error code:
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/app-root/product/div[1]/div[1]/div[2]/div/product-details/div/ul/li[1]/ul[1]/div[3]/div[2]/div[2]/button"}
  (Session info: chrome=97.0.4692.99)
Stacktrace:
Backtrace:
    Ordinal0 [0x00BFFDC3+2555331]
    Ordinal0 [0x00B977F1+2127857]
    Ordinal0 [0x00A92E08+1060360]
    Ordinal0 [0x00ABE49E+1238174]
    Ordinal0 [0x00ABE69B+1238683]
    Ordinal0 [0x00AE9252+1413714]
    Ordinal0 [0x00AD7B54+1342292]
    Ordinal0 [0x00AE75FA+1406458]
    Ordinal0 [0x00AD7976+1341814]
    Ordinal0 [0x00AB36B6+1193654]
    Ordinal0 [0x00AB4546+1197382]
    GetHandleVerifier [0x00D99622+1619522]
    GetHandleVerifier [0x00E4882C+2336844]
    GetHandleVerifier [0x00C923E1+541697]
    GetHandleVerifier [0x00C91443+537699]
    Ordinal0 [0x00B9D18E+2150798]
    Ordinal0 [0x00BA1518+2168088]
    Ordinal0 [0x00BA1660+2168416]
    Ordinal0 [0x00BAB330+2208560]
    BaseThreadInitThunk [0x75DEFA29+25]
    RtlGetAppContainerNamedObjectPath [0x77307A9E+286]
    RtlGetAppContainerNamedObjectPath [0x77307A6E+238]

I do wait 5 seconds for the page to load, but still it can't find xpath. I triplechecked that the xpath was right, and if I search for the xpath in the chrome inspect windows, it can find it.
The problem could be switching the iframe, but the website doesn't use iframes I think. Here is the website URL: https://store.nvidia.com/de-de/geforce/store/?page=1&limit=9&locale=de-de&search=geforce%20rtx%203060%20ti

A: Selenium looks good.
Your locator is not appropriate so you can use the following one:
1- Absolute xpath:
//html/body/app-root/product/div[1]/div[1]/div[2]/div/product-details/div/div/div/div[3]/div[3]/button
2- Relative xpath:
(//button[@class='compare'])[1]
Note: you can change the value of index depending on which index(button) you want to interact.
3- css-selector:
button[class='compare']


text:
Q: spring start parallel transactions in integration test I've been looking around for a solution but can't seem to find a good one.
I have a complex scenario in which I would like to evaluate the behavior of hibernate optimistic locking vs pessimistic locking
The perfect place to do this would be in a good set of integration tests, but I can't seem to be able find a clean way of starting parallel transactions.

*

*How can I create 2 parallel transactions in a spring integration test without manually creating Threads and injecting SessionFactory objects.

Note that I haven't found a way to create 2 parallel transactions without spawning at least 2 threads (maybe there is a way, I hope you can show me an example of that).

A: Adding this as an answer as there's not enough space on the comments:
In the past, I've tested on vanilla Spring by creating different EntityManager/Session and later injecting those. I'm not sure how you can do this from an Spring integration test, but it might spark an idea.
In the following code, Account is a tiny object which is versioned. You can achieve the same, if the Spring Integration flow (or whatever is called) can be instantiated with a custom entity manager.
public void shouldThrowOptimisticLockException() {
      EntityManager em1 = emf().createEntityManager();
      EntityManager em2 = emf().createEntityManager();
      EntityTransaction tx1 = em1.getTransaction();
      tx1.begin();

      Account account = new Account();
      account.setName("Jack");
      account.updateAudit("Tim");

      em1.persist(account);
      tx1.commit();

      tx1.begin();
      Account account1 = em1.find(Account.class, 1L);
      account1.setName("Peter");

      EntityTransaction tx2 = em2.getTransaction();
      tx2.begin();
      Account account2 = em2.find(Account.class, 1L);
      account2.setName("Clark");

      tx2.commit();
      em2.close();

      tx1.commit(); //exception is thrown here
      em1.close();
}


text:
Q: Converting SQL Server to Oracle In my project, I have a database in SQL which was working fine. But now I have to make the application support oracle db too.
Some limitations I found out was that in Oracle, there is no bit field and the table name cannot be greater than 30 char. Is there any other limitation that I need to keep in mind.
Any suggestion from past experience will be helpful.

A: If I recall correctly from my earlier Oracle days:

*

*there's no IDENTITY column specification in Oracle (you need to use sequences instead)

*you cannot simply return a SELECT (columns) from a stored procedure (you need to use REF CURSOR)

*of course, all stored procs/funcs are different (Oracle's PL/SQL is not the same as T-SQL)

A: The SQL ISNULL counterpart in Oracle is NVL
select ISNULL(col, 0)...

select NVL(col, 0)...

You will also struggle if you attempt to select without a from in Oracle. Use dual:
select 'Hello' from DUAL

Bear in mind also, that in Oracle there is the distinction between PL/SQL (Procedural SQL) and pure SQL. They are two distinct and separate languages, that are commonly combined.

A: *

*Varchar in Oracle Databases called
varchar2 is limited to 4000
characters

*Oracles concept of temporary tables is different, they have a global redefined structure

*by default sort order and string compare is case-sensitive

When you add a column to a select *
Select * from table_1 order by id;

you must prefix the * by the table_name or an alias
Select
   (row_number() over (order by id)) rn,
   t.*
from table_1 t
order by id;

Oracle doesn't distinguish between null and '' (empty string). For insert and update you ca use '', but to query you must use null
create table t1 (
    id NUMBER(10),
    val varchar2(20)
);

Insert into t1 values (1, '');
Insert into t1 values (2, null);
Select * from t1 where stringval = 0; -- correct but empty
Select * from t1 where stringval is null; -- returns both rows

A: ORACLE do not support TOP clause. Instead of TOP you can use ROWNUM.
SQL Server: TOP (Transact-SQL)
SELECT TOP 3 * FROM CUSTOMERS

ORACLE: ROWNUM Pseudocolumn
SELECT * FROM CUSTOMERS WHERE ROWNUM <= 3


text:
Q: Can continuity test cause component damage? In order to test some tracks on a mounted PCB, I would like to use a multimeter for continuity test.
However, then I measured the open-circuit voltage of two multimeters at hand, and the results were:

*

*Fluke 87 V: 7.3 V

*Keysight 34465A: 9.4 V

Both have a current limit of 1 mA, but when doing a measurement without connection, it applies the rather high open-circuit voltage.
I was pretty surprised to discover that these widely used high-end multimeters apply an open-circuit voltage for continuity test that is above the absolute maximum ratings of common chips like CMOS 7400-series 3.3-V logic with high impedance inputs, which is for example 6.5 V for TI SN74LVC00A.
Am I being overly concerned here, or is there actually a risk of damaging the components when doing continuity test on mounted PCBs with these multimeters?
Is there any suggestion of how to do continuity test with lower open-circuit voltage?

A:
Can continuity test cause component damage?

Generally no. I have used ohmmeters to measure continuity on expensive aerospace electronics and was never concerned. Reliability engineers never warned us about risks.
For your example (LVTTL component), the part will never see a large voltage, the ESD protection circuit will limit the voltage. Connecting an ohmmeter is not the same as connecting a stiff voltage from a power supply. A stiff voltage probably would damage the part.
Some parts without ESD protection could be damaged by an ohmmeter if their absolute maximum input voltage was very low. These types of parts are not common.

A: Note that your "open circuit" voltage test is probably applying a 10meg load (10M voltmeter) to auto-ranging ohmmeter.  Perhaps the ohmmeter had switched into "20 megohm" range mode, which might apply a different voltage than a low-ohms range?
With this Fluke 189 here, with a 10meg voltmeter measuring the output, the 20meg range applies repeating pulses well over 2V, while the low ranges all apply 5.1V continuous.
So, try using the range button to force your meter into various range settings.  See which ones give high-ish volts.
ALSO: try measuring a 1meg resistor, 1K, etc., then simultaneously check the voltage being applied.  Even if your meter has no 'range' button, perhaps you can force it into a low-voltage ohmmeter mode.  Set it to beeper continuity, then jam a 220 ohm resistor across the bananas?  (Usually 220 ohms is far too high to trigger the "beep.")
I can't think of any modern circuitry which would suffer damage from an ohmmeter.  However, I recall a famous story from WWII, where a new tech was testing some expensive experimental microwave-detector diodes.  They all tested bad.   In this story, his big black bakelite SIMPSON meter, set to the wrong ohms range, was applying well over 10mA to each one, destroying it.
Then there's the 'Darwin Award' story, where the military tech decided to find out his internal body-resistance by jamming the ohmmeter probes deep into his hands.  This supposedly killed him, by triggering heart fibrillation.
https://darwinawards.com/darwin/darwin1999-50.html     I did something similar with three 9V batteries, salt water, and a soup spoon held in my mouth.  No death; not even any pain, however I did see grey "flashes" in my whole visual field when I bumped the connections together.  Nikola Tesla would be proud!  Or maybe not, since he swore by healthful x-rays aimed at brain, rather than direct electrode connections.
Death's Ray (Mitchell & Webb):  https://www.youtube.com/watch?v=8HgejSCHRi8


text:
Q: Removing user object from Ad Group-Powershell How can i remove user objects from an AD Group and not delete user contacts? I do not want to delete contacts from the AD Group. I have a script but i feel it will delete contacts too
import-module activedirectory
$group="Group Name"
Get-ADGroupMember "$group" | ForEach-Object {Remove-ADGroupMember "$group" $_ -Confirm:$false}

A: Use the Where-Object cmdlet to filter on the objectclass to pass only user objects.
Get-ADGroupMember $group |
    Where-Object {$_.objectclass -eq 'user'} |
    ForEach-Object {Remove-ADGroupMember $group $_ -Confirm:$false}


text:
Q: Max memory usage on watchOS 2? I didn't find anything regarding the memory usage availavable for an app in watchOS 2. I'm currently developing an app for watchOS and I'm using Core Data in the watch side.
When I load 166 of 189 objects to an array, the app crashes, the memory usage at that point is 34mb. As the watch has 512mb of memory I'm not entirely sure how much can you use with just one app.
I'm gonna improve my code's performance and ram usage but eitherway I still don't know what amount of memory can I use as it's not availavable on Apple Developer portal as far as I know.
Would appreciate information regarding this matter if you know.
Thanks!

A: Memory usage for WatchKit Application and WatchKit extension is not documented yet . For more detail visit this technical Q&A forum .


text:
Q: Rabin's Tree Theorem I've been reading Rabin's article on decidability in Barwise's text, and I came across Rabin's discussion of the decidability proof of his tree theory: the second-order theory with two successor functions.  The text mentions that the proof is hard and very technical owing to many extensions of automata theory, and I was wondering if someone might be able to sketch it out.
Thanks!

A: [Edit, June 2, 2013: At the Nordic Spring School in Logic this year there was a course by Wolfgang Thomas on Logic, automata and games. You may be interested in the slides, particularly for part III (Rabin's tree theorem). Slides and notes for all courses can be downloaded here; the slides for part III can be downloaded here.]
This is a nice result, but you are right that the known proofs are rather elaborate. Below, I just give the briefest of sketches, but it gives a glimpse of the ideas involved. The game theoretic approach is elegant, even if it takes a bit of time to understand the relevant notions.
An excellent reference is the book "The classical decision problem", by Börger, Grädel, and Gurevich (Springer, 1997). You can find the proof in II.7.1.
I lectured on it in Caltech a few centuries ago (2007). If you do not have access to the book, you may want to take a look at homework sets 5 and 6 at this link. There, you will find a sketch of the so called Forgetful Determinacy theorem of Gurevich and Harrington. This is the key technical result. Here, I'll just state it.
(The theorem comes from Gurevich-Harrington, "Trees, automatas, and games". 14th annual ACM Symposium on Theory of Computation, 60-65, 1982. The presentation in the book follows Zeitman, "Unforgettable forgetful determinacy", Journal of Logic and Computation, vol 4, 273-283 (1994).)

Theorem (Forgetful determinacy for tree automata). If $A$ is a $\Sigma$-tree automaton and $F$ is a $\Sigma$-tree, one of the players ($A$ or Pathfinder) has a winning strategy in
  $\Gamma(A,F)$ that is forgetful in the sense that whenever $p$, $q$ are positions from which the winner moves,
   $$ LAR(p)=LAR(q), $$
  and
   $$ \mbox{$Node(p)$-residue of $F=Node(q)$-residue of $F$}, $$
  then $f(p)=f(q)$.

(Here, the node of a position is simply the node in the binary tree that is being played. Given a $\Sigma$-tree $F$, the $v$-residue of $F$ is the $\Sigma$-tree $F_v$ coming from $F$ by only considering the tree from $v$ on, that is, $F_v(w)=F(vw)$. I define the other relevant notions below.)
Using this, it is relatively easy to check that the "Emptiness problem" is decidable for tree automata: There is an algorithm that, given a $\Sigma$-automaton $A$, decides whether there is a $\Sigma$-tree that $A$ accepts.
Similarly, but this takes a bit of work and is really the whole point, Forgetful Determinacy implies that there is an algorithm that to each $\Sigma$-automaton $A$ assigns a $\Sigma$-automaton $C$ with the property that $C$ accepts a $\Sigma$-tree iff $A$ rejects it. (This is the "Complementation Theorem".)
Using this, it is a simple matter of induction in formulas to prove decidability, since one can effectively associate to each monadic formula $\phi(X_1,\dots,X_n)$ (of second-order theory with two successors) a $\Sigma$-automaton $A$ for $\Sigma=\{0,1\}^n$, with the property that, for any collections $W_1,\dots,W_n$ of binary words, the automaton $A$ accepts the tree $T$ they define iff $T^2$ satisfies $\phi(W_1,\dots,W_n)$, where $T^2$ is the structure given by the full binary tree with the two successor functions.

Let me briefly review the relevant definitions, following the book closely. I'm just quoting the notes of my younger self, so there may be a bit of irrelevancy, for which I apologize.
Let $MOVE$ be a finite alphabet. An arena $A$ is a colored
bipartite multi-digraph in the following sense:

*

*The vertices of $A$ are divided into two disjoint sets,
east vertices and west vertices. There are no edges
between east vertices or between west vertices. There may be
several edges between an east and a west vertices, or between a
west and an east vertices (so edges have directions, which is
why we call the object a digraph, and there may be several edges
between the same vertices, which is why we call it a multi-digraph).

*There is a distinguished vertex, the start vertex. Every
vertex is reachable from the start vertex (i.e., for any $v$
there is a finite sequence $v_0,\dots,v_n$ where $v_0$ is the start
vertex, $v_n=v$ and for each $i\lt n$ there is an edge going from $v_i$
to $v_{i+1}$). Any vertex has at least one outgoing edge.

*The edges are labeled by elements of $MOVE$ in such a way that no
two outgoing edges from the same vertex have the same label.

*There is a finite set $S$ of colors that partition the set of
vertices. We denote by $C^s$ the vertices with color $s$.
A game on $A$ is played between two players 0 and 1 who
alternate choosing an outgoing edge from the current vertex,
starting from the start vertex. So a play of the game defines an
infinite path through $A$ (we allow for the possibility of
revisiting vertices). A position $p$ is a finite directed path
through $A$ from the start vertex, so it is uniquely described by a
word in $MOVE^*$, with which we identify $p$. Given a position $p$,
the labels of the edges leading out of the last vertex of $p$ are
the possible moves at $p$. A play is an $\omega$-sequence
$P\in MOVE^\omega$ such that each initial segment is a position. The set
of plays over $A$ is $PLAY(A)$.
A graph game is a triple $\Gamma=(A,\varepsilon,W_\varepsilon)$ where $A$ is an arena,
$\varepsilon\in\{0,1\}$ (denoting the player that goes first) and
$W_\varepsilon$, the winning set for player $\varepsilon$, is
a Boolean combination of the sets ${}[C^s]$ where ${}[C^s]$ is the set
of plays that infinitely often pass through a vertex of color $s$.
Player $\varepsilon$ wins a play $P$ of $\Gamma$ iff $P\in
W_\varepsilon$. Otherwise, player $1-\varepsilon$ wins the play $P$.
Notice that if the start vertex is an east (resp., a west) vertex
then, playing $\Gamma$, player $\varepsilon$'s turns to move are
always at east (resp., west) vertices. Call the set of these
vertices $V_{\varepsilon}$ and the set of remaining vertices
$V_{1-\varepsilon}$.
A forgetful strategy $f$ for player $\delta\in\{0,1\}$ in
$\Gamma$ is a function $f:V_\delta\to{\mathcal P}(MOVE)$ that to each
$v\in V_\delta$ assigns a non-empty set of possible moves from $v$.
(The strategy is forgetful since it depends only on $v$ and not on
how $v$ was reached.)
The latest appearance record $LAR(p)$ of a position $p$ is an
ordering of the colors. We define $LAR$ inductively, with
$LAR(start)$ being an ordering whose last color is that of the start
vertex. If a position $q$ is obtained from a position $p$ by
adjoining an edge to a vertex of color $s$, then $LAR(q)$ is
obtained from $LAR(p)$ by moving $s$ to the last place. The coloring
of an arena $A$ is forgetful if any two positions at the same
vertex have the same $LAR$, in which case we can simply talk of the
$LAR$ at a vertex $v$ (rather than at a position $p$ whose last
vertex is $v$).
What one actually shows is the following:

Theorem (Forgetful determinacy).
  Let $\Gamma=(A,\varepsilon,W_\varepsilon)$ be a graph game with a
  forgetful coloring of the arena $A$. Then one of the players has a
  forgetful winning strategy in $\Gamma$.

One then uses this result to prove the version I stated earlier. For this, let $\Gamma(A,F)$ be a game on a $\Sigma$-tree $F$ between
a $\Sigma$-tree automaton $A$ and Pathfinder. Define from this a
graph game whose alphabet consists of the states of $A$ and names
for the two directions left and right. (So $A$ starts the game and
chooses a state according to its initial table, Pathfinder responds
by choosing the name of a direction, then $A$ chooses a state, etc.)
All positions $p$ where $A$ makes a move have the same default
color. If $A$ chooses a state $s$ at $p$ then the color of position
$ps$ is $s$. (One needs to check that this coloring is forgetful.)
One then has that either $A$ or Pathfinder has a forgetful
winning strategy in $\Gamma(A,F)$, by "transfering" the strategy that the forgetful determinacy theorem guarantees.

A: Here is a very sketchy answer, but it should give the first idea of the proof.
Basically, even on words (structures with one successor), you can decide if an MSO (Monadic Second Order) sentence accepts a model by translating the sentence to an equivalent automaton, and then you just need to find an accepting path in this automaton, which is easy.
What Rabin did is develop a model of automaton running on infinite tree, together with a way to translate MSO sentences to equivalent automata. Then, in the same way, deciding if the MSO sentence accepts a model is reduced to finding a "path" (which is generalized to a tree structure in some way) in the equivalent automaton.


text:
Q: How to group data vertically in rdlc reports i have data in following format:
AssetID  AssetName          AssetMaster      AssetMain          OpeningValue
1        0100101 Generator  01 Electronic    01001 Equipments   150
2        0100102 Heater     01 Electronic    01001 Equipments   100

I want to show this data in rdlc report in this format:
Asset                      OpeningValue
01 Electronic
01001 Equipments
0100101 Generator          150
0100102 Heater             100

A: You can make this using several groups.
Group on:

*

*AssetMaster

*AssetMain

*AssetName

Good luck


text:
Q: How to determine if a number is negative, including -0 I need to define a sign function which returns either -1 or 1. The Math.sign function does not suffices since it returns -0 and0 respectively for the inputs -0 and 0.
My first attempt at solving this was...
function my_sign(a) {
    let sign = Math.sign(a);
    if (sign === 0 || sign === 1){
        return 1;
    } else {
        return -1;
    }
}

Although, since 0 === -0 is true, this does not work. How to proceed?


text:
Q: adding chatgpt's api to a discord command in discord.js i have this code which is fine as far as i know but it keeps hitting me with error below, the api key is correct and the code is all good and the api is working so why am i getting this error.
Code:
const { SlashCommandBuilder } = require('@discordjs/builders');
const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: "MY API KEY HERE",
});
const openai = new OpenAIApi(configuration);

module.exports = {
  data: new SlashCommandBuilder()
    .setName('chat')
    .setDescription('Get an AI-generated response based on your message')
    .addStringOption(option =>
      option.setName('message')
        .setDescription('The message to generate a response from')
        .setRequired(true)),
  async execute(interaction) {
    const message = interaction.options.getString('message');

    try {
      const completion = await openai.createChatCompletion({
        model: "gpt-3.5-turbo",
        messages: [{ role: "user", content: message }],
      });

      const response = completion.data.choices[0].text.trim();

      await interaction.reply(response);
    } catch (error) {
      console.error(error);
      await interaction.reply({ content: 'Sorry, there was an error processing your request!', ephemeral: true });
    }
  },
};

The code checks out unless there is something i don't know that is wrong
Error:
Error: Request failed with status code 404
    at createError (C:\Users\user\OneDrive\Desktop\rzn bot\node_modules\openai\node_modules\axios\lib\core\createError.js:16:15)
    at settle (C:\Users\user\OneDrive\Desktop\rzn bot\node_modules\openai\node_modules\axios\lib\core\settle.js:17:12)
    at IncomingMessage.handleStreamEnd (C:\Users\user\OneDrive\Desktop\rzn bot\node_modules\openai\node_modules\axios\lib\adapters\http.js:322:11)
    at IncomingMessage.emit (node:events:525:35)
    at endReadableNT (node:internal/streams/readable:1359:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  config: {
    transitional: {
      silentJSONParsing: true,
      forcedJSONParsing: true,
      clarifyTimeoutError: false
    },
    adapter: [Function: httpAdapter],
    transformRequest: [ [Function: transformRequest] ],
    transformResponse: [ [Function: transformResponse] ],
    timeout: 0,
    xsrfCookieName: 'XSRF-TOKEN',
    xsrfHeaderName: 'X-XSRF-TOKEN',
    maxContentLength: -1,
    maxBodyLength: -1,
    validateStatus: [Function: validateStatus],
    headers: {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'application/json',
      'User-Agent': 'OpenAI/NodeJS/3.2.1',
      Authorization: 'Bearer THE API KEY HERE',
      'Content-Length': 74
    },
    method: 'post',
    data: '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"hey"}]}',
    url: 'https://api.openai.com/v1/chat/completions'
  },
  request: <ref *1> ClientRequest {
    _events: [Object: null prototype] {
      abort: [Function (anonymous)],
      aborted: [Function (anonymous)],
      connect: [Function (anonymous)],
      error: [Function (anonymous)],
      socket: [Function (anonymous)],
      timeout: [Function (anonymous)],
      finish: [Function: requestOnFinish]
    },
    _eventsCount: 7,
    _maxListeners: undefined,
    outputData: [],
    outputSize: 0,
    writable: true,
    destroyed: true,
    _last: false,
    chunkedEncoding: false,
    shouldKeepAlive: true,
    maxRequestsOnConnectionReached: false,
    _defaultKeepAlive: true,
    useChunkedEncodingByDefault: true,
    sendDate: false,
    _removedConnection: false,
    _removedContLen: false,
    _removedTE: false,
    strictContentLength: false,
    _contentLength: 74,
    _hasBody: true,
    _trailer: '',
    finished: true,
    _headerSent: true,
    _closed: true,
    socket: TLSSocket {
      _tlsOptions: [Object],
      _secureEstablished: true,
      _securePending: false,
      _newSessionPending: false,
      _controlReleased: true,
      secureConnecting: false,
      _SNICallback: null,
      servername: 'api.openai.com',
      alpnProtocol: false,
      authorized: true,
      authorizationError: null,
      encrypted: true,
      _events: [Object: null prototype],
      _eventsCount: 9,
      connecting: false,
      _hadError: false,
      _parent: null,
      _host: 'api.openai.com',
      _closeAfterHandlingError: false,
      _readableState: [ReadableState],
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: undefined,
      _server: null,
      ssl: [TLSWrap],
      _requestCert: true,
      _rejectUnauthorized: true,
      timeout: 5000,
      parser: null,
      _httpMessage: null,
      [Symbol(res)]: [TLSWrap],
      [Symbol(verified)]: true,
      [Symbol(pendingSession)]: null,
      [Symbol(async_id_symbol)]: -1,
      [Symbol(kHandle)]: [TLSWrap],
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]: Timeout {
        _idleTimeout: 5000,
        _idlePrev: [TimersList],
        _idleNext: [TimersList],
        _idleStart: 12141,
        _onTimeout: [Function: bound ],
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: false,
        [Symbol(refed)]: false,
        [Symbol(kHasPrimitive)]: false,
        [Symbol(asyncId)]: 343,
        [Symbol(triggerId)]: 341
      },
      [Symbol(kBuffer)]: null,
      [Symbol(kBufferCb)]: null,
      [Symbol(kBufferGen)]: null,
      [Symbol(kCapture)]: false,
      [Symbol(kSetNoDelay)]: false,
      [Symbol(kSetKeepAlive)]: true,
      [Symbol(kSetKeepAliveInitialDelay)]: 1,
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(connect-options)]: [Object]
    },
    _header: 'POST /v1/chat/completions HTTP/1.1\r\n' +
      'Accept: application/json, text/plain, */*\r\n' +
      'Content-Type: application/json\r\n' +
      'User-Agent: OpenAI/NodeJS/3.2.1\r\n' +
      'Authorization: Bearer THE API KEY HERE' +
      'Content-Length: 74\r\n' +
      'Host: api.openai.com\r\n' +
      'Connection: keep-alive\r\n' +
      '\r\n',
    _keepAliveTimeout: 0,
    _onPendingData: [Function: nop],
    agent: Agent {
      _events: [Object: null prototype],
      _eventsCount: 2,
      _maxListeners: undefined,
      defaultPort: 443,
      protocol: 'https:',
      options: [Object: null prototype],
      requests: [Object: null prototype] {},
      sockets: [Object: null prototype] {},
      freeSockets: [Object: null prototype],
      keepAliveMsecs: 1000,
      keepAlive: true,
      maxSockets: Infinity,
      maxFreeSockets: 256,
      scheduling: 'lifo',
      maxTotalSockets: Infinity,
      totalSocketCount: 1,
      maxCachedSessions: 100,
      _sessionCache: [Object],
      [Symbol(kCapture)]: false
    },
    socketPath: undefined,
    method: 'POST',
    maxHeaderSize: undefined,
    insecureHTTPParser: undefined,
    path: '/v1/chat/completions',
    _ended: true,
    res: IncomingMessage {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 4,
      _maxListeners: undefined,
      socket: null,
      httpVersionMajor: 1,
      httpVersionMinor: 1,
      httpVersion: '1.1',
      complete: true,
      rawHeaders: [Array],
      rawTrailers: [],
      aborted: false,
      upgrade: false,
      url: '',
      method: null,
      statusCode: 404,
      statusMessage: 'Not Found',
      client: [TLSSocket],
      _consuming: false,
      _dumped: false,
      req: [Circular *1],
      responseUrl: 'https://api.openai.com/v1/chat/completions',
      redirects: [],
      [Symbol(kCapture)]: false,
      [Symbol(kHeaders)]: [Object],
      [Symbol(kHeadersCount)]: 14,
      [Symbol(kTrailers)]: null,
      [Symbol(kTrailersCount)]: 0
    },
    aborted: false,
    timeoutCb: null,
    upgradeOrConnect: false,
    parser: null,
    maxHeadersCount: null,
    reusedSocket: false,
    host: 'api.openai.com',
    protocol: 'https:',
    _redirectable: Writable {
      _writableState: [WritableState],
      _events: [Object: null prototype],
      _eventsCount: 3,
      _maxListeners: undefined,
      _options: [Object],
      _ended: true,
      _ending: true,
      _redirectCount: 0,
      _redirects: [],
      _requestBodyLength: 74,
      _requestBodyBuffers: [],
      _onNativeResponse: [Function (anonymous)],
      _currentRequest: [Circular *1],
      _currentUrl: 'https://api.openai.com/v1/chat/completions',
      [Symbol(kCapture)]: false
    },
    [Symbol(kCapture)]: false,
    [Symbol(kBytesWritten)]: 0,
    [Symbol(kEndCalled)]: true,
    [Symbol(kNeedDrain)]: false,
    [Symbol(corked)]: 0,
    [Symbol(kOutHeaders)]: [Object: null prototype] {
      accept: [Array],
      'content-type': [Array],
      'user-agent': [Array],
      authorization: [Array],
      'content-length': [Array],
      host: [Array]
    },
    [Symbol(kUniqueHeaders)]: null
  },
  response: {
    status: 404,
    statusText: 'Not Found',
    headers: {
      date: 'Thu, 02 Mar 2023 22:37:48 GMT',
      'content-type': 'application/json; charset=utf-8',
      'content-length': '158',
      connection: 'keep-alive',
      vary: 'Origin',
      'x-request-id': '40456c1da0117d70199e713b83ddc6f8',
      'strict-transport-security': 'max-age=15724800; includeSubDomains'
    },
    config: {
      transitional: [Object],
      adapter: [Function: httpAdapter],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      maxBodyLength: -1,
      validateStatus: [Function: validateStatus],
      headers: [Object],
      method: 'post',
      data: '{"model":"gpt-3.5-turbo","messages":[{"role":"user","content":"hey"}]}',
      url: 'https://api.openai.com/v1/chat/completions'
    },
    request: <ref *1> ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 7,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      destroyed: true,
      _last: false,
      chunkedEncoding: false,
      shouldKeepAlive: true,
      maxRequestsOnConnectionReached: false,
      _defaultKeepAlive: true,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      strictContentLength: false,
      _contentLength: 74,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      _closed: true,
      socket: [TLSSocket],
      _header: 'POST /v1/chat/completions HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: application/json\r\n' +
        'User-Agent: OpenAI/NodeJS/3.2.1\r\n' +
        'Authorization: Bearer MY API KEY' +
        'Content-Length: 74\r\n' +
        'Host: api.openai.com\r\n' +
        'Connection: keep-alive\r\n' +
        '\r\n',
      _keepAliveTimeout: 0,
      _onPendingData: [Function: nop],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      maxHeaderSize: undefined,
      insecureHTTPParser: undefined,
      path: '/v1/chat/completions',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      reusedSocket: false,
      host: 'api.openai.com',
      protocol: 'https:',
      _redirectable: [Writable],
      [Symbol(kCapture)]: false,
      [Symbol(kBytesWritten)]: 0,
      [Symbol(kEndCalled)]: true,
      [Symbol(kNeedDrain)]: false,
      [Symbol(corked)]: 0,
      [Symbol(kOutHeaders)]: [Object: null prototype],
      [Symbol(kUniqueHeaders)]: null
    },
    data: { error: [Object] }
  },
  isAxiosError: true,
  toJSON: [Function: toJSON]
}

The error does say a 404 but i can't tell why and how to fix it


text:
Q: Pandas mishandling apostrophe when exporting to csv file Pandas is mishandling apostrophes when exporting them to a csv file.  It is changing the apostrophe in "community's" to "community's".  The program first reads an Excel file into a dataframe, then merges that dataframe with another dataframe, and then exports the resulting dataframe to a csv file.  The apostrophe starts off looking like this in the input Excel file (' - a straight apostrophe), then looks like this after import (' - a curly apostrophe), then looks like this after exporting to csv (').  The numeric value I get when I use the Python ord() function on the curly apostrophe value in the dataframe "'" is 8217.
Here's some of the pertinent code.  Any thoughts on how to fix this?
xls_file = pd.ExcelFile(path + file)
df_cust_quests = xls_file.parse('CustQuests')

df_cust_combined = pd.merge(df_cust_clsend, df_cust_quests, on=['ServiceLine', 'QuestNum'], how='left')

df_cust_combined.to_csv('C:/Users/User/Desktop/Sample File.csv', index=False)

A: Found the solution.  The Excel file I was importing contained curly apostrophes.  They looked straight because they were small, but when I looked at them closer I could see they were curly.  I changed them to straight apostrophes and that fixed the problem.


text:
Q: What happens when ShowMessage is called? I am working on the project where I communicate with another device over COM port.
For incoming data I am using VaComm1RXchar event, there I store the message into the array and increment msgIndex which represents number of messages.
Then I call the function where I work with this message.
Inside this function is this timeout cycle where I wait for this message:
  while MsgIndex < 1 do
  begin
  stop := GetTickCount;
  if (stop - start)> timeout then
    begin

      MessageBox(0, 'Timeout komunikace !', 'Komunikace', MB_OK);
      exit(false);
    end;
    sleep(10);
  end;

The strange thing for me is that, when have it like this above then it always end with timeout. But when I put on there before this while cycle a ShowMessage('Waiting') then It works correcly.
Does anyone know what can caused this and how can I solve it? Thanks in advance!

A: We can deduce that the VaComm1RXchar event is a synchronous event and that by blocking your program in a loop you are preventing the normal message processing that would allow that event to execute.
Showing a modal dialog box, on the other hand, passes message handling to that dialog so the message queue is properly serviced and your Rx events and handled normally.
You can be certain this is the case if this also works (please never write code like this - it's just to prove the point):
while MsgIndex < 1 do begin
  stop := GetTickCount;
  if (stop - start)> timeout then begin
    MessageBox(0, 'Timeout komunikace !', 'Komunikace', MB_OK);
    exit(false);
  end;
  Application.ProcessMessages; // service the message queue so that
  sleep(10);                   // your Rx event can be handled
end;

If there is a lesson here it is that RS-232 communication really needs to be done on a background thread.  Most all implementations of "some chars have been received" events lead to dreadful code for the very reason you are discovering.  Your main thread needs to be free to process the message that characters have been received but, at the same time, you must have some parallel process that is waiting for those received characters to complete a cogent instruction.   There does not exist a sensible solution in an event-driven program to both manage the user interface and the communication port at the same time on one thread.
A set of components like AsyncPro**, for example, wrap this functionality into data packets where synchronous events are used but where the components manage start and end string (or bytes) detection for you on a worker thread.  This removes one level of polling from the main thread (ie: you always get an event when a complete data packet has arrived, not a partial one). Alternatively, you can move the communication work to a custom thread and manage this yourself.
In either case, this is only partly a solution, of course, since you still cannot stick to writing long procedural methods in synchronous event handlers that require waiting for com traffic.  The second level of polling, which is managing a sequence of complete instructions, will still have you needing to pump the message queue if your single procedure needs to react to a sequence of more than one comport instruction.  What you also need to think about is breaking up your long methods into shorter pieces, each in response to specific device messages.
Alternatively, for heavily procedural process automation, it is also often a good idea to move that work to a background thread as well.  This way your worker threads can block on synchronization objects (or poll in busy loops for status updates) while they wait for events from hardware.  One thread can manage low level comport traffic, parsing and relaying those commands or data packets, while a second thread can manage the higher level process which is handling the sequence of complete comport instructions that make up your larger process.  The main thread should primarily only be responsible for marshalling these messages between the workers, not doing any of the waiting itself.
See also : I do not understand what Application.ProcessMessages in Delphi is doing

** VAComm may also support something like this, I don't know.  The API and documentation are not publicly available from TMS for ASync32 so you'll need to consult your local documentation.

A: What happens is that a modal message loop executes when the dialog is showing. That this message loop changes behaviour for you indicates that your communications with the device require the presence of a message loop.
So the solution for you is to service the message queue. A call to Application.ProcessMessages in your loop will do that, but also creates other problems. Like making your UI become re-entrant.
Without knowing more about your program, I cannot offer more detailed advice as to how you should solve this problem.


text:
Q: Android app always crash when recieve push notification from Pusher I'm just trying to implement a simple Pusher beam notification from Pusher. i did a quick start from Pusher. I configured and added dependencies and stuff but whenever i use the curl command to try to send notification . it always crash . I've been trying to find the solution for hours but couldn't find it. It's driving me crazy . please help.
Here is my code in
MainActivitiy.kt
    PushNotifications.start(this, "instance id")
    PushNotifications.addDeviceInterest("hello")

here's the log :
 E/AndroidRuntime: FATAL EXCEPTION: Firebase-WrappedFirebaseMessagingService
Process: com.example.azda, PID: 22200
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
    at android.content.ContextWrapper.getSystemService(ContextWrapper.java:562)
    at com.google.firebase.messaging.zzd.zza(com.google.firebase:firebase-messaging@@20.0.0:10)
    at com.google.firebase.messaging.FirebaseMessagingService.zzc(com.google.firebase:firebase-messaging@@20.0.0:60)
    at com.google.firebase.messaging.zze.run(com.google.firebase:firebase-messaging@@20.0.0:2)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at com.google.android.gms.common.util.concurrent.zza.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:818)

A: I found it . The problem is i shouldn't use kotlin syntax of applicationContext when the solution is to use getApplicationContext() like in java .
Spent 10 hours just to write 2 lines of code . Felt so worthless and wanted to kill myself . Goddamn


text:
Q: Progress bar in a Flash MP3 Player I have coded a simple XML driven MP3 player. I have used Sound and SoundChannel objects and method but I can´t find a way of make a progress bar.
I don´t need a loading progress I need a song progress status bar.
Canbd anybody help me?
Thanks.
UPDATE:
Theres is the code.

var musicReq: URLRequest;
var thumbReq: URLRequest;
var music:Sound = new Sound();
var sndC:SoundChannel;
var currentSnd:Sound = music;
var position:Number;
var currentIndex:Number = 0;
var songPaused:Boolean;
var songStopped:Boolean;
var lineClr:uint;
var changeClr:Boolean;
var xml:XML;
var songList:XMLList;

var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, Loaded);

loader.load(new URLRequest("musiclist.xml"));

var thumbHd:MovieClip = new MovieClip();
thumbHd.x = 50;
thumbHd.y = 70;
addChild(thumbHd);

function Loaded(e:Event):void{
    xml = new XML(e.target.data);
    songList = xml.song;
    musicReq = new URLRequest(songList[0].url);
    thumbReq = new URLRequest(songList[0].thumb);
    music.load(musicReq);
    sndC = music.play();
    title_txt.text = songList[0].title + " - " + songList[0].artist;

    loadThumb();
    sndC.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

function loadThumb():void{
    var thumbLoader:Loader = new Loader();
    thumbReq = new URLRequest(songList[currentIndex].thumb);
    thumbLoader.load(thumbReq);
    thumbLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, thumbLoaded);
}

function thumbLoaded(e:Event):void {
    var thumb:Bitmap = (Bitmap)(e.target.content);
    var holder:MovieClip = thumbHd;
    holder.addChild(thumb);
}

prevBtn.addEventListener(MouseEvent.CLICK, prevSong);
nextBtn.addEventListener(MouseEvent.CLICK, nextSong);
playBtn.addEventListener(MouseEvent.CLICK, playSong);

function prevSong(e:Event):void{
    if(currentIndex > 0){
        currentIndex--;
    }
    else{
        currentIndex = songList.length() - 1;
    }

    var prevReq:URLRequest = new URLRequest(songList[currentIndex].url);
    var prevPlay:Sound = new Sound(prevReq);
    sndC.stop();
    title_txt.text = songList[currentIndex].title + " - " + songList[currentIndex].artist;
    sndC = prevPlay.play();
    currentSnd = prevPlay;
    songPaused = false;
    loadThumb();
    sndC.addEventListener(Event.SOUND_COMPLETE, nextSong);
}

function nextSong(e:Event):void {
    if(currentIndex
And here the code for the lenght and position. It´s inside a MovieClip. That´s why I use absolute path for find the Sound object.

this.addEventListener(Event.ENTER_FRAME, moveSpeaker);

var initWidth:Number = this.SpkCone.width;
var initHeight:Number = this.SpkCone.height;
var rootObj:Object = root;

function moveSpeaker(eventArgs:Event)
{
    var average:Number = ((rootObj.audioPlayer_mc.sndC.leftPeak + rootObj.audioPlayer_mc.sndC.rightPeak) / 2) * 10;
//  trace(average);
//  trace(initWidth + ":" + initHeight);
    trace(rootObj.audioPlayer_mc.sndC.position + "/" + rootObj.audioPlayer_mc.music.length);
    this.SpkCone.width = initWidth + average;
    this.SpkCone.height = initHeight + average;
}

A: You can get a normalized floating point value ( the percent complete ) by using: SoundChannel.position / Sound.length. Then you can use that value as a scalar for your sound playback progress indicator.
Psuedo Code:
// -- set the x scale of the progress bar to the percent complete
progbar.scaleX = channel.position / sound.length;

A: The Sound class has a "length" property indicating the length of the sound and the SoundChannel has a "position" property indicating the position of the sound currently playing. Use these 2 properties as data for a ProgressBar component.

A: you have to listen for the complete event, and inside of that set the scaleX to 1.


text:
Q: Using file-name as parameter in batch file I have something like this
FOR %%A IN ("Drawings\*.txt") DO draw.exe /f %%A /d ONLY_FILENAME

But I need to put file-name of each txt-file automatically into the string as "/d ..." parameter.
Example:
I have file "The First File.txt" in my Drawings directory. And the automatically generated string have to be like this one
FOR %%A IN ("Drawings\*.txt") DO

draw.exe /f "Drawings\The First File.txt" /d "The First File"

How to do that?

A: FOR %%A IN ("Drawings\*.txt") DO draw.exe /f "%%A" /d "%%~nA"

?
Here's an excerpt from FOR help:
In addition, substitution of FOR variable references has been enhanced
You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string


text:
Q: Large amounts of file handles to large files - potential problems? Would keeping say 512 file handles to files sized 3GB+ open for the lifetime of a program, say a week or so, cause issues in 32-bit Linux? Windows?
Potential workaround: How bad is the performance penalty of opening/closing file handles?

A: The size of the files doesn't matter. The number of file descriptors does, though. On Mac OS X, for example, the default limit is 256 open files per process, so your program would not be able to run.

A: I don't know about Linux, but in Windows, 512 files doesn't seem that much to me. But as a rule of thumb, any more than a thousand and it's too many. (Although I have to say that I haven't seen any program first-hand opening more than, say, 50.)
And the cost of opening/closing handles isn't that big unless you do them every time you want to read/write a small amount, in which case it's too high and you should buffer your data.


text:
Q: Firebase Cloud Function does not terminate in functions:shell I'm trying to import a JSON into a collection. For testing purpose, I'm using emulators and document creation trigger.
The workflow is :

*

*start emulators with firebase emulators:start

*start functions shell in another terminal with firebase functions:shell (tells me that no emulator is running btw)

*call my function with tempoCF()

*it runs and add documents to collection but it seems that the function does not terminate. I cannot call another function and need to press CTRL+C to be able to write again in the shell.

Here is the function I use :
const functions = require("firebase-functions");
const admin = require('firebase-admin');
const fetch = require('node-fetch');

admin.initializeApp();

const db = admin.firestore();

exports.tempoCF = functions
    .firestore.document('/tempo/{docId}')
    .onCreate(async (snap, context) => {
        console.log("onCreate");

        let settings = { method: "Get" };

        let url = "https://opendata.paris.fr/api/records/1.0/search/?dataset=sanisettesparis&q=&rows=-1";
        try {
            let response = await fetch(url, settings);
            let json = await response.json();
            // TODO for each json object, add new document
            return Promise.all(json["records"].map(toiletJsonObject => {
                console.log(toiletJsonObject);
                return db.collection('toilets').doc(toiletJsonObject["recordid"]).set({});
            }));
        }

        catch(error) {
            console.log(error);
            return null;
        }
    }
    );

I know I can use the emulator UI to create a new document that trigger the tempoCF function and it works as well but I fear that my function isn't correct and could generate bugs in production.
Here is the screenshot of the terminal. It prints logs and at the end, there is no way to write anything on the last empty line in the screenshot. I run it in Android Studio but I don't think that it matters.

A: I'm not on Windows but on a Mac, and I can reproduce your problem in the Terminal by calling the function with tempoCF(). Somehow, by doing that, you are simulating the creation a Firestore document without data.
But if I pass some data when calling the Cloud Function, e.g. tempoCF({foo: "bar"}) (i.e. providing new test data for the onCreate operation) I'm able to write to the Terminal after the CF has completed. See the doc for more details.


text:
Q: How to destroy intro js when click other button? i want to close / destroy intro js when i click .citysubmit button
function introjsstart(){
  introJs().setOption('keyboardNavigation', false).setOptions({
    steps: [
      {
        element : document.querySelector('.stepPremium1'),
        intro: "
{{ trans('premium.facebook.intro.intro1') }}
",
        position: 'top'
      },{
        element : document.querySelector('.stepPremium2'),
        intro   : '
{{ trans('premium.facebook.intro.intro2') }}
',
        position: 'top'
      }
    ]
  }).start()
}

when i press this intro js should be done
$(".citysubmit").click(function(){
    //how to destroy intro js?
});

A: As written in the Intro.js documentation you can exit by using exit() function in your code:
introJs().exit()


text:
Q: Clip button to view enter image description hereSo i have backgroundView (UIView) and two buttons in it.
Now i have made following code
 buttonBackgroundView.layer.cornerRadius = 5.0
 buttonBackgroundView.layer.borderColor = UIColor.black.cgColor
 buttonBackgroundView.layer.borderWidth = 0.5

@IBOutlet weak var firstbutton: UIButton!{
        didSet{
            proceedButton.clipsToBounds = true
        }
    }

in this the view has rounded corner but the button does not have those rounded corners
How do i implement that? (so that button also get the rounded corner.
I have two buttons, so I want only the left corner of left button and right corner of right button.
I have added the image link which i want to achieve.

A: Please try using masksToBounds property,
@IBOutlet weak var firstbutton: UIButton!{
    didSet{
        proceedButton.clipsToBounds = true
        proceedButton.masksToBounds = true
    }
}

A: class ViewController: UIViewController {

    @IBOutlet weak var yourView: UIView! //Create your view outlet
    override func viewDidLoad() {
        super.viewDidLoad()
        yourView.clipsToBounds = true
        yourView.layer.cornerRadius = 15 // As per you requirement
        yourView.layer.borderColor = UIColor.black.cgColor
        yourView.layer.borderWidth = 2

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Add Following constraint

Output:

This might help you :)


text:
Q: How to compute percentage within groups In a dataset including employees by department, I am trying to calculate the total employee count in each department and job role divided by the total number of employees in either female or male groups.
The final result should be divided up horizontally by female and male. Under both female and male, there are three different departments listed. Vertically, I have four different job roles listed. Each cell holds a value of the total percent.
For example, if there's a total of 100 females and four people in the maternity department AND nurse role, that particular cell will display 4%.
What am I doing incorrectly to summarize data into this format?
My current code:
library(dplyr)

attr_per <- heatmap_data %>%
  group_by(Department, JobRole, Gender) %>%
  mutate(Percent = sum(Attrition == "Yes")/n()) %>%
  summarize(Department, JobRole, Gender, Percent)

The ultimate goal is to use this data to make a heatmap.

A: Summarize your counts, then mutate as a percentage.
You may want to make Attrition a calculated value like
gorup_by(..., Attrition = Attrition == "yes")
library(dplyr)
heatmap_data |>
  group_by(Department, JobRole, Category, Attrition) |>
  summarise(count = n()) |>
  # may want to reset the grouping variables here
  mutate(Percent = count/sum(count))


text:
Q: Question about using FacesValidator (JSF Validation) and Bean Validation on one Field i have an email field
which i want to validate that it's valid email, and validate that it doesn't exist in the database, so i used for valid email pattern the @Email from hibernate in the bean:
@NotBlank(message = "{email.required}")
@Email(message = "{invalid.email}")
@Size(max = 25, message = "{long.value}")

and in the jsf page:
<f:validator binding="#{emailExistValidator}" />

my questions:

*

*What happens first, the faces validator or the bean validation ?

*What do you think about this mixing between bean validation and
FacesValidator, is it bad practice,if so what do you suggest ?

A:
1- What happens first, the faces validator or the bean validation?

JSF conversion and validation will run first in the order it is been declared on the component, with required first. If any of it fails, then the remnant of JSF validation and all the bean validation is completely skipped, else all of the bean validation is executed.

2- What do you think about this mixing between bean validation and FacesValidator, is it bad practice, if so what do you suggest?

Hard to answer. It solely depends on the functional requirements and the purpose of the validator and how closely tied the validation is to the model or the view.
If the validation needs to run everytime the model property is set (so, it's closely tied to the model), then bean validation would be preferred. But if validation needs to run only once, e.g. during registration (so, it's closely tied to a specific view), then JSF validation would be preferred.
For example, if you're checking the email syntax pattern, then bean validation would make more sense, e.g.:
@Pattern(regexp = "([^.@]+)(\\.[^.@]+)*@([^.@]+\\.)+([^.@]+)", message = "Email is not in valid format")
private String email;

If you're checking the email existance against the DB, then a JSF validator would make more sense since you don't want it to unnecessarily be executed on every property set. DB calls are not cheap per se.
Again, this is subjective. See what fits the business requirements the best. Maybe you're required to validate it on every property set, for example.