text:
Q: Database giving value twice I'm trying to get value from multiple columns from multiple tables. The code looks like this:
<?php

$connect = mysql_connect("localhost","en","]9");

mysql_select_db("en");
$result = mysql_query("SELECT title, field_id_1 FROM exp_channel_titles, exp_channel_data") or die(mysql_error());

// check for empty result
if (mysql_num_rows($result) > 0) {
    // looping through all results
    // products node
    $response["video_path"] = array();

    while ($row = mysql_fetch_array($result)) {
       // temp user array
        $s1 = explode('"',$row['field_id_1']);
        $path = array();
        $path["field_id_1"] = $s1[5];
       $path["title"] = $row["title"];
        array_push($response["video_path"], $path);
    }
    // success
    $response["success"] = 1;
     // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

In the result the values are appearing twice instead of only once. I checked the two tables, but these two tables do contain the column of the same name.

A: Did You run query from Your code in mysql client?
You are making implicit cross join, that's why you are getting what seems to be duplicated result. In fact You are getting cartesian product of both tables.
Read more about this at http://en.wikipedia.org/wiki/Join_%28SQL%29#Cross_join and consider using left join.
Since You didn't publish schema of your tables I can't tell you more.

A: Cehck output of query
SELECT title, field_id_1 FROM exp_channel_titles, exp_channel_data
Join two table based on relations, use distinct, This will solve your problem


text:
Q: Getting Selected options from Multi Select tag via Javascript and Send via XHR I'm looking to submit a form via an XHR but I'm having trouble getting a hold of the selected data to pass along.
<form>
    <select multiple id="select" >
        <option class="userOptions" value="1">Tyler Durden</option>
        <option class="userOptions" value="2">Robert Paulson</option>
        <option class="userOptions" value="3">Marla Singer</option>
    </select>
</form>

What would be the best way to grab hold of the user selected values and pass them off to a page via an XHR?
I've tried things like document.getElementsByClassName("userOptions").selected but it's not returning anything. Also, should I pack this up as an array? Or is there a better way to send it? Thanks for your time!

A: Here is a function in vanilla Javascript that will help you:
function getMultiValue(selectId)
{
    var list     = document.getElementById(selectId),
        selected = [],
        i;
    for (i = 0; i < list.options.length; i++) {
        if (list.options[i].selected) {
            selected.push(list.options[i].value);
        }
    }
    return selected;
}

In the case of your example, you must use this way:
var values = getMultiValue('select');

If you want those values converted to a query string:
var queryString = 'select=' + values.implode('&select=');

If the values contain special characters, you must do this before  the construction of the query string:
var i;
for (i = 0; i < values.length; i++) {
    values[i] = escape(values[i]);
}

Or just change a little the previous function:
function getMultiValue(selectId, mustEscape)
{
    var list     = document.getElementById(selectId),
        selected = [],
        i;
    for (i = 0; i < list.options.length; i++) {
        if (list.options[i].selected) {
            selected.push(mustEscape ? escape(list.options[i].value) : list.options[i].value);
        }
    }
    return selected;
}

And use it this way:
var values      = getMultiValue('select', true),
    queryString = 'select=' + values.implode('&select=');

A: Use jQuery and its just simple!
You can do it like this: http://jsfiddle.net/Hm2KL/
$("#sendbtn").click(function() {

    var data = $("#selectme").val();
    alert(data);

    $.ajax({
        url: ..,
        data: {data}
           etc..
    });

});

jQuery Ajax Doc: http://api.jquery.com/jQuery.ajax/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Installing packages with Anaconda On Ubuntu 14.04, I have installed Anaconda, which I use as my main Python interpreter. I now want to install the TensorFlow library and use this via Anaconda. So, I downloaded the relevant foo.whl file from the TensorFlow website, and then ran pip install foo.whl. After this, I ran pip freeze, and it showed me tensorflow==0.7.1 indicating that it was installed successfully.
However, using the Anaconda interpreter, when I run a Python file which has import tensorflow, it tells me ImportError: No module named 'tensorflow'. Additionally, if I search my Anaconda directory, there is no reference to TensorFlow.
Now at first, I thought this was because pip install was using pip that comes with the native Ubuntu installation. However, I have the line export PATH=/home/karnivaurus/Libraries/Anaconda/bin:$PATH in my .bashrc file, and so this suggests it would use Anaconda's pip.
Any idea what's going on? Thanks!

A: You can try the similar answer here:
https://stackoverflow.com/a/33698750/5573572
Pretty much do these steps:
1. Uninstall TensorFlow from pip:

pip uninstall tensorflow

Do the above to avoid conflicts.
2. Install Python 3 in a virtual environment (version 0.7.1 as of this writing):

conda create -n <environment_name> python==3.5.1

3. Activate your virtual environment (do this every time you want to use TensorFlow):

source activate <environment_name>

4. Install a Conda version of TensorFlow in that environment (version 0.7.1 as of this writing):

conda install -c https://conda.anaconda.org/jjhelmus tensorflow

Remember to change "environment_name" to whatever you want to name your environment. After these, you should hopefully be able to import tensorflow. If not, then anaconda might be having trouble installing TensorFlow's dependencies. I'll run this on my machine to check real quick :p. I have confirmed that this works.
A possible reason that your installation attempt was not working is because Ubuntu 14.04 has Python 2.7 installed, in which many system programs depend on for the time being. As an aside, the Ubuntu development team is working on porting all of those programs to use Python 3 instead:
https://wiki.ubuntu.com/Python/Python35Transition
Update: added instructions to include creating a virtual environment. The virtual environment helps because it allows you to use the Python commands within the environment instead of any system Python commands. So, commands like "pip" and "python" will use the ones in the environment, which also contains the TensorFlow libraries. To get out of the environment, do:
source deactivate

A: Try without sudo:
pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl

instead of
sudo pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.7.1-cp27-none-linux_x86_64.whl

A: First uninstall all the dependencies of tensorflow using
pip uninstall tensorflow

Then install tensorflow package with conda run:
 conda install -c jjhelmus tensorflow=0.10.0rc0

If you want to install tensorflow package with pip run:
pip install -i https://pypi.anaconda.org/jjhelmus/simple tensorflow

Sources: https://anaconda.org/jjhelmus/tensorflow


text:
Q: (not set) list name in Product List Performance in Google Analytics and its segment Product List Performance report in Google Analytics has (not set) list. It happens when google can't find any action corresponding to any list prior to purchase. For example, visitor is landing to cart page or product page and immediately make purchase.
Q1: Does this attribution take place on session or user level?
Help is not clear.
In my case more than 30% of revenue corresponds to (not set). If attribution is on session scope the only reason left is session interruption after 30 minutes (default settings in GA). It's possible that in first session visitor adds items to cart and in the second session buy it. So I change session timeout to 4 hours (maximum allowed). Will wait for result, but doubt big positive effect.
While waiting I decide to make custom segment of session where List Name was (not set) and purchase was made. And I was greatly surprised that all revenue of the day was reported, while in GA Product List Performance report there's only :) one third. Obviously I made mistake in segment definition.
My segment:
metrics=ga:itemRevenue
segment=sessions::condition::ga:productListName==(not set);ga:itemRevenue>0

I've tried another way like sequence, but failed.
segment=sessions::sequence::ga:productListName==(not set);ga:itemQuantity>0

Q2: How can I make segment with sessions with purchases corresponding to (not set) list?


text:
Q: REACT_APP_API_URL is undefined in NextJS I have added a .env file to my root folder and added the below variable.
REACT_APP_API_URL=http://localhost:4000

I have used this in a component as below.
process.env.REACT_APP_API_URL

After adding the above, I have restarted the reactJS application and run the application via npm start. I see the below message in the console, but still, the variable gives an undefined value.

ready - started server on 0.0.0.0:3000, url: http://localhost:3000

info  - Loaded env from D:\ReactJsProj.env

info  - Using webpack 5. Reason: no next.config.js https://nextjs.org/docs/messages/webpack5

A: it seems you just want to change your port, not the whole app url. so just do this in your .env file:
PORT=4000

and then restart the dev server. it will do the job!

A: In nextjs you should add env variables in .env.locale


text:
Q: Bulk dynamic pricing for WooCommerce products with specific product-tag I'm trying to add dynamic discount to all products who have the tag: "bulk-discount" I want the discount to happen if a customer buys eg. 5 similar or different prducts with the tag.
I'm working with this code. And this answer.
This is what i have:
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 9999 );

function bbloomer_quantity_based_pricing( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

// Loop through cart items
foreach ( $cart->get_cart() as $cart_item ) {

    // Get an instance of the WC_Product object
    $product = $cart_item['data'];

    // Get product id
    $product_id = $cart_item['product_id'];

    if( method_exists( $product, 'set_name' ) && has_term( 'bulk-discount', 'product_tag', $product_id ) ) {

    // Define discount rules and thresholds
    $threshold1 = 5; // Change price if items > 4
    $discount1 = 0.05; // Reduce unit price by 5%
    $threshold2 = 10; // Change price if items > 9
    $discount2 = 0.1; // Reduce unit price by 10%

    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
      if ( $cart_item['quantity'] >= $threshold1 && $cart_item['quantity'] < $threshold2 ) {
         $price = round( $cart_item['data']->get_price() * ( 1 - $discount1 ), 2 );
         $cart_item['data']->set_price( $price );
      } elseif ( $cart_item['quantity'] >= $threshold2 ) {
         $price = round( $cart_item['data']->get_price() * ( 1 - $discount2 ), 2 );
         $cart_item['data']->set_price( $price );
      }
    }

 }

A: The first loop counts how many times the tag appears on a single product or multiple items from the same product
The 2nd loop applies the discount if the condition is met
function bbloomer_quantity_based_pricing( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 ) return;

    // count tag found
    $tag_found = 0;

    // Loop through cart items, count how many times tag occurs
    foreach ( $cart->get_cart() as $cart_item ) {
        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get product id
        $product_id = $cart_item['product_id'];

        // if product has tag
        if( has_term( 'bulk-discount', 'product_tag', $product_id ) ) {

            // Get quantity from product in cart
            $quantity = $cart_item['quantity'];

            // if product quantity > 1
            if ( $quantity > 1) {
                $tag_found = $tag_found + $quantity;
            } else {
                $tag_found += 1;
            }
        }
    }

    // Define discount rules and thresholds
    $threshold = 5; // Change price if items > 4
    $discount = 0.05; // Reduce unit price by 5%

    // if tag found >= $threshold
    if ( $tag_found >= $threshold ) {
        // Loop through cart items, add discount
        foreach ( $cart->get_cart() as $cart_item ) {
            // Get an instance of the WC_Product object
            $product = $cart_item['data'];

            // Get product id
            $product_id = $cart_item['product_id'];

            // if product has tag
            if( has_term( 'bulk-discount', 'product_tag', $product_id ) ) {
                // calculate new price
                $price = round( $cart_item['data']->get_price() * ( 1 - $discount ), 2 );

                // set new price
                $cart_item['data']->set_price( $price );
            }
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'bbloomer_quantity_based_pricing', 10, 1 );

Related: Multiple bulk dynamic pricing for WooCommerce products with specific product-tag


text:
Q: Show that every Banach space is isometric to a subspace of an $L_{\infty}(\mu)$-space The following statement can be obtain in the proof of Proposition $7.1$

Since every Banach space is isometric to a subspace of an $L_{\infty}(\mu)$-space (e.g. an $l_{\infty}(T)$ for suitable $T$), the proposition is trivial if $p=\infty$.

Question: How to show that 'every Banach space is isometric to a subspace of an $L_{\infty}(\mu)$-space'?

A: Let $X$ be a Banach space and let $B_{X^*}$ be the unit ball of $X^*$. Define a map $T\colon X\to \ell_\infty(B_{X^*})$ by $$Tx = (\langle f, x\rangle)_{f\in B_{X^*}}\quad (x\in X).$$ Then $T$ is linear. It follows from the Hahn–Banach theorem that $T$ is isometric.
In some sense the answer is optimal because spaces which do not admit a strictly convex renorming (such as $\ell_\infty/c_0$) do not embed into $L_\infty(\mu)$ for $\mu$ being $\sigma$-finite.


text:
Q: update records in oracle8i database where we cannot use regex I have a task in hand where I need to update phone numbers format of around 200 records. The current format is
xwz@gmail.com,04163304166@redcoal.com
The new format should be
xwz@gmail.com,+614163304166@redcoal.com
I tried to use regex but oracle 8i doesn't allow me to use it.

A: This looks like a really bad data format -- storing multiple values in a string.  But, you can use replace(), at least for the example you have given:
select replace(col, ',0', ',+61')
from t;

I would check that this does what you want.  In the end, the query might look like:
update t
    set col = replace(col, ',0', ',+61')
    where col like '%,0';


text:
Q: Count per year with only start and end year data I want to create a line chart in ggplot2 with 350 beer breweries. I want to count per year how many active breweries there are. I only have the start and end date of brewery activity. tidyverse answers prefered.
begin_datum_jaar is year the brewery started. eind_datum_jaar is in which year the brewery has ended.
example data frame:
library(tidyverse)

# A tibble: 4 x 3
  brouwerijnaam begin_datum_jaar eind_datum_jaar
  <chr>                    <int>           <int>
1 Brand                     1340            2019
2 Heineken                  1592            2019
3 Grolsche                  1615            2019
4 Bavaria                   1719            2010

dput:
df <- structure(list(brouwerijnaam = c("Brand", "Heineken", "Grolsche",
"Bavaria"), begin_datum_jaar = c(1340L, 1592L, 1615L, 1719L),
    eind_datum_jaar = c(2019L, 2019L, 2019L, 2010L)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -4L))

Desired output where etc. is a placeholder.
# A tibble: 13 x 2
   year      n
   <chr> <dbl>
 1 1340      1
 2 1341      1
 3 1342      1
 4 1343      1
 5 etc.      1
 6 1592      2
 7 1593      2
 8 etc.      2
 9 1625      3
10 1626      3
11 1627      3
12 1628      3
13 etc.      3

A: Could try:
library(tidyverse)

df %>%
  rowwise %>%
  do(data.frame(brouwerij = .$brouwerijnaam,
                Year = seq(.$begin_datum_jaar, .$eind_datum_jaar, by = 1))) %>%
  count(Year, name = "Active breweries") %>%
  ggplot(aes(x = Year, y = `Active breweries`)) +
  geom_line() +
  theme_minimal()

Or try expand for the first part:
df %>%
  group_by(brouwerijnaam) %>%
  expand(Year = begin_datum_jaar:eind_datum_jaar) %>%
  ungroup() %>%
  count(Year, name = "Active breweries")

However, note that the rowwise, do or expand parts are resource intensive and may take long time. If that happens, I'd rather use data.table for expanding the data frame, and then continue, like below:
library(data.table)
library(tidyverse)

df <- setDT(df)[, .(Year = seq(begin_datum_jaar, eind_datum_jaar, by = 1)), by = brouwerijnaam]

df %>%
  count(Year, name = "Active breweries") %>%
  ggplot(aes(x = Year, y = `Active breweries`)) +
  geom_line() +
  theme_minimal()

The above gives you the plot directly. If you'd like to save it to a data frame first (and then do the ggplot2 thing), this is the main part (I use the data.table for expanding as it's much faster in my experience):
library(data.table)
library(tidyverse)

df <- setDT(df)[
  , .(Year = seq(begin_datum_jaar, eind_datum_jaar, by = 1)),
  by = brouwerijnaam] %>%
  count(Year, name = "Active breweries")

Output:
# A tibble: 680 x 2
    Year `Active breweries`
   <dbl>              <int>
 1  1340                  1
 2  1341                  1
 3  1342                  1
 4  1343                  1
 5  1344                  1
 6  1345                  1
 7  1346                  1
 8  1347                  1
 9  1348                  1
10  1349                  1
# ... with 670 more rows

A: We can use map2 to get the sequence from start to end date for each corresponding element, unnest the list column to expand and use count to get the frequency of the 'year'
library(tidyverse)
df %>%
   transmute(year = map2(begin_datum_jaar, eind_datum_jaar, `:`)) %>%
   unnest %>%
   count(year)
# A tibble: 680 x 2
#    year     n
#   <int> <int>
# 1  1340     1
# 2  1341     1
# 3  1342     1
# 4  1343     1
# 5  1344     1
# 6  1345     1
# 7  1346     1
# 8  1347     1
# 9  1348     1
#10  1349     1
# … with 670 more rows

Or using Map from base R
table(unlist(do.call(Map, c(f = `:`, df[-1]))))

A:   df1 <- data.frame(year=1000:2020) # Enter range for years of choice

  df1 %>%
  rowwise()%>%
  mutate(cnt=nrow(df %>%
                    filter(begin_datum_jaar<year & eind_datum_jaar>year)
                  )
         )


text:
Q: Store images in Mongodb serve them with Nodejs I understand Mongodb can store images in two ways.

*

*in a regular document by storing the image as binary

*via Gridfs for managing larger images.

For simplicity and because the images I plan to server are small, I will go for option 1.
To serve the images to a browser I am using nodejs.
My question is how difficult will this be? How do you turn binary data to an actual image a browser will understand? What type of encoding is involved?
Could you point me to tutorials/examples elsewhere on the web?
By the way I know this may not be good idea for performance reasons, I plan to cache the images once served. I just want to avoid the file-system all-together.

A: I would strongly advise against serving images from MongoDB.
It would be better to store them on a static filestore (S3) and maybe keep the path in MongoDB.

You would probably use base64 encoding to put the file into mongodb: http://www.greywyvern.com/code/php/binary2base64/ (or just base64 shell utility).
If you're just using regular documents then the performance cost is relatively low (so long as caching is good). If you're using a mixed database where you have GridFS and regular documents you're going to need a lot of RAM on your server(s) -- the GridFS queries will run completely differently from the document queries.
Converting the image might work like this:
var base64Data = imagefile.replace(/^data:image\/png;base64,/,""),
var dataBuffer = new Buffer(base64Data, 'base64');

// below line won't actually work but it's something along the lines of what you want:

db.foo.insert({magic: 123, etc... img: dataBuffer.toString()})

A: All you need to do to have your web-browser render the content is send the correct headers and response body.
So, assuming you are trying to render a PNG image, your mimetype would be image/png and then add the image files bytes to the response body.
The browser will then interpret this response as being an image of type PNG and render it appropriately


text:
Q: How the Pointers output as a Value is Work? I want to out put like below:
The Stack & the Class Template (in-lab portion)
test nodes: 101(-> / ) 212(-> / )
test next:  101(->212) 212(-> / )

But my out put will be like below:
The Stack & the Class Template (in-lab portion)
test nodes: 101 (-> / )  212 (-> / )
test next:  101 (->212 (-> / ) )  212 (-> / )

My header IntNode is like below:
class IntNode {
public:
    IntNode( int new_value );
    int      get_data( ) const;
    void     set_next( IntNode* new_next );
    IntNode* get_next( ) const;
    void     debug_write( ostream& outfile ) const;

private:
    int      payload;
    IntNode* next = nullptr;
};

ostream& operator<<( ostream& outfile, const IntNode& node );

The implementation of write function is below:
void IntNode::debug_write( ostream& outfile ) const{
        outfile << payload;
        if(next == nullptr)
            outfile << "(-> / ) ";
        else
            outfile << "(->" << *next << ") ";
}

ostream& operator<<( ostream& outfile, const IntNode& node ){
    node.debug_write(outfile);
    return outfile;
}

The main function is like below:
int main(){

    cout << "The Stack & the Class Template (in-lab portion)\n";
    IntNode int_item_1( 101 );
    IntNode int_item_2( 212 );
    cout << "test nodes: " << int_item_1 << ' ' << int_item_2 << "\n";
    int_item_1.set_next( &int_item_2 );
    cout << "test next:  " << int_item_1 << ' ' << int_item_2 << "\n\n";

    return 0;
}

A: Your immediate issue is in attempting to pass a dereferenced next pointer (e.g. *next) for output in your debug.write() function. According to your shown output you need to pass the payload for the next node for output, e.g. next->payload. That will provide the output you show.
Additionally, you must have using namespace std; somewhere in your code. Please look at Why is "using namespace std;" considered bad practice?.
You don't show the implementation for your remaining member functions, so we have to guess a bit that your class implementation looks similar to:
class IntNode {
  public:
    IntNode (int new_value) { payload = new_value; }
    int      get_data() const { return payload; }
    void     set_next (IntNode* new_next) { this->next = new_next; }
    IntNode *get_next() const { return next; }
    void     debug_write (std::ostream& outfile) const;

  private:
    int      payload = 0;
    IntNode *next = nullptr;
};

By ordering your function definitions in the right order, you can do away with the prototype for the overload of <<, e.g.
std::ostream& operator <<(std::ostream& outfile, const IntNode& node)
{
    node.debug_write (outfile);

    return outfile;
}

void IntNode::debug_write (std::ostream& outfile) const {
        outfile << payload;
        if(next == nullptr)
            outfile << "(-> / ) ";
        else
            outfile << "(->" << next->payload << ") ";
}

Then with the main() you show:
int main (void) {

    std::cout << "The Stack & the Class Template (in-lab portion)\n";

    IntNode int_item_1 (101);
    IntNode int_item_2 (212);

    std::cout << "test nodes: " << int_item_1 << ' ' << int_item_2 << "\n";

    int_item_1.set_next (&int_item_2);
    std::cout << "test next:  " << int_item_1 << ' ' << int_item_2 << "\n\n";
}

Example Use/Output
You receive the output you describe wanting:
$ ./bin/ll-intnode
The Stack & the Class Template (in-lab portion)
test nodes: 101(-> / )  212(-> / )
test next:  101(->212)  212(-> / )

When overloading << and >> for class use, you also have the option of declaring the overload function as a friend function allowing protected members to be directly accessed by the overloaded operator. Here you simply provide a public "getter" function used by the overloaded operator which is 100% fine.
look things over and let me know if you have further questions.


text:
Q: wpf remove converter from button style I'm using Mahapp Metro buttons in a wpf project. Some of the standard buttons have a converter defined in the contentpresenter of the original mahapp template.
f.e. squarebutton:
<ContentPresenter x:Name="contentPresenter"
ContentTemplate="{TemplateBinding ContentTemplate}"
Content="{TemplateBinding Content, Converter={StaticResource ToLowerConverter}}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"
RecognizesAccessKey="True"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
OpacityMask="{x:Null}" />

Is there a simple way I can change the squarebutton to NOT use the ToLowerConverter without changing the whole template?
I tried changing the ContentTemplate in a style, but without success:
<Style x:Key="MyFlyoverButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource SquareButtonStyle}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate>
                <TextBlock Text="{TemplateBinding Content}"   VerticalAlignment="{TemplateBinding VerticalAlignment}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" />
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>

A: Changing the ContentTemplate won't help you because that is just used by the  that you want to replace. You could use something like the following to access a ContentPresenter, but this only works on a per UI element basis from a UI collection, eg. you could use this to access the single ContentPresenter defined in a template from a ListBoxItem that has that template applied:
ContentPresenter contentPresenter = FindVisualChild(dependencyObject);

As that is no use to you, I won't bother showing the code for that method. The only other alternative you have is to define a new ControlTemplate. It should be a simple matter to define a new ControlTemplate if you have access to the default ControlTemplate.


text:
Q: React BrowserRouter only load the NavBar No error, the code should be right, but I got no result just the navbar is working.
I generated the basic app with npx
Code App.js
import React, {Component} from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import './App.css';

import NavBar from './components/NavBar';

import Home from './components/Home';
import Pagina2 from './components/Pagina2';
import Pagina3 from './components/Pagina3';
import Pagina4 from './components/Pagina4';
import Pagina5 from './components/Pagina5';

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <NavBar>
          <Switch>
            <Route path="/home" component={Home} />
            <Route path="/pagina2" component={Pagina2} />
            <Route path="/pagina3/:parametro1?/:parametro2?" component={Pagina3} />
          </Switch>
        </NavBar>
      </BrowserRouter>
    );
  }
}

export default App;

Navbar.js
import React, { Component } from 'react';

import { Link } from 'react-router-dom';

class NavBar extends Component {
    render() {
        return (

<Link to="/home">Home</Link>

<Link to="/pagina2/">Pagina 2</Link>

<Link to="/pagina3/aaa/bbb">Pagina 3</Link>

        );

    }
}
export default NavBar;

Home.js
import React, { Component } from 'react';
class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            myProps: ''
        };
    }
    render() {
        return (
            <>

Homepage

            </>
        );
    }
}

export default Home;

Pagina2.js
import React, { Component } from 'react';

import {NavLink} from 'react-router-dom';

class Pagina2 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            myProps: ''
        };
    }
    render() {
        return (
            <>

Pagina2

                <NavLink activeStyle={{color:'green'}}
                to={{
                    pathname:'/pagina3/a/b',
                    search:'?nome=aaa&eta=22',
                    hash:'#hash-value',
                    state:{
                        fromPagina2:"Info"
                    }
                }}>Link con parametri</NavLink>
            </>
        );
    }
}
export default Pagina2;

Pagina3.js
import React, { Component } from 'react';

class Pagina3 extends Component {
    constructor(props) {
        super(props);
        this.state = {
            parametro2: props.match.params.parametro2
        };
    }
    render() {
        const queryString = new URLSearchParams(this.props.location.search);
        return (
            <>

Pagina3

                {this.props.match.params.parametro1}
                {queryString.get('nome')}
            </>
        );
    }
}
export default Pagina3;

I only see this (I removed Pagina4 and Pagina5 because they are the same as Home).

I think there should not be any problem with my code, I checked it multiple times but it still not working. Maybe it's the npx or npm version... or the react-router-dom ^5.2.0... but if there is anything wrong with my code I really want to know why.

A: In React's JSX, you only need to write <NavBar></NavBar> when the component has child components, like this:
<NavBar>
    <Child />
    <Child />
    <Child />
</NavBar>

But here NavBar is Separate component and Route won't work as child of NavBar
Hence try modifying App.js like below
 <BrowserRouter>
    <>
     <NavBar/>
     <Switch>
       <Route path="/home" component={Home} />
       <Route path="/pagina2" component={Pagina2} />
       <Route path="/pagina3/:parametro1?/:parametro2?" component={Pagina3} />
     </Switch>
   </>
</BrowserRouter>

A similar example: https://codesandbox.io/s/react-bootstrap-nav-active-link-eqm0f

A: Your NavBar is a adjacent component of your page. Try:
import { BrowserRouter, Route, Switch } from 'react-router-dom';

import './App.css';

import NavBar from './components/NavBar';

import Home from './components/Home';
import Pagina2 from './components/Pagina2';
import Pagina3 from './components/Pagina3';
import Pagina4 from './components/Pagina4';
import Pagina5 from './components/Pagina5';

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <>
          <NavBar />
          <Switch>
            <Route path="/home" component={Home} />
            <Route path="/pagina2" component={Pagina2} />
            <Route path="/pagina3/:parametro1?/:parametro2?" component={Pagina3} />
          </Switch>
        </>
      </BrowserRouter>
    );
  }
}

export default App;


text:
Q: python socket send immediately The problem with sockets is that they buffer data and send it when buffer fills or in given interval. Any way to avoid it and send something through socket with high priority, without any delay? In my case milliseconds count.

A: TCP_NODELAY is the option you are looking for
Sample code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

For further info see
this SO QA
this article
this other SO QA
Note: on Linux systems option TCP_CORK is also available.
Experiment with both options in your application and see what happens.
Please read this exhaustive and very informative article about pros and cons of both.


text:
Q: Highcharts displays wrong month (next month) in datetime chart As mentioned in the title, Highcharts displays the next month instead of the correct month that I want to be shown.

So as per the code I provide I want it to display Feb in xAxis but it jumps to March instead.
How can I fix this to display  the month that I want?
Does Highcharts use the user timezone? How can I display a fixed timezone and avoid using user timezone?
https://jsfiddle.net/v4kasmv1/

A: Just edit 02 to 01 for Feb min: Date.UTC(2016,01,20) as 00 for Jan, 01 for Feb and 02 for March:
$(function () {
    Highcharts.setOptions({
        global: {
            //timezoneOffset: 3.30 * 60
        }
    });

    $('#container').highcharts({
        xAxis: {
            type: 'datetime',
            tickInterval: 3600 * 1000,
            min: Date.UTC(2016,01,20),
            max: Date.UTC(2016,01,21),
        },
        series: [{
            data: [
                [Date.UTC(2016, 01, 20,0,45), 1],
                [Date.UTC(2016, 01, 20,12,15), 3],
                [Date.UTC(2016, 01, 20,14,30), 6],
                [Date.UTC(2016, 01, 20,15,45), 9],
                [Date.UTC(2016, 01, 20,17,45), 5],
                ],
            pointStart: Date.UTC(2016, 01, 20),
            pointInterval: 3600 *1000
        }]
    });
});


text:
Q: Spark: Logistic regression This code works great!
val model = new LogisticRegressionWithLBFGS().setNumClasses(2).run(training)

I am able to call model.predict(...)
However, when I try to setup the model parameters, I can't call model.predict
For example, with the following code, I can't call predict on model variable.
val model = new LogisticRegressionWithLBFGS().setNumClasses(2)

model.optimizer.setUpdater(new L1Updater).setRegParam(0.0000001).setNumIterations(numIterations)
 model.run(training)

Any help with this will be great.

A: It happens because model in the second case is LogisticRegressionWithLBFGS not LogisticRegressionModel. What you need is something like this:
import org.apache.spark.mllib.classification.{
  LogisticRegressionWithLBFGS, LogisticRegressionModel}
import org.apache.spark.mllib.optimization.L1Updater

// Create algorithm instance
val lr: LogisticRegressionWithLBFGS = new LogisticRegressionWithLBFGS()
  .setNumClasses(2)

// Set optimizer params (it modifies lr object)
lr.optimizer
  .setUpdater(new L1Updater)
  .setRegParam(0.0000001)
  .setNumIterations(numIterations)

// Train model
val model: LogisticRegressionModel = lr.run(training)

Now model is LogisticRegressionModel and can be used for predictions.


text:
Q: How to select value from Dropdown in Selenium when it is an input Selection of Value from Dropdown in selenium webdriver when the type of dropdown is Input
Provided the XPath for the Dropdown clicked on it but not able to select values displayed.
Html for the Dropdown:

Value in Dropdown:
06/29/2019

Should be able to select any value form the Dropdown on the basis of User Input.

A: Use Dynamic Xpath as below:
    String date = "06/22/2019";

    String Xpath = "//tr[@class='dxeListBoxItemRow_PDPSTheme']/tr[contains(.,'"+date+"')]";

Find element of dropdown click on in and then click on the element as per above xpath.
you also need to scroll down or focus the element first
here date is the input and as per your input the element will be selected


text:
Q: Create DateTime from string without applying timezone or daylight savings How do I create a DateTime var from a string which is already adjusted for UTC?  I am running this on a machine set to BST (GMT+1).  If I run the following line of code:
DateTime clientsideProfileSyncStamp = Convert.ToDateTime("20-May-2011 15:20:00");

and then use the value in a test against a database holding (UTC) values then it would appear that the Convert.ToDateTime() is actually giving me a UTC value of 14:20.  I don't want it to do the conversion - I just want it to accept that my DateTime string is already in UTC.
Thanks.

A: @Guffa's answer is very good but i will like to add an additional answer.
If your datetime string is looking like this "2017-11-27T05:30:00.000Z" then AssumeUniversal is not working.
Try this :
    DateTime.Parse("2017-11-27T05:30:00.000Z", null, System.Globalization.DateTimeStyles.AdjustToUniversal);

There is a slight difference between AssumeUniversal and AdjustToUniversal. Read here : Difference between AssumeUniversal and AdjustToUniversal

A: Add a Z to the DateTime string:
DateTime clientsideProfileSyncStamp = Convert.ToDateTime("20-May-2011 15:20:00Z");
Console.Write(clientsideProfileSyncStamp.ToUniversalTime()); // 20-May-2011 15:20:00

A: Don't forget the TryParse variant which allows you to handle a parse error without an exception
DateTime clientsideProfileSyncStamp;
DateTime.TryParse(
    "20-May-2011 15:20:00",
    System.Globalization.CultureInfo.CurrentCulture,
    System.Globalization.DateTimeStyles.AssumeUniversal,
    out clientsideProfileSyncStamp
);

Also if you are not using ParseExact or TryParseExact it will assume the output Kind is Local so you may also want to use ToUniversalTime()
clientsideProfileSyncStamp.ToUniversalTime();

A: Parse the string, and specify that it should assume UTC time when there is no time zone specified in the string:
DateTime clientsideProfileSyncStamp =
  DateTime.Parse(
    "20-May-2011 15:20:00",
    CultureInfo.CurrentCulture,
    DateTimeStyles.AssumeUniversal
  );

A: Use
DateTimeOffset.Parse

The under-advertised DateTimeOffset type represents a point in time regardless of timezone differences, and as such should be used in preference to DateTime where a 'timestamp' is required.

A: DateTime.Parse() or DateTime.TryParse()
var clientsideProfileSyncStamp = DateTime.Parse("20-May-2011 15:20:00");

A: To create culture independent DateTime use:
DateTime.Parse("2022-02-15 09:30:47", CultureInfo.InvariantCulture)

Then the date stays always exactly as defined in string.


text:
Q: Creating dummy variables from variable with multiple values in r I have a data frame below where I want to add a new column where if language spoken is English then 1 else 0
language_spoken
         Jap;Fre
         Jap;Fre
         Fre;Ch
         Eng
         Eng;Jap
         Hindi;Eng

         Eng;Spanish;Fre
         Spanish;Jap
         Spanish

Final dataframe
      language_spoken   Eng
         Jap;Fre         0
         Jap;Fre         0
         Fre;Ch          0
         Eng             1
         Eng;Jap         1
         Hindi;Eng       1
                         0
        Eng;Spanish;Fre  1
        Spanish;Jap      0
        Spanish          0

what I tried is below but it's not working
     b <- data.frame(model.matrix(~.-1,data))
     b

Sample data set below:
     data <- data.frame(language_spoken = c("Jap;Fre","Jap;Fre","Fre;Ch","Eng","Eng;Jap","Hindi;Eng","","Eng;Spanish;Fre","Spanish;Jap","Spanish"))

A: In base R this will work:
data$Eng <- as.integer(grepl("Eng", data$language_spoken))

data
#>    language_spoken Eng
#> 1          Jap;Fre   0
#> 2          Jap;Fre   0
#> 3           Fre;Ch   0
#> 4              Eng   1
#> 5          Eng;Jap   1
#> 6        Hindi;Eng   1
#> 7                    0
#> 8  Eng;Spanish;Fre   1
#> 9      Spanish;Jap   0
#> 10         Spanish   0

This would be one tidyverse approach:
library(dplyr)
library(stringr)

data %>%
  mutate(Eng = as.numeric(str_detect(language_spoken, "Eng")))

#>    language_spoken Eng
#> 1          Jap;Fre   0
#> 2          Jap;Fre   0
#> 3           Fre;Ch   0
#> 4              Eng   1
#> 5          Eng;Jap   1
#> 6        Hindi;Eng   1
#> 7                    0
#> 8  Eng;Spanish;Fre   1
#> 9      Spanish;Jap   0
#> 10         Spanish   0

Created on 2021-07-21 by the reprex package (v0.3.0)

A: Does this work:
library(dplyr)
df %>% mutate(End = +grepl('Eng',language_spoken))
            language_spoken End
1                   Jap;Fre   0
2                   Jap;Fre   0
3                    Fre;Ch   0
4                       Eng   1
5                   Eng;Jap   1
6                 Hindi;Eng   1
7                             0
8           Eng;Spanish;Fre   1
9               Spanish;Jap   0
10                  Spanish   0


text:
Q: React-Native: Where the index.js file is called from? App initialisation and SplashScreen rendering executes form Mainactivity.java. Once this native part is over then React-Native comes into the picture. index.js is base file to execute all the React-Native code.
May I know how come control is coming to index.js?
Is there any file which calls index.js explicitly for further React-Native code execution?

A: And since 0.70 react native hermes engine by facebook is responsible to run javascript not v8 by google
you are able to see binaries also in react-native module
      java public class MainApplication extends Application implements ReactApplication {

          private final ReactNativeHost mReactNativeHost =
              new ReactNativeHost(this) {
                @Override
                public boolean getUseDeveloperSupport() {
                  return BuildConfig.DEBUG;
                }

                @Override
                protected List<ReactPackage> getPackages() {
                  @SuppressWarnings("UnnecessaryLocalVariable")
                  List<ReactPackage> packages = new PackageList(this).getPackages();
                  // Packages that cannot be autolinked yet can be added manually here, for example:
                  // packages.add(new MyReactNativePackage());
                  return packages;
                }
        //here
                @Override
                protected String getJSMainModuleName() {
                  return "index";
                }
              };

  @Override
  public void onCreate() {
    super.onCreate();
    // If you opted-in for the New Architecture, we enable the TurboModule system
    ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
    SoLoader.init(this, /* native exopackage */ false);
//-- more specifically  exactly here
    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
  }

and in react native module in node modules react.gradle

*
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

    import org.apache.tools.ant.taskdefs.condition.Os
    import org.gradle.internal.jvm.Jvm

    def config = project.hasProperty("react") ? project.react : [:];

    def detectEntryFile(config) {
        if (System.getenv('ENTRY_FILE')) {
            return System.getenv('ENTRY_FILE')
        } else if (config.entryFile) {
            return config.entryFile
        } else if ((new File("${projectDir}/../../index.android.js")).exists()) {
            return "index.android.js"
        }
    //here
        return "index.js";
    }


text:
Q: SQL min function I am trying to get two columns, frequency and frequency - min(frequency) but all I see is zero for the second column. What could possibly be wrong?
SELECT
    frequency, frequency - min(frequency)
    FROM
    words
GROUP BY id
ORDER BY frequency;

A: Your query groups by the unique value of frequency. In each such group, the minimal frequency is just the frequency itself, so you always get 0 when subtracting the two. Instead, you could use the windowing version of min:
SELECT   frequency, frequency - MIN(frequency) OVER() AS diff
FROM     words
ORDER BY frequency

A: Add a sub-query that returns the min frequency value:
SELECT
    frequency, frequency - (select min(frequency) from words)
    FROM
    words
ORDER BY frequency;

Edit:
Wrap it up in a derived table:
SELECT frequency, frequency - minfreq, frequency + minfreq
FROM words
    CROSS JOIN (select min(frequency) minfreq from words) dt
ORDER BY frequency

A: Try it:
SELECT frequency, frequency-min_frequency
FROM (
SELECT frequency,  MIN(frequency) AS min_frequency
FROM words
GROUP BY frequency
) as A
ORDER BY frequency;

A: This is certainly a queer query. You group by ID, so you get one result record per ID. But ID suggests that this is the table's ID identifying records uniquely. So GROUP BY id doesn't change anything, you still get all records in your results. With one exception: min(frequency) now means the minimum frequency per group. As the "group" is one record, the minimum value is the the value itself of course. The non-aggregated frequency is also the records' frequency uniquely identified by ID. So your query can be re-written as:
SELECT
  frequency, frequency - frequency
FROM words
ORDER BY frequency;

I suppose you want to compare each record's frequency with the minimum frequency found in the table? You'd get this value in a subquery:
SELECT
  frequency, frequency - (select min(frequency) from words)
FROM words
ORDER BY frequency;

Or:
SELECT
  w.frequency, w.frequency - m.min_frequncy
FROM words w
CROSS JOIN (select min(frequency) as min_frequncy from words) m
ORDER BY frequency;


text:
Q: Unity references break after scene reload I'm facing a weird issue in unity, the references keep breaking as soon as i reload a scene, i tried to understand what is really going on but no luck.
i made a script to replicate the issue you can find bellow.
when i edit the last data element "list" by changing the size, the change is reflected on the other data objects list, cause they are treated just as references.
.
if i reload the scene, the changes are not reflected anymore as previously, it behaves like copies instead of references this time.
can someone help me figure out what is going on ?
.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

public class test : MonoBehaviour
{

    public List<data> Data = new List<data>();
}
[System.Serializable]
public class data
{

    public List<int> list = new List<int>();
}
[CustomEditor(typeof(test))]
public class testEditor:Editor
{
    test test;
    public void OnEnable()
    {
        test = (test)target;
    }
    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        if (GUILayout.Button("Add"))
        {
            data data = new data();
            if (test.Data.Count >= 1) data.list = test.Data[test.Data.Count - 1].list;
            test.Data.Add(data);

            EditorUtility.SetDirty(test);
        }
        if (GUILayout.Button("Clear"))
        {
            test.Data.Clear();

            EditorUtility.SetDirty(test);
        }
    }
}

A: In general: Don't directly access and change the values of your MonoBehaviour instance!
As you noted you will have to handle all kind of marking dirty and saving yourself. What you experience when re-opening the scene in the Editor that something wasn't marked dirty correctly and thus not saved together with the scene.

Always rather go through SerializedPropertys which handle all the marking dirty and saving and especially also undo/redo etc. automatically:
[CustomEditor(typeof(test))]
public class testEditor : Editor
{
    private SerializedProperty Data;

    public void OnEnable()
    {
        Data = serializedObject.FindProperty(nameof(test.Data));
    }

    public override void OnInspectorGUI()
    {
        DrawDefaultInspector();

        // load all current values of the properties in test into the SerializedProperty "clones"
        serializedObject.Update();

        if (GUILayout.Button("Add"))
        {
            // this simply adds a new entry to the list
            // since the data and list are both serializable this already initializes them with values
            Data.arraySize++;

            // Actually the entire following block is redundant
            // by using Data.arraySize++; the new added entry automatically
            // is a full copy of the entry before!
            // I just decided to add it as example how you would access further nested SerializedProperties

            //// if there was an element before now there are two
            //if (Data.arraySize >= 2)
            //{
            //    // get the last added element
            //    var lastElement = Data.GetArrayElementAtIndex(Data.arraySize - 1);
            //    var beforeElement = Data.GetArrayElementAtIndex(Data.arraySize - 2);

            //    // deep clone the list
            //    var lastElementList = lastElement.FindPropertyRelative(nameof(data.list));
            //    var beforeElementList = beforeElement.FindPropertyRelative(nameof(data.list));

            //    lastElementList.arraySize = beforeElementList.arraySize;
            //    for (var i = 0; i < lastElementList.arraySize; i++)
            //    {
            //        lastElementList.GetArrayElementAtIndex(i).intValue = beforeElementList.GetArrayElementAtIndex(i).intValue;
            //    }
            //}
        }

        if (GUILayout.Button("Clear"))
        {
            Data.arraySize = 0;
        }

        // write back the values of the SerializedProperty "clones" into the real properties of test
        serializedObject.ApplyModifiedProperties();
    }
}

This now handles all marking dirty, saving the scene correctly, undo/redo etc automatically and you don't have to take care about that anymore.

And then a little "pro" tip: Use ReorderableList! It looks a bit tricky to set up but is extremly powerful: Among other things as the name says it allows you to simply reorder the elements by drag and drop in the Inspector and also allows to delete an item from the middle which is impossible with the normal list drawer. This completely replaces your Add and Clear buttons:
using UnityEditor;
using UnityEditorInternal;

[CustomEditor(typeof(test))]
public class testEditor : Editor
{
    private SerializedProperty Data;
    private ReorderableList dataList;

    public void OnEnable()
    {
        Data = serializedObject.FindProperty(nameof(test.Data));

        //                                 should the list
        //                                                     | be reorderable by drag&drop of the entries?
        //                                                     |     | display a header for the list?
        //                                                     |     |     | have an Add button?
        //                                                     |     |     |     | have a Remove button?
        //                                                     v     v     v     v
        dataList = new ReorderableList(serializedObject, Data, true, true, true, true)
        {
            // what shall be displayed as header
            drawHeaderCallback = rect => EditorGUI.LabelField(rect, Data.displayName),

            elementHeightCallback = index =>
            {
                var element = Data.GetArrayElementAtIndex(index);
                var elementList = element.FindPropertyRelative(nameof(data.list));
                return EditorGUIUtility.singleLineHeight * (elementList.isExpanded ? elementList.arraySize + 4 : 3);
            },

            drawElementCallback = (rect, index, isFocused, isActive) =>
            {
                var element = Data.GetArrayElementAtIndex(index);

                EditorGUI.LabelField(new Rect(rect.x,rect.y,rect.width,EditorGUIUtility.singleLineHeight), element.displayName);
                // in order to print the list in the next line
                rect.y += EditorGUIUtility.singleLineHeight;

                var elementList = element.FindPropertyRelative(nameof(data.list));
                EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width,  EditorGUIUtility.singleLineHeight * (elementList.isExpanded ? elementList.arraySize + 1 : 1)), elementList, true);
            }
        };
    }

    public override void OnInspectorGUI()
    {
        // load all current values of the properties in test into the SerializedProperty "clones"
        serializedObject.Update();

        dataList.DoLayoutList();

        // write back the values of the SerializedProperty "clones" into the real properties of test
        serializedObject.ApplyModifiedProperties();
    }
}

Note If not the case already anyway:
The testEditor part should

*

*either be placed in a different script in a folder called Editor

*or you should wrap anything related to the UnityEditor namespace within pre-processors like
#if UNITY_EDITOR
using UnityEditor;
using UnityEditorInternal;
#endif

...

#if UNITY_EDITOR
[CustomEditor(typeof(test))]
public class testEditor : Editor
{
    ...
}
#endif

otherwise you will get errors when building the app since the UnityEditor namespace is stripped of in a build and exists only inside the Unity Editor itself.


text:
Q: Desire2Learn: start with SIS Org Code, retrieve Org ID My team is using D2L Valence to supplement our SIS integration. Our use case is to enroll (i.e., create a NEW enrollment for) a known User into a known Course Offering, both of which originally came from the SIS.
We're bumping into the common problem of "how to retrieve a D2L Org ID when all you have is the SIS Org Code". The best previous solution I've seen is:

Desire 2 Learn Org Unit ID: Retrieve all Course Offering descendants of the university. Then pattern-match inside the JSON result to find the Offering you're looking for.

But there's a caveat: "This process will almost certainly require fetching a large amount of data, and then parsing through it." It also recommends to (1) start the search further down in the org structure, if you know THAT Org ID; and (2) "then persist and use [this data] directly later."
These are problematic because our D2L org structure is big (~3500 offerings per semester) and constantly shifting and growing. We don't want to persist any D2L data; we'd rather retrieve on the fly.
So is this the most efficient current method of retrieving a single Org ID for an object that came from our SIS? If so, are there any plans for a method that retrieves a unit by Org Code?

A: The information in the link you quoted is still current. The functionality you are identifying is in the list of requests. It is expected to take a form similar to search-for-users-by-orgedfinedid. Prior to a given release you will see docs appear on valence that identify new calls, so you will be able to follow if a given release includes a change like this one.


text:
Q: Is there a way that i can fix my server greeting? While creating the server greeting for my discord bot and following along with a youtube video i created this part of code for my bot.
I save and run the code and it does not replace ${member} with the username of the joining member to welcome them into the server.
I've tried changing ${member} to the following:
${Member}
and
@{member}
bot.on('guildMemberAdd', member => {

      const channel = member.guild.channels.find(channel => channel.name === "welcome");
      if(!channel) return;

      channel.send('Welcome to our server, ${member}, Read our server rules / introduce yourself and get comfortable! We thank you for joining our server.')

I Expected : Welcome to our server, @JohnDoe, Read our server rules / introduce yourself and get comfortable! We thank you for joining our server.
Actual Output : Welcome to our server, ${member}, Read our server rules / introduce yourself and get comfortable! We thank you for joining our server.

A: Use back-ticks/grave accents (`) instead of quotes, like this:
`Welcome to our server, ${member}, Read our server rules / introduce yourself and get comfortable! We thank you for joining our server.`

More about template literals.


text:
Q: Metropolis-Hastings : Finding the transition matrix given the state space and the stationary distribution In this paper Diaconis, P. (2009). The markov chain monte carlo revolution. Bulletin of the American Mathematical Society, 46(2), 179-205. https://math.uchicago.edu/~shmuel/Network-course-readings/MCMCRev.pdf , the author uses the Metropolis-Hastings algorithm to decipher a message ciphered with a simple substitution cipher.
Since it is a MCMC algorithm and the number of ciphers is finite, there is a Markov chain with a transition matrix behind this algorithm. However, I have no clue about the coefficients of that matrix.
I understand so far that the state space is the permutation space of the 26 letters of the alphabet, that the stationary distribution is proportional to :
Pl($\sigma$) =$\displaystyle \prod_{i=1}^n$
M ($\sigma(s_i),\sigma(s_{i+1}))$
Where $s_i$ is the i-th letter of the ciphered message, $\sigma$ is any permutation of the 26 letters and $M(a,b)$ is the probability that the letter a is followed by the letter b in English.
Hence my question : What is the transition matrix associated to this stationary distribution ?
Thank you for your help

A: The answer seems to be in the part 3.1 of the same article (here the alphabet only has three letters and instead of $PL(\sigma)$ a function with similar behaviour is used $\pi(\sigma)$
The coefficients of the transition matrix are simply equal to the probability that, if the n-th element of the sample from the Metropolis algorithm is the permutation $\sigma_i$, the next element generated by the algorithm is the permutation $\sigma_j$ (assuming the Metropolis algorithm has "already" converged to the desired stationary distribution)


text:
Q: Do there exist an infinite number of integer-solutions $(x,y,z)$ of $x^x\cdot y^y=z^z$ where $1\lt x\le y$? Question : Do there exist an infinite number of integer-solutions $(x,y,z)$ of $x^x\cdot y^y=z^z$ where $1\lt x\le y$ ?
Motivation : After struggling to find a solution, I've just got one solution, which is
$$(x,y,z)=(1679616, 2985984, 4478976).$$
In the following, I'm going to write how I got this solution.
Letting $d$ be the greatest common divisor of $x,y,z$, we can represent
$$x=ad, y=bd, z=cd$$
where $a,b,c$ are coprimes with each other. Then, we get
$$d^{a+b-c}\cdot a^a\cdot b^b=c^c.$$
In the following, let's consider without the condition $x\le y$. Here, I suppose
$$a=2^m, b=3^n, a+b-c=1.$$
(As a result, this supposition works.)
Then, we get
$$d=\frac{c^c}{2^{ma}\cdot 3^{nb}}.$$
Hence, letting $c=2^k\cdot 3^l$, if
$$kc\ge ma=m\cdot 2^m, lc\ge nb=n\cdot 3^n,$$
then $d$ is an integer.
Since $(m,n)=(4,2)$ satisfies the above conditions, then we get $d=2^8\cdot 3^6=186624.$ Hence we can get
$$x=9d=2^8\cdot 3^8=1679616, y=16d=2^{12}\cdot 3^6=2985984, z=24d=2^{11}\cdot 3^7=4478976.$$
Note that here I interchanged $x$ and $y$.
P.S : I was surprised to get this solution because I got this almost by chance. So, I don't know the other solutions. If you have any helpful information, please teach me.

A: Ke Zhao find these solutions: $n\in\mathbb N,$
$$x=2^{2^{n+1}(2^n-n-1)+2n}(2^n-1)^{2(2^n-1)},\\
y=2^{2^{n+1}(2^n-n-1)}(2^n-1)^{2(2^n-1)+2},\\
z=2^{2^{n+1}(2^n-n-1)+n+1}(2^n-1)^{2(2^n-1)+1}.$$
You may find that these solutions satisfies $4xy=z^2,$ W.H.Mills proved that
1)If $4xy=z^2$ then Ke Zhao's solutions are all of them.
2)If $4xy>z^2$ then there has no solutions.
3)If $4xy<z^2$ then there only exist fintite many solutions.
Hence maybe Ke Zhao has given all the solutions to $x^xy^y=z^z,$ but this has not been proven.

A: I've just got the following in a similar way as above.
The answer is Yes; there exist an infinite number of solutions.
Letting $p,q$ be coprime integers with each other, suppose
$$a=p^m, b=q^n, a+b-c=1, c=p^k\cdot q^l, kc\ge ma, lc\ge nb.$$
Here, I got the following because of a relational equation $N^2+(N-1)^2=2N(N-1)+1$.
$$p=N-1, m=2, N=2^s, q=2, n=2s, k=1, l=s+1,$$$$ a=(2^s-1)^2, b=2^{2s}, c=2^{s+1}(2^s-1).$$
Now, we know that if $s\ge 2$, then these satisfy the above conditions. Also, note that the $s=2$ case is the case I found.
Hence, we get
$$d=2^u\cdot p^v, u=2^{s+1}(2^s-s-1), p=2^s-1, v=2(2^s-1),$$$$ x=2^u\cdot p^{v+1}, y=2^{2s+u}\cdot p^v, z=2^{u+s+1}\cdot p^{v+1}.$$
You can take every integer larger than or equal to $2$ as $s$, then we now know that there exist an infinite number of solutions. Now the proof is completed.
$P.S.$ For $s=3$, we get
$$p=7, a=49, b=64, c=112, u=64, v=14,$$$$ x=2^{64}\cdot 7^{16}, y=2^{70}\cdot 7^{14}, z=2^{68}\cdot 7^{15}.$$
Note that $z=2^{68}\cdot 7^{15}\approx 10^{33}.$
I'm interested in finding every solution, which seems very hard.


text:
Q: APIs for redirecting to live TV channels of sonyliv, zee5, voot, and other OTT apps? I am trying to search for any APIs or deep links that can allow me to redirect to specific live TV channels in the OTT apps like Sonyliv, Zee5, Voot, etc.
Any help is appreciated
This is still a new topic and couldn't find information


text:
Q: missing right parenthesis with update statment i am trying to make a normal update statement .
update adm_types_uda set type_id =28202 where recid in (
SELECT  recid FROM
    (
    SELECT *FROM adm_types_uda
    ORDER BY recid desc
    )
WHERE rownum <= 284
ORDER BY recid )

it gives me
SQL Error: ORA-00907: missing right parenthesis

the inner select between in worked well independent .
i try to give all select an alias but still give the same error
update adm_types_uda uda set uda.type_id =28202 where uda.recid in (
SELECT  gd.recid FROM
    (
    SELECT * FROM adm_types_uda u
    ORDER BY u.recid desc
    ) gd
WHERE rownum <= 284
ORDER BY gd.recid)

can any one help ?

A: Fixed version:
update demo
set    type_id = 28202
where  recid in
       ( select recid from
                ( select *from demo
                  order by recid desc )
         where rownum <= 284 )

My first attempt which was wrong (thanks mathguy) was to refactor the outer where rownum ... order by ... by moving it into the inner subquery, however I missed that the outer order by was redundant anyway and it just needed removing.
The 'missing right parenthesis' error was because the parser doesn't recognise the order by in the subquery as this is not allowed (I couldn't see any explicit statement about this in the SQL reference, but it isn't).

A: Remove the last ORDER BY clause, which doesn't do anything anyway (it makes no sense to ORDER a set of rows used in an IN condition) and is illegal there.
After you delete it, the query will work just fine.


text:
Q: How to add ambient Serilog properties during an MVC controller's action processing I'd like to add a Serilog property to all logging that occurs within the scope of a request to an ASP.NET Core controller.  The value of this property is determined by routing data.
Conceptually, this is easy, I just add something like the following to my controller:
public override void OnActionExecuting(ActionExecutingContext context)
{
   var propValue = context.ActionArguments["myvalue"] as string;
   // BAD CODE DON'T COPY THIS
   LogContext.PushProperty("MyProperty", propValue);
   base.OnActionExecuting(context);
}

This "works", in that it adds 'MyProperty' to every logged event all the way down for the rest of the call to this request.  However, it's clearly not the right way to do this, as the docs give strict instructions to carefully dispose calls to LogContext.PushProperty in the reverse order to which they were pushed.  There's nothing to say that LogContext has the same scope as the HTTP request anyway.
I thought IDiagnosticContext was the solution, but it only affects the Serilog's request logging, it's not a general ambient context.
The framework actually achieves exactly what I want, decorating the log context with things like 'ActionName' and 'RequestId' - but I guess it does this at some point where the scope of the request is much clearer.
Is there a simple way to add ambient Serilog properties "for the rest of the current request", or do I need to write middleware to do this?

A: OK, turns out there's an easy solution to this and that Controller has a more suitable override than OnActionExecuting:
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
    var propValue = context.ActionArguments["myvalue"] as string;
    using (LogContext.PushProperty("MyProperty", propValue))
    {
        await base.OnActionExecutionAsync(context, next);
    }
}


text:
Q: Html form values not getting as typed +php I have a php page

Comments

       <textarea name="comments"></textarea>
    	</tr

I am typing some values in the comment box like this
*
first sentence
second sentence

but when i try to echo the comment box value as echo $_POST['comments'];
it will out put as
first sentence second sentence.
How can i out put it as
first sentence
second sentence

A: Run it through nl2br(). Line breaks have no meaning in HTML output.

A: You could wrap it in nl2br() - http://php.net/manual/en/function.nl2br.php


text:
Q: Description of Puzzle Type I am looking for the name of a certain type of word puzzle.  A string of letters is given without any spaces between those letters.  By strategically inserting spaces into the string, different valid phrases are generated.
I would use Google for this, but Google is tough if you don't know the search phrase.


text:
Q: How to make a disappearing glow effect Let's say i have a button class
.mat-cancel-color {
    width: 160px;
    border: 1px solid #dddddd;
    color: #dddddd;
    background-color: white;
    border-radius: 25px;
}

and whenever i click something(not the 'mat-cancel-color' button) i want this class to gain a glow effect which would fade away over .4s.
should i create a new class and then give that class the box-shadow(glow) property, then below  transition-duration property and then the the box-shadow(no glow) property again? as such:
click-class {
-webkit-box-shadow: 0px 0px 15px 10px rgba(255,255,0,1);
-moz-box-shadow: 0px 0px 15px 10px rgba(255,255,0,1);
box-shadow: 0px 0px 15px 10px rgba(255,255,0,1);
transition-duration: .4s;
-webkit-box-shadow: 0px 0px 0px 0px rgba(255,255,0,1);
-moz-box-shadow: 0px 0px 0px 0px rgba(255,255,0,1);
box-shadow: 0px 0px 0px 0px rgba(255,255,0,1);
}

or does transition-duration only work when switching classes or does it also work when switching properties inside a class? if it as such, how should i go about it?
EDIT: mistook transition-delay with transition-duration.

A: What you are looking for is a CSS animation. Mainly because you don't want the default state with the glow, that's why transition won't work here.

.mat-cancel-color {
  width: 160px;
  border: 1px solid #dddddd;
  color: #dddddd;
  background-color: white;
  border-radius: 25px;
}

.mat-cancel-color:hover {
  animation-name: glow;
  animation-duration: .4s;
}

.mat-cancel-color-trans {
  width: 160px;
  border: 1px solid #dddddd;
  color: #dddddd;
  background-color: white;
  border-radius: 25px;
  transition: all .4s ease;
  box-shadow: 0px 0px 15px 10px rgba(255, 255, 0, 0);
}

.mat-cancel-color-trans:hover {
  box-shadow: 0px 0px 0px 0px rgba(255, 255, 0, 1);
}

/* Standard syntax */

@keyframes glow {
  0% {
    box-shadow: 0px 0px 15px 10px rgba(255, 255, 0, 1);
  }
  100% {
    box-shadow: 0px 0px 0px 0px rgba(255, 255, 0, 1);
  }
}
<button class="mat-cancel-color">Button</button>

<button class="mat-cancel-color-trans">Button</button>

A: You could use some psudo classes like this:
:active:not(*element/class*) {...}

and then put the glow animation that you want within the brackets. :active is a psudo class that is only applied when the element named is clicked. :not() excludes the class listed in the parentheses. As long as you have the glow animation working fine, then this should work.
This is a snippet of my test code:
a:active:not(.mat-cancel-color) {...}


text:
Q: How can I functionally update a dataclass? I'd like to copy an instance of a frozen dataclass, changing just one field ("functional update").
Here's what I tried
from dataclasses import dataclass, asdict
@dataclass(frozen = True)
class Pos:
    start: int
    end: int

def adjust_start(pos: Pos, delta: int) -> Pos:
   # TypeError: type object got multiple values for keyword argument 'start'
   return Pos(**asdict(pos), start = pos.start + delta)

adjust_start(Pos(1, 2), 4)

What I'm looking for:

*

*Is there a more straightforward way than converting to/from dicts?

*How to get around the TypeError: if there is a way to functionally update kwargs then that could work.

In Scala, a functional update of a case class (Scala dataclass) can be done like this: pos.copy(start = pos.start + delta).

A: dataclasses.replace() to the rescue.

dataclasses.replace(obj, /, **changes) creates a new object of the same type as obj, replacing fields with values from changes.

import dataclasses

@dataclasses.dataclass(frozen=True)
class Pos:
    start: int
    end: int

def adjust_start(pos: Pos, delta: int) -> Pos:
    return dataclasses.replace(pos, start=pos.start + delta)

p = adjust_start(Pos(1, 2), 4)

Personally, I might put adjust on the dataclass itself:
import dataclasses

@dataclasses.dataclass(frozen=True)
class Pos:
    start: int
    end: int

    def adjust(self, *, start: int, end: int) -> "Pos":
        return dataclasses.replace(
            self,
            start=self.start + start,
            end=self.end + end,
        )

p = Pos(1, 2).adjust(start=4)

A: You can use a @cached_class_property approach with dataclasses.fields().
For example:
from dataclasses import fields, dataclass

class cached_class_property(object):
    """
    Descriptor decorator implementing a class-level, read-only property,
    which caches the attribute on-demand on the first use.

    Credits: https://stackoverflow.com/a/4037979/10237506
    """
    def __init__(self, func):
        self.__func__ = func
        self.__attr_name__ = func.__name__

    def __get__(self, instance, cls=None):
        """This method is only called the first time, to cache the value."""
        if cls is None:
            cls = type(instance)

        # Build the attribute.
        attr = self.__func__(cls)

        # Cache the value; hide ourselves.
        setattr(cls, self.__attr_name__, attr)

        return attr

@dataclass(frozen=True)
class Pos:
    start: int
    end: int

    @cached_class_property
    def init_fields(cls):
        return tuple(f.name for f in fields(cls) if f.init)

    def adjust_start(self, delta: int) -> 'Pos':
        attrs = [getattr(self, f) + delta if f == 'start' else getattr(self, f)
                 for f in Pos.init_fields]

        return Pos(*attrs)

p1 = Pos(1, 2)
print(p1)

p2 = Pos(1, 2).adjust_start(4)
print(p2)

As you are using a frozen=True dataclass and with slots=False, you could also simplify this approach, i.e. without the use of @cached_class_property:
def adjust_start(self, delta: int) -> 'Pos':
    _dict = self.__dict__.copy()
    _dict['start'] += delta

    return Pos(*_dict.values())

Output:
Pos(start=1, end=2)
Pos(start=5, end=2)

Results show it's ever slightly faster than dataclasses.replace():
from dataclasses import fields, dataclass, replace
from timeit import timeit

@dataclass(frozen=True)
class Pos:
    start: int
    end: int

    # `cached_class_property` defined from above
    @cached_class_property
    def init_fields(cls):
        return tuple(f.name for f in fields(cls) if f.init)

    def adjust_via_copy(self, delta: int) -> 'Pos':
        _dict = self.__dict__.copy()
        _dict['start'] += delta

        return Pos(*_dict.values())

    def adjust_via_fields(self, delta: int) -> 'Pos':
        attrs = [getattr(self, f) + delta if f == 'start' else getattr(self, f)
                 for f in Pos.init_fields]

        return Pos(*attrs)

    def adjust_via_replace(self, delta: int) -> 'Pos':
        return replace(
            self,
            start=self.start + delta,
        )

p = Pos(1, 2)

print('o.__dict__.copy:      ', round(timeit('p.adjust_via_copy(4)', globals=globals()), 3))
print('dataclasses.fields:   ', round(timeit('p.adjust_via_fields(4)', globals=globals()), 3))
print('dataclasses.replace:  ', round(timeit('p.adjust_via_replace(4)', globals=globals()), 3))

assert Pos(-2, 2) == p.adjust_via_replace(-3) == p.adjust_via_fields(-3) == p.adjust_via_replace(-3)

o.__dict__.copy:       0.408
dataclasses.fields:    0.499
dataclasses.replace:   0.659


text:
Q: 355/113 and small odd cubes An important approximation to $\pi$ is given by the convergent $\frac{355}{113}$.
The numerator and the denominator of this fraction are at the same distance of small consecutive odd cubes.
$$\frac{355}{113} = \frac{7^3+12}{5^3-12}$$

Is this a consequence of some general formula, such as a series or continued
fraction?

Attempts, drafts
$$\frac{113}{355} = \frac{1}{10}\left(2+\frac{5^3}{3+\frac{7^3}{4}}\right)-\frac{8}{355} = \frac{1}{5}\left(3-\frac{5^3}{3+\frac{7^3}{4}}\right)$$
Similarly, for $\frac{22}{7}$
$$\frac{7}{22} =\frac{1}{2}\left(\frac{3^3}{1+\frac{4^3}{2}}\right) -\frac{1}{11}$$
For the first convergent $3$,
$$\frac{3^3-6}{1^3+6}=\frac{21}{7}=3$$
The tentative expression
$$a(n)=\frac{(4n+3)^3+6(3n-1)}{(4n+1)^3-6(3n-1)}$$
has $a(0)=3$ and $a(1)=\frac{355}{113}$ but $\lim_{n \to \infty} a(n) = 1 \neq \pi$
A similar fraction for the approximation $\frac{223}{71}$ (Archimedes' lower bound) is
$$\frac{98+5^3}{98-3^3}=\frac{2·7^2+5^3}{2·7^2-3^3}=\frac{223}{71}=3+\frac{1}{7+\frac{1}{10}}$$

A: For a coprime pair of integers $1 \le p,q$, consider the following diophantine equation:
$$\frac{x^3+z}{y^3-z}= \frac{p}{q}$$
with $x,y,z$ integer unknowns. This is equivalent to
$$z= \frac{y^3p-x^3q}{p+q}$$
Thus a solution exists if and only if there exist $x,y$ such that
$$y^3p-x^3q \equiv 0 \pmod{(p+q)}$$
Now, note that $-q \equiv p$, and that it has an inverse $\mod (p+q)$. This means that we need
$$x^3+y^3 \equiv 0 \pmod{(p+q)}$$
Now, if we pick $p=355$ and $q=113$, we get
$$p+q=468 = 7^3+5^3$$
In other words, the fraction $355/113$ has such a special property not because it is a convergent of $\pi$, but simply because the sum of numerator and denominator is a sum of two small cubes. We can do the same job with the fraction
$$\frac{203}{265} = \frac{5^3+78}{7^3-78}$$
nothing special with $\pi$.
As for $22/7$ we can find $$\frac{22}{7} = \frac{17^3+5^3}{12^3-5^3}$$
which is even more surprising. In my opinion, having three variables gives you a lot of freedom, so that yo can find such nice forms for any rational number.
EDIT: Just for fun, I looked up convergents of a completely different constant, namely $\gamma$: Euler-Mascheroni constant. One of its convergents is
$$\frac{71}{123}= \frac{3^3+470}{11^3-470}$$ Again, there is nothing special about this rational, simply you can find such a form for any number.


text:
Q: nodetool with Java 8u331 returns "URISyntaxException: 'Malformed IPv6 address at index 7: rmi://[127.0.0.1]:7199'" Why does running nodetool return the following exception?
nodetool: Failed to connect to '127.0.0.1:7199' - \
  URISyntaxException: 'Malformed IPv6 address at index 7: rmi://[127.0.0.1]:7199'.

This question is commonly reported by Cassandra users after upgrading Java on servers.

A: Root cause
The URL parser for JNDI providers which includes RMI (used by JMX) has been improved in Oracle Java 8u331 and brackets are only allowed around IPv6 addresses (JDK-8278972).
Attempts to run nodetool with newer Java versions breaks because the host in the RMI URL is enclosed in square brackets (from NodeProbe.java class):
    private static final String fmtUrl = "service:jmx:rmi:///jndi/rmi://[%s]:%d/jmxrmi";

Workarounds
OPTION 1 - Add the "legacy" parsing flag when running nodetool, for example:
$ nodetool -Dcom.sun.jndi.rmiURLParsing=legacy status

OPTION 2 - Specify the hostname with an IPv6 subnet prefix, for example:
$ nodetool -h ::FFFF:127.0.0.1 status

Solution
This issue has been addressed in Apache Cassandra 3.0.27, 3.11.13, 4.0.4 and 4.1 releases (CASSANDRA-17581).
Upgrade to the latest patch release to fix the issue in your cluster. Cheers!

Republished from DataStax Community.

 Please support the Apache Cassandra community by hovering over cassandra then click on the Watch tag button.  Thanks!


text:
Q: Remove last comma (and possible whitespaces after the last comma) from the end of a string Using JavaScript, how can I remove the last comma,  but only if the comma is the last character or if there is only white space after the comma? This is my code.
I got a working fiddle. But it has a bug.
var str = 'This, is a test.';
alert( removeLastComma(str) ); // should remain unchanged

var str = 'This, is a test,';
alert( removeLastComma(str) ); // should remove the last comma

var str = 'This is a test,          ';
alert( removeLastComma(str) ); // should remove the last comma

function removeLastComma(strng){
    var n=strng.lastIndexOf(",");
    var a=strng.substring(0,n)
    return a;
}

A: In case its useful or a better way:
str = str.replace(/(\s*,?\s*)*$/, "");

It will replace all following combination end of the string:
1. ,<no space>
2. ,<spaces>
3. ,  ,  , ,   ,
4. <spaces>
5. <spaces>,
6. <spaces>,<spaces>

A: The greatly upvoted answer removes not only the final comma, but also any spaces that follow. But removing those following spaces was not what was part of the original problem. So:
let str = 'abc,def,ghi, ';
let str2 = str.replace(/,(?=\s*$)/, '');
alert("'" + str2 + "'");
'abc,def,ghi '

https://jsfiddle.net/dc8moa3k/

A: This will remove the last comma and any whitespace after it:
str = str.replace(/,\s*$/, "");

It uses a regular expression:

*

*The / mark the beginning and end of the regular expression

*The , matches the comma

*The \s means whitespace characters (space, tab, etc) and the * means 0 or more

*The $ at the end signifies the end of the string

A: long shot here
var sentence="I got,. commas, here,";
var pattern=/,/g;
var currentIndex;
while (pattern.test(sentence)==true)  {
  currentIndex=pattern.lastIndex;
 }
if(currentIndex==sentence.trim().length)
alert(sentence.substring(0,currentIndex-1));
else
 alert(sentence);

A: Remove last comma. Working example

function truncateText() {
  var str= document.getElementById('input').value;
  str = str.replace(/,\s*$/, "");
  console.log(str);
}
<input id="input" value="address line one,"/>
<button onclick="truncateText()">Truncate</button>

A: First, one should check if the last character is a comma.
If it exists, remove it.
if (str.indexOf(',', this.length - ','.length) !== -1) {
    str = str.substring(0, str.length - 1);
}

NOTE str.indexOf(',', this.length - ','.length) can be simplified to str.indexOf(',', this.length - 1)

A: you can remove last comma from a string by using slice() method, find the below example:
var strVal = $.trim($('.txtValue').val());
var lastChar = strVal.slice(-1);
if (lastChar == ',') {
    strVal = strVal.slice(0, -1);
}

Here is an Example

function myFunction() {
 var strVal = $.trim($('.txtValue').text());
 var lastChar = strVal.slice(-1);
 if (lastChar == ',') { // check last character is string
  strVal = strVal.slice(0, -1); // trim last character
  $("#demo").text(strVal);
 }
}

Striing with Commma,

<button onclick="myFunction()">Try it</button>

A: you can remove last comma:
var sentence = "I got,. commas, here,";
sentence = sentence.replace(/(.+),$/, '$1');
console.log(sentence);

A: function removeLastComma(str) {
   return str.replace(/,(\s+)?$/, '');
}

A: To remove the last comma from a string, you need
text.replace(/,(?=[^,]*$)/, '')
text.replace(/,(?![^,]*,)/, '')

See the regex demo. Details:

*

*,(?=[^,]*$) - a comma that is immediately followed with any zero or more chars other than a comma till end of string.

*,(?![^,]*,) - a comma that is not immediately followed with any zero or more chars other than a comma and then another comma.

See the JavaScript demo:

const text = '1,This is a test, and this is another,  ...';
console.log(text.replace(/,(?=[^,]*$)/, ''));
console.log(text.replace(/,(?![^,]*,)/, ''));

A: Remove whitespace and comma at the end use this,
var str = "Hello TecAdmin, ";
str = str.trim().replace(/,(?![^,]*,)/, '')
// Output
"Hello TecAdmin"

A: The problem is that you remove the last comma in the string, not the comma if it's the last thing in the string. So you should put an if to check if the last char is ',' and change it if it is.
EDIT: Is it really that confusing?
'This, is a random string'
Your code finds the last comma from the string and stores only 'This, ' because, the last comma is after 'This' not at the end of the string.

A: With or without Regex.
I suggest two processes and also consider removing space as well. Today I got this problem and I fixed this by writing the below code.
I hope this code will help others.

//With the help of Regex
var str = "        I am in Pakistan, I am in India, I am in Japan,     ";
var newstr = str.replace(/[, ]+$/, "").trim();
console.log(newstr);

//Without Regex
function removeSpaceAndLastComa(str) {
  var newstr = str.trim();
  var tabId = newstr.split(",");
  strAry = [];
  tabId.forEach(function(i, e) {
    if (i != "") {
      strAry.push(i);
    }
  })
  console.log(strAry.join(","));
}

removeSpaceAndLastComa(str);

A: If you are targeting es6, then you can simply do this
str = Array.from( str ).splice(0, str.length - 1).join('');

*

*This Array.from(str) converts the string to an array (so we can slice it)

*This splice( 0 , str.length - 1 ) returns an array with the items from the array sequentially except the last item in the array

*This  join('') joins the entries in the array to form a string
Then if you want to make sure that a comma actually ends the string before performing the operation, you can do something like this
str = str.endsWith(',') ? Array.from(str).splice(0,str.length - 1).join('') : str;


text:
Q: Red5 live streaming example using java I wanted to know is there any good documentation or example blog that shows how to use Red5 with Java. Is it possible to to live streaming from remote camera using `Red5' ? . Any links or documentations are helpful.
Live streaming use case is, Record video from camera and send to Red5 server. Red5 server can restream the feed live to web or save it in the network storage. For this usecase Red5 is good option ?
Thanks


text:
Q: pytest marks test as PASSED after an assertion error I am trying to write a test using pytest. I have a service which can register a listener with an event name and a callback function. For a period it generates data and invoke the callback passing it as an argument. Basically I need to evaluate some assertions inside the callback, but even if the assertion fails pytest says that test is passed.
def mytest():
    service = MyService()

    def on_data(data):
        assert False

    def on_end():
        print('All done')

    service.on('data', on_data)
    service.on('end', on_end)

    service.start()

When running this using pytest, I get:
ERROR assert False
Traceback [...]
    assert False
AssertionError: assert False

All done
PASSED

============================== 1 passed in 10.67s ==============================

Why is test marked as PASSED?


text:
Q: Compiler does not give error when using list initialization which will cause information loss In c++ primer(5th), it mentioned:

When used with variables of built-in type, this form of initialization
  has one
  important property: The compiler will not let us list initialize variables of built-in type if the initializer might lead to the loss
  of information:

longdouble ld = 3.1415926536;
int a{ld}, b = {ld}; // error: narrowing conversion required
int c(ld), d = ld;  // ok: but value will be truncate

I compile the code using gcc4.8.1 , it only give a warning rather than an error.
g++  -W -Wall -Wextra -pedantic -std=c++0x  -o m main.cpp

main.cpp: In function 'int main()':
main.cpp:64:13: warning: narrowing conversion of 'ld' from 'long double' to 'int' inside { } [-Wnarrowing]
     int a{ld}, b= {ld};
             ^
main.cpp:64:22: warning: narrowing conversion of 'ld' from 'long double' to 'int' inside { } [-Wnarrowing]
     int a{ld}, b= {ld};

Is there any flags that will turn on the feature of the important property ?

A: A quick search for "gcc diagnostic flag" turns up documentation resources.
Inside your program, you could do this:
#ifdef __GNUC__
#   pragma GCC diagnostic error "-Wnarrowing"
#endif

There is a command-line option too: -Werror=narrowing, but since you want to alter the semantic meaning of the program itself according to GCC, putting it in the source code is probably more appropriate.
Note, when it makes a difference other than simple well-formedness, such as in overload selection, GCC does diagnose the condition correctly.

A: The standard never calls for errors or for warnings: the standard only requires an implementation to issue a diagnostic. Whether such a diagnostic takes the form of a compiler error, or a warning, or something entirely different from them both, is outside the scope of the standard.


text:
Q: Jenkins: Github webhook does not trigger any job I try to configure Jenkins. I want a simple behavior: trigger a build on new pull request.
I cannot understand what I missed...
Jenkins version: 2.89.2
At https://ci.mysite.fr/configure :

Still no build triggered:

At https://ci.mysite.fr/job/test-back/configure :

On Github, Webhook is sent and well received by Jenkins:

Nginx Log says the same:

Help please!

A: Some things to check when debugging this sort of thing:

*

*Check your Jenkins logs to see whether or not Jenkins is receiving the hook and deciding not to take action for some reason.

*Check Jenkins security by clicking Manage Jenkins -> Configure Global Security.  Open things up as much as you're comfortable doing and see if that changes anything.

*Ensure that you're pushing changes to the master branch.  For simplification, consider using ** as your branch specifier while you're getting this to work.

*Ensure Git is properly configured on your Jenkins host by clicking Manage Jenkins -> Global Tool Configuration

*Make sure the user whose credentials you provided can manage hooks and pull from the repo you're interested in.

*Run the job manually in Jenkins, ensure that it works.

*After you run the job, it should show up as an option in Protected Branches/Required Statuses.  In your repo, click on Settings->Branches, select your branch in the Branches section, click Require Status Check to Pass before merging option, and your job should show up in the list which appears.

A: Webhooks are arguably the most difficult Jenkins feature to test without prior experience, because of gotchas like these (probably their list is incomplete):

*

*New git commit / git push must be made for each pipeline build  (repeating a previous one won't trigger a new build even if webhooks are already set up correctly - see below).

*First build made after setting up webhook correctly must be manual (no bootstrap from the webhook itself is possible).

*First build made after setting webhook correctly must succeed completely for the changes to take effect and for webhooks to start working. This will also cause Jenkins to miss all incoming requests made during the first build of a newly created pipeline.

More info

*

*Please be warned that it is not possible to trigger a build using the same build conditions again (at least using a webhook). Therefore you might have a correct webhook setup already, but not find out that it works unless you create a new git commit and push it to the remote repo on Github. If your try to repeat some old push over and over again, by simply pressing the "Redeliver" button in the Recent deliveries section on Github's Webhooks / Manage webhook page, Jenkins will never move beyond the "poke" repo stage, as it requires SCM changes to be detected in order to trigger a new build:

Received PushEvent for https://github.com/mirekphd/<REPO_NAME> from <GITHUB_IP> ⇒ <JENKINS_URL>/github-webhook/

Apr 16, 2021 9:42:12 PM INFO org.jenkinsci.plugins.github.webhook.subscriber.DefaultPushGHEventSubscriber$1 run
Poked <REPO_NAME>

Apr 16, 2021 9:42:13 PM INFO com.cloudbees.jenkins.GitHubPushTrigger$1 run
SCM changes detected in <REPO_NAME>. Triggering #236

For further info on points 2) and 3): see original source.


text:
Q: Adopt regular expression to mysql I made regular expression
^http[s]?:\/\/[^\/]*\.[a-z]+\/?$

which perfectly working
link
now i am moving it to mysql
REGEXP ('^http[s]?:\\/\\/[^\\/]*\\.[a-z]+\\/?$')

I had to escape forward slash twice (as i understand it mysql specs)
but still this expression catches much more than it suppose to
What is wrong ?
UPDATE
I did more tests and looks like this particular part not doing anything in Mysql
    REGEXP ('[^/]*')
I assume it suppose to filter out all urls NOT contains forward slash


text:
Q: Best approach to creating a database driven Java website? I'm fairly new to programming and new to java, but I'd like to jump in the deep end with a little database driven website project. I've read quite a lot about requirements in the 'real world' requesting experience with Spring and Hibernate, so I have those installed on netbeans and a project created (if I hit run I get the default spring page). Now I just need a little guidance as to where to start designing my app (please tell me if I'm getting in a bit too over my head for a beginner!).
Should I start off with my classes? - create all my classes as they map to my database tables and decide which attributes and methods each will require?
Can anyone suggest any good books for maybe.. making a java based website from scratch (i.e. from design right through to deployment) that might be useful for a beginner?
Any help appreciated thanks.
Edit: since posting this I've found a brilliant book that fits my needs just right to get started. Firstly I tried both spring in action and hibernate in action - but found both to be a bit too heavy for my novice mind. Instead I got the Java EE 5 Development with Netbeans 6 book https://www.packtpub.com/java-ee5-development-with-netbeans-6/book and its been a great help. If you use netbeans and are in a similar position to me, I'd say pick it up!

A: Too over your head?  Depends on what you hope to accomplish.  Are you trying to create a revenue-generating site to which users will be asked to trust credit card numbers and other sensitive information?  Then yeah, you're getting way ahead of yourself.  Is this a tool for personal use or a toy you're throwing together primarily as a learning experience?  Then I say "Pffffft!" to the notion of over-the-head-ness.  Go for it.
As to where to start, I say start with whatever portion of this beast is clearest to you.  Have a solid idea of what the database is going to look like?  Then start with it and its supporting classes.  Have a clear vision of what the guts of the code are supposed to do?  Start there.  Etc.  And if all things are equal, I'd say start at the bottom with the database layer and work your way up -- but that's just me.
And as for the books, can't help you there, but I'm sure somebody can.

A: I suggest to take a look at web application frameworks such as Spring's Roo or Grails.  Sadly I have no experience with Roo.  But I do have some experience with Grails.
With Grails you will be working mostly with Groovy, a language similar to Python, but still using the JVM.  You'll still have the option to use Java anywhere you like (I think). Grails (and maybe Roo too?) manages Spring and Hibernate for you.
As for books on Grails, I recommend "Grails in Action".  I have read a little of "Grails 1.1 Web Application Development" and it also seems to be a good reference.  BTW, netbeans supports Grails too.

A: Not trying to gut your goals, but if you are wondering whether to start with your classes, I would suggest you work on your programming skills more.
I'd suggest taking a look at Larman's "Applying UML & Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development (3rd Edition)" as well as a book on relational database theory (you need to know how to model databases properly.)
You can try your hand at building a database driven web app, and it might give you an insight into how to do it, but you need have some programming maturity to take those skills into the non-trivial.
This is a completely personal opinion so please take it with a grain of salt: Before someone tackles the building of a data-driven application with the purpose of eventually being able to use it in non-trivial projects, that person needs to have a good exposure to programming (by good I mean a LOT, say 1-2 introductory courses, 1-2 intermediate and at least one junior-level course, perhaps a total of 15-30 credits.) Unless that person is a natural programming virtuoso, I don't see it happening otherwise.
I would suggest, if you are serious about programming, to spend a substantial amount on learning the fundamentals before tackling something like this.
Good luck.


text:
Q: Splitting an Array into multiple chunks I'm looking to find a way to split an array into a set number of chunks. I've seen multiple posts on here which split it into chunks with a specified length, but that's not what I'm after. For example, consider the following array:
var array = ['1','2','3','4','5','6']
I would like to easily be able to pass this to a function such as the following
splitArray(array, 2)
Which would result in the following:
[[1,2,3], [4,5,6]]
Edit: As i mentioned, I wasnt to evenly split an array into a set number of chunks, not a number of chunks with a specified length as other questions ask


text:
Q: Python code not writing into file I have several text files in a folder, containing a list of names and adjectives. I have managed to create a script that takes random names, second names and such and creates a character from that data.
What I am using for that is the following code, which takes all the lines from the text file and places them in an array (This approach has worked well so far):
file=open("file_name","r")
array_name = []
for line in file:
    array_name.append( line.rstrip('\n') )

(Repeat this for every text file)

The sources I take that data from are often badly formatted (Everything in caps, nothing capitalised, etc), so I am trying to create another piece of code that capitalises every single word in all those text files. After extensive searching I've found that title() does exactly what I want to do, and I am trying to implement that approach using part of the previous code.
I am running into some trouble, especially because apparently I have created a piece of code that does what I want but does not actually write the changes to the file. Here is what I have done:
file=open("file_name","r+")
for line in file:
    line=line.title()
file.close

The idea is to open the file in read and write mode, read a line, change that line to the same line with title() applied and repeat until the end of the file.
Am I forgetting to add something? I have been trying things and thinking about it for some time now and I am not able to make this work. I am assuming the problem is in the line=line.title() line, but all my attempts have ended with the text files being empty or screwed up in some other way.

A: First, use a context manager, the with statement:
with open('file_name', 'r+') as my_file: # this automatically closes it
    lines = my_file.readlines()
    # now, rewrite the data
    for line in lines:
        my_file.write(line.title())

Edit: to completely rewrite the data, you have to use a 'w+' buffer mode (so first you can read it, than write over the original data) and also set the file pointer back to the beginning of the file:
with open('file_name', 'w+') as my_file:
    lines = my_file.readlines()
    # set the file pointer at the beginning of the file
    my_file.seek(0, 0)
    # now, rewrite the data
    for line in lines:
        my_file.write(line.title())

The previous issue (with my first example) is that once you have fully read the file, the file pointer is at the end of the file. Thus, you have to set it back to the beginning using the file.seek method.

A: def main():
    words = {}
    for whichfile in ['firstname', 'lastname', 'noun', 'adjective']:
        # read all words from file
        with open(whichfile + '.txt') as inf:
            words[whichfile] = [line.strip().title() for line in inf]

        # write capitalized words back to file
        with open(whichfile + '.txt', 'w') as outf:
            outf.write('\n'.join(words[whichfile]))

if __name__=="__main__":
    main()


text:
Q: Groupby operations on multiple columns Pyspark I have applied a groupby and calculating the standard deviation for two features in pyspark dataframe
from pyspark.sql import functions as f

val1 = [('a',20,100),('a',100,100),('a',50,100),('b',0,100),('b',0,100),('c',0,0),('c',0,50),('c',0,100),('c',0,20)]
cols = ['group','val1','val2']
tf = spark.createDataFrame(val1, cols)
tf.show()
tf.groupby('group').agg(f.stddev(['val1','val2']).alias('val1_std','val2_std'))

but it is giving me following error
TypeError: _() takes 1 positional argument but 2 were given

How to perform it in pyspark?

A: The problem is that the stddev function acts on a single column rather than multiple columns as in the code you have written (hence the error message about 1 vs 2 arguments). One way to get what you are looking for is to calculate the standard deviation separately for each column:
# std dev for each col
expressions = [f.stddev(col).alias('%s_std'%(col)) for col in ['val1','val2']]
# Now run it
tf.groupby('group').agg(*expressions).show()

#+-----+------------------+------------------+
#|group|          val1_std|          val2_std|
#+-----+------------------+------------------+
#|    c|               0.0|43.493294502332965|
#|    b|               0.0|               0.0|
#|    a|40.414518843273804|               0.0|
#+-----+------------------+------------------+