text:
Q: Convert black parts of an image to transparent parts by batch file Hi guys I'm an animator working with textures that some of them need to Convert black parts of an image to transparent parts and it's really boring to sit and all the day do it with photoshop can't I do it with a batch file?tnx.

A: Sure, use ImageMagick - it is free and available for Linux, OSX and Windows. The command you need is this:
convert image.png -transparent black result.png

and it turns into this:

If your blacks are not perfectly black, you can allow a fiddle factor like this:
convert image.png -fuzz 20% -transparent black result.png

If you want to apply that to all the PNG files in the current directory and save the results in a subdirectory called deblacked, you could do this:
mkdir deblacked
mogrify -path deblacked -transparent black *.png

Please try that on a COPY of your images first till you get the idea of it!

A: Another Way is to use these 2 commands :
PNG2HEX.EXE
This will decompose your image in one pixel (in Hexa value) per line.
Then you can parse the output file and replace each ALPHA CHANEL from FF TO 00 (000000FF to 00000000 for BLACK -> Transparent)
and then rebuild it with
HEX2PNG.EXE
These examples are in FRENCH but if you have some problem I can make you an example in English.
You can build you're own filters in BAT with these commands.
Sure the imageMagick solution is easier (the filter is already done !). But if you want to make your own filters (steganographic, gray level,...) It stay a very good solution.
Download : https://goo.gl/614NH8


text:
Q: Nginx not parsing PHP So I can't remember what I did, but for some reason I cannot get PHP to be parsed anymore. What would be the basic troubleshooting steps to check on this? I have php5 installed and nginx running but when I, for example, create a phpinfo page, the raw php is displayed on the website. I'd like to know how to really 'activate' php and make sure it can make a successful connection with nginx to serve up pages with php content. I am referring to a linux CLI environment, in case that was unclear.

A: nginx doesn't bundle itself with PHP support.  To "enable" PHP, you have to let your webserver know how to handle the packages.  This is where PHP-FPM comes in.
Using whatever package manager is appropriate for your OS, install FPM (e.g. apt-get install php5-fpm), give it a configuration file, then reload nginx.
Here's my /etc/nginx/nginx.conf to get you started:
user  nginx;
worker_processes  1;
pid        /var/run/nginx.pid;

events {
    worker_connections  768;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;
    access_log  /var/log/nginx/error.log  main;

    sendfile                on;
    tcp_nopush              on;
    tcp_nodelay             on;

    keepalive_timeout  10;
    types_hash_max_size 2048;
    server_tokens off;

    ssl_session_cache       shared:SSL:10m;
    ssl_session_timeout     10m;
    ssl_ciphers     HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

        open_file_cache          max=5000  inactive=20s;
        open_file_cache_valid    30s;
        open_file_cache_min_uses 2;
        open_file_cache_errors   on;

    #php cache
    #mkdir /var/cache/nginx; chown nginx:nginx /var/cache/nginx;
    #consider doing a tmpfs if memory allows - VPS disk speed is hardly robust
    fastcgi_cache_path /var/cache/nginx levels=1:2 keys_zone=microcache:10m max_size=1000m inactive=60m;

    #consider turning off if CPU thrashing
    gzip  on;
    gzip_static on;
    gzip_disable "msie6";
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_proxied any;
    gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;
    gzip_buffers 16 8k;

    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

A: nginx doesn't have built in support for PHP, as Apache does via mod_php.
To get PHP scripts running you should research the use of FPM.

A: You need to check you have all the relevant packages installed. It might be that you accidentally deleted something, or missed something.
Try cleaning up, and starting again.
Check out this link, it has the basic packages and set up required to get you started again

redpajama_set_name: RedPajamaStackExchange


text:
Q: problems with modules while importing custom functions I've created a Notebook with some custom functions to shorten my coding, mainly while plotting, but I have a problem with a custom function, while importing the ".py" file into another notebook.
Let's say I've created the "plots_custom_functions.py" file. Inside it I have such a function:
def get_label(TITLE, X, Y):
    '''
    this function appends the labels to a plot. Arguments in the following order:
    Title, x label, y label
    '''
    plt.title(TITLE)
    plt.xlabel(X)
    plt.ylabel(Y)
    plt.show

Now, I create another notebook and type:
import seaborn as sns
import matplotlib.pyplot as plt
import plots_custom_functions

then I want to create one plot like that:
sns.histplot(data=my_data, x='my_x')

get_label('MY_TITLE', 'MY_X)', 'MY_Y' )

but I get an error like that:
NameError: name 'plt' is not defined

Now, It seems like it can't load matplotlib.pyplot as plt somewhere.
I've tried to import it in the plots_custom_functions in different "positions" like at the beginning of the file and like inside the get_label() function I've created, but I still get the same error.
Where can the error be?
[EDIT: SOLVED]
I do not know why, but it works importing just one function at a time.
So, in my "plots_custom_functions.py" file I have:
import matplotlib.pyplot as plt

def get_label(TITLE, X, Y):
        '''
        this function appends the labels to a plot. Arguments in the following order:
        Title, x label, y label
        '''
        plt.title(TITLE)
        plt.xlabel(X)
        plt.ylabel(Y)
        plt.show

Then, when invoking my custom functions in another Notebook I have to type:
from plots_custom_functions import get_label

And it works. It's not handy, but it works.
So, to make it handy we can type this:
from plots_custom_functions import *

And this is one of the reasons why we have better not create "too many" custom functions in just one ".py" file.


text:
Q: Make a input be ahead of a paragraph I am creating a little effect with an input, but I am facing a problem.
I have an input and as a placeholder I am using a paragraph which I used translate to position inside the input.
What I am doing is when the input is focused the paragraph is moved up and when it is not focused it is put back in its original position, 'inside' the input.
Like this:

The problem is that in order to make the input focused I have to click on it, but the p is ahead of it, so, when I click on the text I don't reach the input, consequently it doesn't get focused and the p doesn't move.
Is there a way to send the p behind the input? I tried with z-index, but it seems that it doesn't work to inputs.
Is there anything similar that would work?

const placeholder = document.getElementsByClassName('frete-input-placeholder')[0].parentNode.children

const h2 = document.getElementById('h2')

window.addEventListener('click', () => {
    if (placeholder[1] === document.activeElement) {
        placeholder[0].style.transform = 'translate(0, 30px)'
      h2.innerHTML = 'FOCUSED'
    } else {
        placeholder[0].style.transform = 'translate(0, 55px)'
      h2.innerHTML = 'NOT FOCUSED'
    }
})
.frete-calculo-cep {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    width: 65%;
}

.frete-calculo-cep div {
    width: 62%;
}

.frete-input-placeholder {
    background-color: tomato;
    width: 20%;
    margin-left: 10px;

    transform: translate(0, 55px);
    transition: 0.5s;
}

.frete-calculo-cep input {
    max-width: 93%;
    height: 42px;
    outline: none;
    border:1px solid #BEBEBE;
    padding-left: 10px;
    font-size: 18px;
    z-index: 9999;

    border-radius: 3px;
}

.frete-calculo-cep input:focus {
    outline: none;
    border:1px solid #5A98FF;
}

.frete-calculo-cep button {
    width: 35%;
    height: 45px;
    background-color: #5F22A8;
    color: white;
    font-weight: bold;
    font-size: 17px;
    border: 0;
    cursor: pointer;

    border-radius: 3px;
}

.frete-calculo-cep button:hover {
    background-color: #7032bb;
}

.frete-calculo-cep button:focus {
    outline: 0;
}

Digite seu CEP

            <input type="text" />

NOT FOCUSED

A: Just set pointer-events:none; on the paragraph in CSS.
But also, document.getElementsByClassName()[0] is really, really not good code. Instead use document.querySelector as I've shown below.
And, instead of inline styles, always try to use CSS classes, which you can easily add, remove or toggle with element.classList.
Finally, don't use .innerHTML when there is no HTML in the string you are working with as .innerHTML has security and performance implications. Use textContent instead.

const placeholder = document.querySelector('.frete-input-placeholder');
const input = document.querySelector("input");

const h2 = document.getElementById('h2')

window.addEventListener('click', () => {
    if (input === document.activeElement) {
      placeholder.classList.add("focused");
      h2.textContent = 'FOCUSED'
    } else {
      placeholder.classList.remove("focused");
      h2.textContent = 'NOT FOCUSED'
    }
})
.frete-calculo-cep {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    width: 65%;
}

.frete-calculo-cep div {
    width: 62%;
}

.frete-input-placeholder {
    background-color: tomato;
    width: 20%;
    margin-left: 10px;

    transform: translate(0, 55px);
    transition: 0.5s;

    pointer-events:none;  /* <---- This is all you need  */
}

/* Use CSS Classes instead of inline CSS */
.focused { transform:translate(0, 30px); }

.frete-calculo-cep input {
    max-width: 93%;
    height: 42px;
    outline: none;
    border:1px solid #BEBEBE;
    padding-left: 10px;
    font-size: 18px;
    z-index: 9999;

    border-radius: 3px;
}

.frete-calculo-cep input:focus {
    outline: none;
    border:1px solid #5A98FF;
}

.frete-calculo-cep button {
    width: 35%;
    height: 45px;
    background-color: #5F22A8;
    color: white;
    font-weight: bold;
    font-size: 17px;
    border: 0;
    cursor: pointer;

    border-radius: 3px;
}

.frete-calculo-cep button:hover {
    background-color: #7032bb;
}

.frete-calculo-cep button:focus {
    outline: 0;
}

Digite seu CEP

            <input type="text" />

NOT FOCUSED

A: I just moved the p behind with position absolute

const placeholder = document.getElementsByClassName('frete-input-placeholder')[0].parentNode.children

const h2 = document.getElementById('h2')

window.addEventListener('click', () => {
    if (placeholder[1] === document.activeElement) {
        placeholder[0].style.transform = 'translate(0, 30px)'
      h2.innerHTML = 'FOCUSED'
    } else {
        placeholder[0].style.transform = 'translate(0, 55px)'
      h2.innerHTML = 'NOT FOCUSED'
    }
})
.frete-calculo-cep {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    width: 65%;
    margin-top: 50px;
}

.frete-calculo-cep div {
    width: 62%;
}

.frete-input-placeholder {
    background-color: tomato;
    width: 20%;
    margin-left: 10px;
    position: absolute;
    top: -20px;
    transform: translate(0, 55px);
    transition: 0.5s;
}

.frete-calculo-cep input {
    max-width: 93%;
    height: 42px;
    outline: none;
    border:1px solid #BEBEBE;
    padding-left: 10px;
    font-size: 18px;
    z-index: 9999;

    border-radius: 3px;
}

.frete-calculo-cep input:focus {
    outline: none;
    border:1px solid #5A98FF;
}

.frete-calculo-cep button {
    width: 35%;
    height: 45px;
    background-color: #5F22A8;
    color: white;
    font-weight: bold;
    font-size: 17px;
    border: 0;
    cursor: pointer;

    border-radius: 3px;
}

.frete-calculo-cep button:hover {
    background-color: #7032bb;
}

.frete-calculo-cep button:focus {
    outline: 0;
}

#input1 {
  position: relative;
}

Digite seu CEP

            <input type="text" id="input1" />

NOT FOCUSED


text:
Q: wp_enqueue_style for Plugin with multiple stylesheets I'm making a navigation plugin which adds animations to your wordpress navigation.
I read in Wordpress Codex that I would need to use wp_enqueue_style().
First, How do I use this code for multiple css files?
in my main plugin file.
Now according to this question, I would add stylesheets like this:
function add_my_stylesheet()
{
    wp_enqueue_style( 'myCSS', plugins_url( '/css/myCSS.css', __FILE__ ) );
}

add_action('admin_print_styles', 'add_my_stylesheet');

Since my plugin requires multiple stylesheets to be added, which of the two codes should I use?
function add_my_stylesheet()
{
    wp_enqueue_style( 'myCSS', plugins_url( '/css/myCSS.css', __FILE__ ) );
}

add_action('admin_print_styles', 'add_my_stylesheet');

function add_my_stylesheet1()
{
    wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS1.css', __FILE__ ) );
}

add_action('admin_print_styles', 'add_my_stylesheet1');

Or
function add_my_stylesheet1()
{
    wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS.css', __FILE__ ) );
    wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS1.css', __FILE__ ) );
}

add_action('admin_print_styles', 'add_my_stylesheet1');

Now I know where to add this code. But how do I call the stylesheet I want to use?
Also, just to clear what my plug would do:
The main plugin file would only load the stylesheet required.
And the options page would allow the user to select which of the stylesheet to require.
for example, in php format I would use the following:
<link href="nav-<?php echo $name; ?>.css">

The $name should be the one selected from the options page, but how do I call in the required stylesheet?
I hope my question is clear enough.

A: To answer your first question, you would use the second style, i.e.
function add_my_stylesheet()
{
    wp_enqueue_style( 'myCSS', plugins_url( '/css/myCSS.css', __FILE__ ) );
    wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS1.css', __FILE__ ) );
}

add_action('admin_print_styles', 'add_my_stylesheet');

What the add_action() function does is tell WordPress, "When the admin_print_styles action occurs, run this add_my_stylesheet() function." Confusingly, the practice of using the admin_print_styles and admin_enqueue_styles actions to enqueue stylesheets is incorrect - as counter-intuitive as it is, you should use admin_enqueue_scripts instead.
The calls to wp_enqueue_style() then add the specified stylesheets to a list of stylesheets that will be loaded (if you specify the dependencies argument, then WordPress will also take care of making sure that your stylesheets load in the correct order). You don't need to "call" an enqueued stylesheet as you suggested - if it is enqueued, then it will be printed out in an HTML <link ...> element in the <head></head> section in the same manner that WordPress loads it's own stylesheets.
In order to select which stylesheet will be loaded, you simply add your logic to your add_my_stylesheet() function; if you don't wish for a stylesheet to be used, then you don't enqueue it, i.e.:
function admincolorplugin_enqueue_styles()
{
    // Get the user's stylesheet choice from the options, default to "white"
    $stylesheet = get_option( 'admincolorplugin_stylesheet', 'white' );

    // Conditionally load the appropriate stylesheet
    if( $stylesheet == 'black' ) {
        wp_enqueue_style( 'admincolorplugin-black', plugins_url( '/css/black.css', __FILE__ ) );
    }
    else {
        wp_enqueue_style( 'admincolorplugin-white', plugins_url( '/css/white.css', __FILE__ ) );
    }
}

add_action('admin_enqueue_scripts', 'admincolorplugin_enqueue_styles' );

A: Use an if to check if it conforms to your criteria, for example

*

*a specific page/post (id)

*all pages/post

*related to the admin option.

That way it'll only pull the CSS that you want on the desired page / when the desired admin option is selected.
    function add_my_stylesheet1()
    {
        if(is_page(41)){
            wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS.css', __FILE__ ) );
        }else{
            wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS1.css', __FILE__ ) );
        }
    }

Or:
    function add_my_stylesheet1()
    {
        $adminopt = get_option( $option, $default );
        if($adminopt == "Normal CSS"){
            wp_enqueue_style( 'myCSS', plugins_url( '/css/myCSS.css', __FILE__ ) );
        }else{
            wp_enqueue_style( 'myCSS1', plugins_url( '/css/myCSS1.css', __FILE__ ) );
        }
    }

A: add_action( 'admin_enqueue_scripts', 'safely_add_stylesheet_to_admin' );

/** * Add stylesheet to the page*/
function safely_add_stylesheet_to_admin() {
    wp_enqueue_style( 'prefix-style', plugins_url('plugin_styles.css', __FILE__) );
    wp_enqueue_style( 'prefix-basic', plugins_url('/css/basic.css', __FILE__) );

}


text:
Q: Meaning of < > symbol in a mysql query I came across a mysql query which is
SELECT P.pid FROM Parts P WHERE P.color<> 'blue'

I dont understand the meaning of <> symbol in the query.I have never seen such a symbol in mysql.
And the query in which this subquery is embedded is
SELECT S.sname
    FROM Suppliers S
        WHERE S.sid NOT IN (SELECT C.sid
                            FROM Catalog C
                            WHERE C.pid NOT IN (SELECT P.pid
                                                FROM Parts P
                                                WHERE P.color<> 'blue'))

And the tables are as follows --
Suppliers(sid:integer, sname:string, city:string, street:string)
Parts(pid:integer, pname:string, color:string)
Catalog(sid:integer, pid:integer, cost:real)

Can someone explain the use of this symbol ?

A: It is the not equal operator. It is same as !=

A: It is 'not equal' some SQL versions it is '!=' instead of '<>'.


text:
Q: React Native - How to present an activity when getCurrentActivity() is not working I'm working on a project which integrates 3rd party SDK in it.
The SDK method needs my activity to be passed in.
I'm doing this...
processRegistration(getCurrentActivity(), someEncryptedString);
and I'm getting following error...
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@5b558ea
I'm using react-navigation and above code is called on 3rd screen(component). 2nd screen is 'replace'd 3rd
Can someone help to solve this?

A: This has been observed that in DEBUG mode you may face this issue.
To fix this, run it in RELEASE mode like follows.
react-native run-android --variant=release


text:
Q: missing "Edit Enterprise Library V5 Configuration" I installed Entlib 5 .
In existing WCF application, I see "edit wcf configuration"
But I don't see  "Edit Enterprise Library V5 Configuration"  -Any idea why it is missing?

A: Check Tools | Extension Manager whether the EntLib config tool is actually installed.
If not, you can install it from the Visual Studio Extension Gallery:
http://visualstudiogallery.msdn.microsoft.com/029292f0-6e66-424f-8381-3454c8222f9a
or search for 'entlib' from the Extension Manager.
Also, make sure the config file you are trying to do a right click on, actually has the <configuration> element. The config tool VSIX checks for that before lighting up.


text:
Q: How to compile a java source file which is encoded as "UTF-8"? I saved my Java source file specifying it's encoding type as UTF-8 (using Notepad, by default Notepad's encoding type is ANSI) and then I tried to compile it using:
javac -encoding "UTF-8" One.java

but it gave an error message"
One.java:1: illegal character: \65279

?public class One {

^
1 error

Is there any other way, I can compile this?
Here is the source:
public class One {
    public static void main( String[] args ){
        System.out.println("HI");
    }
}

A: Try javac -encoding UTF8 One.java
Without the quotes and it's UTF8, no dash.
See this forum thread for more links

A: See Below
For example we can discuss with an Program (Telugu words)
Program (UnicodeEx.java)
class UnicodeEx {
    public static void main(String[] args) {
        double ఎత్తు = 10;
        double వెడల్పు = 25;
        double దీర్ఘ_చతురస్ర_వైశాల్యం;
        System.out.println("The Value of Height = "+ఎత్తు+" and Width = "+వెడల్పు+"\n");
        దీర్ఘ_చతురస్ర_వైశాల్యం = ఎత్తు * వెడల్పు;
        System.out.println("Area of Rectangle = "+దీర్ఘ_చతురస్ర_వైశాల్యం);
    }
}

This is the Program while saving as "UnicodeEx.java" and change Encoding to "unicode"
**How to Compile**

javac -encoding "unicode" UnicodeEx.java

How to Execute

java UnicodeEx

The Value of Height = 10.0 and Width = 25.0
Area of Rectangle = 250.0

A: Your file is being read as UTF-8, otherwise a character with value "65279" could never appear. javac expects your source code to be in the platform default encoding, according to the javac documentation:

If -encoding is not specified, the platform default converter is used.

Decimal 65279 is hex FEFF, which is the Unicode Byte Order Mark (BOM).  It's unnecessary in UTF-8, because UTF-8 is always encoded as an octet stream and doesn't have endianness issues.
Notepad likes to stick in BOMs even when they're not necessary, but some programs don't like finding them.  As others have pointed out, Notepad is not a very good text editor.  Switching to a different text editor will almost certainly solve your problem.

A: I know this is a very old thread, but I was experiencing a similar problem with PHP instead of Java and Google took me here. I was writing PHP on Notepad++ (not plain Notepad) and noticed that an extra white line appeared every time I called an include file. Firebug showed that there was a 65279 character in those extra lines.
Actually both the main PHP file and the included files were encoded in UTF-8. However, Notepad++ has also an option to encode as "UTF-8 without BOM". This solved my problem.
Bottom line: UTF-8 encoding inserts here and there this extra BOM character unless you instruct your editor to use UTF8 without BOM.

A: Open the file in Notepad++ and select Encoding -> Convert to UTF-8 without BOM.

A: This isn't a problem with your text editor, it's a problem with javac !
The Unicode spec says BOM is optionnal in UTF-8, it doesn't say it's forbidden !
If a BOM can be there, then javac HAS to handle it, but it doesn't. Actually, using the BOM in UTF-8 files IS useful to distinguish an ANSI-coded file from an Unicode-coded file.
The proposed solution of removing the BOM is only a workaround and not the proper solution.
This bug report indicates that this "problem" will never be fixed : https://web.archive.org/web/20160506002035/http://bugs.java.com/view_bug.do?bug_id=4508058
Since this thread is in the top 2 google results for the "javac BOM" search, I'm leaving this here for future readers.

A: Works fine here, even edited in Notepad.  Moral of the story is, don't use Notepad.  There's likely a unprintable character in there that Notepad is either inserting or happily hiding from you.

A: I had the same problem. To solve it opened the file in a hex editor and found three "invisible" bytes at the beginning of the file. I removed them, and compilation worked.

A: *

*Open your file with WordPad or any other editor except Notepad.

*Select Save As type as Text Document - MS-DOS Format

*Reopen the Project

A: To extend the existing answers with a solution for Linux users:
To remove the BOM on all .java files at once, go to your source directory and execute
find -iregex '.*\.java' -type f -print0  | xargs -0 dos2unix
Requires find, xargs and dos2unix to be installed, which should be included in most distributions. The first statement finds all .java files in the current directory recursively, the second one converts each of them with the dos2unix tool, which is intended to convert line endings but also removes the BOM.
The line endings conversion should have no effect as it should already be in Linux \n format on Linux if you configure your version control correctly but be warned that it does that as well in case you have one of those rare cases where that is not intended.

A: In the Intellij Idea(Settings>Editor>File Encodings), the project encoding was "windows-1256". So I used the following code to convert static strings to utf8
protected String persianString(String persianStirng) throws UnsupportedEncodingException {
    return new String(persianStirng.getBytes("windows-1256"), "UTF-8");
}

Now It is OK!
Depending on the file encoding you should change "windows-1256" to a proper one


text:
Q: Use KeepSolid (VPN Unlimited) proxies from curl It seems KeepSolid's servers run Squid (https://89.45.7.90:3129), and that the Firefox plugin somehow authenticates, so that Firefox can use it.
I want to use curl with KeepSolid's servers (aka. VPN Unlimited).
(Analyticshub.link seems to be the CN of the TLS certificate).
$ curl -v --proxy https://analyticshub.link:3129 --proxy-digest --proxy-user $user:$pass --location https://www.google.com/

*   Trying 89.45.7.90:3129...
* TCP_NODELAY set
* Connected to analyticshub.link (89.45.7.90) port 3129 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: /etc/ssl/certs
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* TLSv1.3 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Change cipher spec (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server did not agree to a protocol
* Proxy certificate:
*  subject: CN=analyticshub.link
*  start date: Jul  5 08:11:25 2021 GMT
*  expire date: Oct  3 08:11:24 2021 GMT
*  subjectAltName: host "analyticshub.link" matched cert's "analyticshub.link"
*  issuer: C=US; O=Let's Encrypt; CN=R3
*  SSL certificate verify ok.
* allocate connect buffer!
* Establish HTTP proxy tunnel to www.google.com:443
* Proxy auth using Digest with user 'keepsolid.com@tange.dk'
> CONNECT www.google.com:443 HTTP/1.1
> Host: www.google.com:443
> User-Agent: curl/7.68.0
> Proxy-Connection: Keep-Alive
>
< HTTP/1.1 407 Proxy Authentication Required
< Server: squid/3.5.23
< Mime-Version: 1.0
< Date: Sun, 01 Aug 2021 19:02:51 GMT
< Content-Type: text/html;charset=utf-8
< Content-Length: 3557
< X-Squid-Error: ERR_CACHE_ACCESS_DENIED 0
< Vary: Accept-Language
< Content-Language: en
< Proxy-Authenticate: Basic realm="Web-Proxy"
< X-Cache: MISS from vpnunlimitedapp.com
< X-Cache-Lookup: NONE from vpnunlimitedapp.com:4129
< Connection: close
<
* Ignore 3557 bytes of response-body
* Received HTTP code 407 from proxy after CONNECT
* CONNECT phase completed!
* Closing connection 0
curl: (56) Received HTTP code 407 from proxy after CONNECT

As you can see the above does not work. What should I do instead?

A: This not a 100% answer in the slightest, but I tried to look into how the Firefox plugin works.
The short answer is that it seems to do good authentication using JWT to an authentication service (auth.simplexsolutionsinc.com) using tokens fetched from multiple cloud storage providers for redundancy/bypassing blocking, and returns then some temporary credentials that get used w/ the proxy.
You should be able to capture those short-term credentials and use them like you are right now, but they might not be simple user/pass, and might be something like OAuth2 bearer or a further layer or JWT on the proxy.
Also, thank you for writing GNU Parallel!


text:
Q: Find matrix representation of following linear transformation Consider subspace $V=span\{f_1,f_2\}$ of the complex vector space of complex valued functions with domain $\mathbb{R}$, where $f_1(x)=\cos x $ and $f_2(x)=\sin x$ for all $x \in \mathbb{R}$. $D: V \to V$ is a linear operator defines as the derivative $D(g)=g'$ for any function $g \in V$

*

*Find the matrix representation of D with respect to the ordered basis $\{f_1,f_2\}$

*Find the matrix representation of the vector $h$ with respect to the ordered basis $\{f_1,f_2\}$ where $h(x)=3e^{ix}-2e^{-ix}, \:$ for all $x \in \mathbb{R}$

*Calculate derivative of $h(x)=3e^{ix}-2e^{-ix}$ using the matrix representations you have found in parts 1 and 2.

This is an exercise in my book.
My thoughts:
For $1$:
$V=span(\cos x, \sin x)=a \cos x+b \sin x,$ for all $a,b \in \mathbb{C}$
So this gives:
$D(span(\cos x, \sin x))=D(a \cos x+b \sin x)=(a \cos x+b \sin x)'=- a\sin x + b \cos x = (- a)(\sin x) + (b )(\cos x ) = \begin{bmatrix} - a\\ b \end{bmatrix}$
I am not sure whether it is correct or not. If I could do first part this might give me some idea about part 2 and 3.
Thank you in advance for your help.

A: Your matrix isn't correct. Remember, if you're representing a linear transformation as a matrix, the columns of the matrix are the images of the basis vectors under the linear transformation. The derivative of the span is a vector - there's no reason that should be the correct matrix.
The correct approach here is to determine $D(\cos(x))$ as a vector $\begin{bmatrix} a \\ b \end{bmatrix}$, and $D(\sin(x))$ as a vector $\begin{bmatrix}c \\ d \end{bmatrix}$, then you have $D = \begin{pmatrix}a & c \\ b & d \end{pmatrix}$. This is the definition of representing the linear transformation as a matrix. Once you have that, for part (b) and (c), recall that $e^{ix} = \cos(x) + i\sin(x)$, and they should follow quickly.


text:
Q: Linking DNS to a consul node I'm trying to set up a consul agent using an example in "Using Docker" (chapter 11).  The example suggests running this to set up one of the consul nodes:
docker run -d --name consul -h consul-1 \
         -p 8300:8300 -p 8301:8301 -p 8301:8301/udp \
         -p 8302:8302/udp -p 8400:8400 -p 8500:8500 \
         -p 172.17.42.1:53:8600/udp \
         gliderlabs/consul agent -data-dir /data -server \
                    -client 0.0.0.0 \
                    -advertise $HOSTA -bootstrap-expect 2

I assume the line with -p 172.17.42.1:53:8600/upp  is linking the container's DNS service with the consul node using an IP address that worked for the author.  What IP address should I use here?

A: Looks like 172.17.42.1 was the default bridge address for docker 1.8 to use when a container is connecting to the host.  This changed in 1.9 and seems to be 172.17.0.1 for me -- although I don't know if this is a guaranteed.

A: You seem to be running an example setup, so better if you expose it to your localhost 127.0.0.1 instead. That's a DNS service, as long as you give a dig command using the correct port for DNS, it will just work. For example following will do for port 8600:
dig @127.0.0.1 -p 8600 stackoverflow.service.consul

; <<>> DiG 9.8.2rc1-RedHat-9.8.2-0.62.rc1.55.amzn1 <<>> @127.0.0.1 -p 53 tracker.service.consul
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 57167
;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; WARNING: recursion requested but not available

;; QUESTION SECTION:
;stackoverflow.service.consul.      IN  A

;; ANSWER SECTION:
stackoverflow.service.consul.   0   IN  A   10.X.X.X

;; Query time: 1 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Fri Jul  7 11:29:01 2017
;; MSG SIZE  rcvd: 56

If you want it to work on the default DNS port so that the queries can directly be handled. You can use something like dnsmaq or any of the methods listed at the following link for DNS forwarding:
https://www.consul.io/docs/guides/forwarding.html


text:
Q: Specify default @Bean without using @Primary Spring Boot have a bean like this:
@Bean
TemplateEngine myTemplateEngine() {...}

But Spring boot also has a bean for TemplateEngine defined in:

org/springframework/boot/autoconfigure/thymeleaf/ThymeleafAutoConfiguration$ThymeleafDefaultConfiguration.class

When I autowire TemplateEngine I get

"Field required a single bean, but 2 were found"

I want the spring boot bean to be the default one and only use my bean if explicity specified, so I couldn't use @Primary annotation because I don't have access to that bean definition.
Also, I would like to avoid using xml configuration as well.

A: Try to define your bean as
@Bean
@ConditionalOnMissingBean(TemplateEngine .class)
TemplateEngine myTemplateEngine() {...}


text:
Q: Magento / Mage: How to port from mage to magento v2? In magento v1.x, we use:
Mage::getVersion()

Mage::app()->getStores()

Mage::getModel('sales/order')->getCollection()

Mage::getSingleton('core/resource')->getConnection('core_read')

What are the equivalents in magento v2?
(And generally, how should we approach porting from mage to magento v2?)


text:
Q: MongooseJS save additional params I am using POST query to save data in my app. How can I add additional params to Item? I want to add something like user: req.user._id.
var Item = new Model(req.body);
    Item.save(function (err, model) {
        res.send(model);
    });

So my document will look like:
{
   param1: '1',
   param2: '2',
   user: ObjectID('blahblahblah')
}

From my form I got two params - param1 and param2. user parameter was added before saving the document.

A: Assuming what you mean is adding something additional that is not in the form, then it is just a JavaScript object so there is nothing wrong with this:
req.body.userId = "Me";

And now req.body contains your new property that you can pass into your other constructor or even directly save. Try it in a REPL or with console.log


text:
Q: Google CloudML job fails with "CreateSession still waiting for response from worker" It's intermittent and seemingly non-deterministic: the exact same job will sometimes work perfectly, sometimes it will stall and print dozens of these errors, then work, and sometimes it stalls for a long time, then dies.
Other StackOverflow users who have run into this say it's a bad Cluster config (typically wrong port #s), but we're not setting any cluster params, instead relying on tf.contrib.learn.Experiment to do all the distributed config.  Also if it were just a bad config, then it would either always work, or never work.
Full error looks like:

10:53:28.899 2017-10-20 17:53:28.899466: I tensorflow/core/distributed_runtime/master.cc:209] CreateSession still waiting for response from worker: /job:ps/replica:0/task:0


text:
Q: Browsershot / Puppeteer ENOTCONN error only when called from Laravel controller I have a Laravel project which attempts to execute this command from within a controller.
$filename = 'google.png';
$screenshot = Browsershot::url('http://google.com/')
    ->setNodeBinary('C:\PROGRA~1\nodejs\node.exe')
    ->setNodeModulePath('D:\Work\Project\node_modules')
    ->setOption('landscape', true)
    ->windowSize(3840, 2160)
    ->waitUntilNetworkIdle()
    ->save($filename);

When I serve the Laravel project (php artisan serve) the command Browsershot invokes with Process results in an error.
The process:
$ "C:\PROGRA~1\nodejs\node.exe" "D:\Work\Project\vendor\spatie\browsershot\src/../bin/browser.js" "{\"url\":\"http:\/\/google.com\",\"action\":\"screenshot\",\"options\":{\"type\":\"png\",\"path\":\"google.jpg\",\"args\":[\"--no-sandbox\"],\"viewport\":{\"width\":1920,\"height\":600},\"timeout\":120000,\"fullPage\":true}}"

Error

node:events:491
throw er; // Unhandled 'error' event
^
Error: read ENOTCONN
at tryReadStart (node:net:638:20)
at Socket._read (node:net:649:5)
at Socket.Readable.read (node:internal/streams/readable:487:10)
at Socket.read (node:net:705:39)
at new Socket (node:net:425:12)
at Object.Socket (node:net:295:41)
at createSocket (node:internal/child_process:328:14)
at ChildProcess.spawn (node:internal/child_process:445:23)
at Object.spawn (node:child_process:713:9)
at BrowserRunner.start (D:\Work\Project\node_modules\puppeteer\lib\cjs\puppeteer\node\BrowserRunner.js:121:34)
Emitted 'error' event on Interface instance at:
at Socket.onerror (node:readline:268:10)
at Socket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {   errno: -4053,   code:
'ENOTCONN',   syscall: 'read' }

If I run exactly that command from the command line, it works. If I take exactly that PHP block and put it in a normal php file and call with Apache, from the same directory with the same Composer vendor directory, it works:
test.php
    $filename = 'google.png';
    $screenshot = Browsershot::url('http://google.com/')
        ->setNodeBinary('C:\PROGRA~1\nodejs\node.exe')
        ->setNodeModulePath('D:\Work\Project\node_modules')
        ->setOption('landscape', true)
        ->windowSize(3840, 2160)
        ->waitUntilNetworkIdle()
        ->save($filename);

So it seems like a problem not with Browsershot or Puppeteer directly but some combination of them and Laravel / the Laravel server. Does anyone have any ideas?


text:
Q: Packages/libraries to build a Laravel 5 REST API I'm going to build a back-end API REST using Laravel 5 for an iOS application (perhaps for Android in the future) so I found a couple of packages on github for the API authentication:

*

*https://github.com/chrisbjr/api-guard

*https://github.com/lucadegasperi/oauth2-server-laravel
And I want to know what's the different between them and what package could be the good choice for my API and of course If you have some advices or another packages to use, will be perfect.
Kind regards.

A: The oAuth2 server package follows rfc6749 and will help you have an Auth server like fb. (please see the link I provided for more information)
You may use a second app for it to separate your servers. (Auth server - resource server)
I never used api-guard but as it says in read me, It will provide a basic api key protection.
If you are planning to share your api with third party apps with user permission, I advice you to follow the oAuth2 path.
But if you are planning to use it in your app only, you definitely need api key only. Don't spend time for oAuth2 configurations.


text:
Q: Update permalinks after domain change I installed my blog in a free hosting webpage, the hosting gave me a free domain and I used that domain in my blog, then I did buy a .net domain, I changed the URL in Settings->General of my dashboard.
I usually edit old posts, the problem is when a reader enters in the blog with the old free domain he gets the old version of my post, when the reader enters with my .net post he gets the modified version
I tried fixing the problem renaming all the link in my database, but it didn't work.
How can I fix this?

A: Option A: Here's a Quick Way to Search and Replace Your WordPress Database
Option B: Export your database using phpmyadmin and open in a text editor such as (Notepad++), and use search/replace to find old domain and replace with new domain.
MAKE SURE YOU BACKUP YOUR DATABASE BEFORE TAKING ANY ACTION


text:
Q: Yii1 search() by many-many relation returns only one related model I have 3 tables:
clients, traders and client_trader_relation
clients can have many traders, and traders can have many clients so this is a MANY-MANY relationship with a "pivot" table. The relation is defined in clients model like this:
$relations = array(
        'traders' => array(self::MANY_MANY, 'traders', 'client_trader_relation(client_id, trader_id)'),
);

Now everything works correctly when displaying a listing of all clients in let's say CGridView, but I also want to be able to  search for clients by a specific trader (so if one of the traders is let's say id 10, then return this client).
I have done it like this in model's search() function:
public function search()
{
    $criteria=new CDbCriteria;

    $criteria->with = 'traders';
    $criteria->together = true;
    $criteria->compare('traders.id', $this->search_trader);
}

search_trader is an additional variable added to the model & rules so it cna be used for searching.
While this works, it successfully returns all clients of specified trader, the result doesn't contain any other related traders, just the one I'm searching for. I can understand this behaviour, because that's the way the generated SQL works.
I'm curious though if there is any way to return all the traders from such search without having to make any additional queries/functions? If not, then what would be the correct way of doing such thing? As for now, I can only think of some function in the model like getAllTraders() that would manually query all the traders related to current client. That would work, I could use this function for displaying the list of traders, but it would produce additional query and additional code.

A: You can use this to disable eager loading:
$this->with(['traders' => ['select' => false]]);

But this will create separate query for each row, so with 20 clients in GridView you will get extra 20 queries. AFAIK there is no clean and easy way to do this efficiently. The easiest workaround is to define additional relation which will be used to get unfiltered traders using eager loading:
public function relations() {
    return [
        'traders' => [self::MANY_MANY, 'traders', 'client_trader_relation(client_id, trader_id)'],
        'traders2' => [self::MANY_MANY, 'traders', 'client_trader_relation(client_id, trader_id)'],
    ];
}

And then define with settings for eager loading:
$this->with([
    'traders' => ['select' => false],
    'traders2',
]);

Then you can use $client->traders2 to get full list of traders.

You can also define this relation ad-hoc instead of in relations():
$this->getMetaData()->addRelation(
    'traders2',
    [self::MANY_MANY, 'traders', 'client_trader_relation(client_id, trader_id)']
);


text:
Q: Cross compile for arm& linux on windows machine I need to cross build application in Windows for ARM and Linux machine.
Suprsingly, I didn't find a toolchain for windows,
Is there such a toolchain or did I miss somthing in my understanding ?
Thank you,
ranran

A: Here https://www.linaro.org/downloads/
scroll down to "Latest Linux Targeted Binary Toolchain Releases"


text:
Q: Unable to read environment variables outside a function in go with os.Getenv("KEY") I am a newbie to go, while using sling to make api calls to an external service
when I do
var api = sling.New().Base(os.Getenv("BASE_URL"))
the value comes as ""
but when I do the same in a function to debug
var api = sling.New().Base(os.Getenv("BASE_URL")) // raw url is blank
var api2=os.Getenv("BASE_URL")
type Params struct{
//params defined
}

func GetInfo(){

//params set

log.debug("base url:",os.Getenv("BASE_URL")) // prints "www.example.com/" as set in .env file
log.debug("base url from outside the function :",api2) //also empty
    if _, err := api.New().Get("trailingURL/rest").QueryStruct(params).ReceiveSuccess(response); err != nil || !response.Successful() {

        return false
    } // fails as base url is not set

}

where am I going wrong?

A: There's no difference where os.Getenv is called. In this basic example:
package main

import (
    "fmt"
    "os"
)

var v = os.Getenv("FOO")

func GetInfo() {
    fmt.Println(os.Getenv("FOO"))
}

func main() {
    fmt.Println(v)
    GetInfo()
}

If you run it with FOO=42 <program>, then it will print 42 twice.

In your code I'd say the difference is that the global initialization calls sling.New().Base while the function doesn't. If I was debugging this, that's where I'd be looking for a difference.
Start by adding an api2 global alongside api:
var api = sling.New().Base(os.Getenv("BASE_URL"))
var api2 = os.Getenv("BASE_URL")

And then printing/logging the value of both, and see what you get.


text:
Q: Java Timer Memory Leak I'm experiencing what I think is a memory leak, but I can't really explain it.
I have a Class, in which can start a task.
public class TestSingleton {

   void start(){
      var task = new ScheduledTask();
      task.run();
   }

   static void setNextRequest(Date date){
      var task = new ScheduledTask();
      if(date != null){
         var timer = new Timer();
         timer.schedule(task, date);
      }else{
         task.run();
      }

   }

}

public class ScheduledTSLUpdate extends TimerTask {

   @Override
   public void run(){
      String request = "http://localhost:2374";

      HttpClient httpClient = HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_2)
                .build();

      HttpRequest httpRequest = HttpRequest.newBuilder()
             .GET()
             .uri(URI.create(request))
             .headers(
                  "Authorization",
                  "Bearer " + Configuration.config.getProperty("JWTTOKEN"))
             .build();
      HttpResponse<String> response = httpClient.send(httpRequest,   HttpResponse.BodyHandlers.ofByteArray());

      ResponseEntity responseEntity = new Gson().fromJson(response, ResponseEntity.class);

      TestClass.setNextRequest(responseEntity.date);
   }

}

Apparently, when I call start(), I get a memory leak, and eventually an OutOfMemoryError: Java Heap Space. In theory, the Timer and ScheduledTask Objects should be garbage collected after execution(?).
Please help me, I'm really at a loss here.
Edit:
Screenshot showing the Exception (I used GSON for deserialization)

A: Each time you run the task, it spawns a new task recursively, so obviously it will not stop until you run out of memory.
If you want to repeat a task, see Timer.scheduleAtFixedRate


text:
Q: Setting height, and width of a relative layout in android Here is my scenario.
I have an image which is made as per resolution 320*480 (assuming i am using mdpi mobile). I am adding this image as a background to a relative layout.
Now my screen has three main things.
1- Title bar (The standard title bar of android)
2- My relative layout and its sub view image relative layout which is matched parent.
3- My menu bar at the bottom.

Now since my image is getting stretched in between menu bar and title bar. I want to make it fit the screen. Below is the code I am using.
    mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            public void onGlobalLayout()
        {
           if (notCreated == true)
           {
               notCreated = false;
           }
           else
           {
               mnHeight = mainLayout.getHeight();
               Rect rect = getRawCoordinatesRect(mainLayout);
               h = getWindowManager().getDefaultDisplay().getHeight() -
                       - rect.top - mainLayout.getHeight();
// rect.top to remove android standard title bar

               RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(image.getWidth(),LayoutParams.MATCH_PARENT);
               params.topMargin = -1 * rect.top;
               params.bottomMargin = -1 * h;
               image.setLayoutParams(params);

       }
    }

});

Now this is not working. A little help would be appreciated.
Note: Actually  I just want to stretch my image relative layout to 320*480. Right now it is sandwitched between title bar and my menu bar. E.g right now its dimensions are 320*400

A: Not sure if it will help, but try to play with setScaleType() trying different options.
image.setScaleType(ScaleType.FIT_CENTER);

Here are listed all the constans the ScaleType class has.

A: I must be honest and say i'm not completely sure what you want to do here. But i'm going to assume that you want to make the image function as a background..
If that's what you want, you can do this simply by setting the android:background="@drawable/your_image" attribute on the main layout in your layout file.
If what you want is remove the titlebar, this is done pretty simple by adding this line to your onCreate method in your activity class:
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);

If what you want to do is remove the notificationbar, this is also done in the onCreate method in your activity class:
//Remove notification bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

I hope this can help you :-) If it's not what you're looking for, then dont hesitate from trying to reformulate what you want.


text:
Q: biblatex: comma between author and year in bibliography when using ext-authoryear style with introcite=label I am using biblatex-ext with introcite=label to get a citation style like shown in the following question:
Creating a bibliography with fixed indention and authoryear labels using biblatex and biber
This gives me labels with a space between author and year both in the label and the bibliography. However, I am required to have a space between author and year in the label and a comma between author and year in the bibliography entry. So I need something like that:
Tietze et al. 2012    Tietze, Ulrich; Schenk, Christoph, 2012.
                      Halbleiterschaltungstechnik. ...

Note that I used the following solution to remove the parentheses around the year: biblatex: How to remove the parentheses around the year in authoryear style?
While searching for a solution, I found
\renewcommand*{\nameyeardelim}{\addcomma\space}

but this only works for the label making the above entry
Tietze et al., 2012    Tietze, Ulrich; Schenk, Christoph 2012.
                      Halbleiterschaltungstechnik. ...

This is the opposite of what I need. I need a space between author and year in the label and a comma in the bibliography entry.

A: As mentioned by David Purton in the comments, nameyeardelim is a context-sensitive delimiter. This means that you can give it different definitions for the bibliography and citations. The introcite label has the context bbx@introcite, which is different from the context bib for the rest of the bibliography, so we can use different values for nameyeardelim here.
The default nameyeardelim for all contexts is \addspace, so we only need to change the delimiter for the bib context to a comma followed by a space.
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[british]{babel}
\usepackage{csquotes}
\usepackage[style=ext-authoryear, backend=biber, introcite=label, dashed=false]{biblatex}
\addbibresource{biblatex-examples.bib}

\setlength{\bibitemsep}{0.5\baselineskip plus 0.5\baselineskip}
\setlength{\introcitewidth}{6em}

\DeclareDelimFormat[bib]{nameyeardelim}{\addcomma\space}

\DeclareFieldFormat{biblabeldate}{#1}

\begin{document}
\cite{sigfridsson,worman,geer,knuth:ct:a}
\printbibliography
\end{document}


text:
Q: Adding attributes with jquery I'm trying to add an attribute to an element. Basically, I want the jquery code to change it from this:

X

To this:

X

Here's the demo of what I tried adding above the  tag:

http://jsfiddle.net/qhu68qk9/
What I'm trying to say though it's that normally I should add the attribute 'data-position = "100, 100" ' by myself (I'm using FractionSlider, so this would position the element inside the slider). However I want the element to be centered, so I thought using jquery to get the position would help.

A: $(this.parent()) throws an error: this.parent is not a function. You should use $(this).parent() as jQuery selector.

A: How about breaking out your code into some helpers.
var ypos = function(el) {
   var $el = $(el)
   var h = ($el.parent().height() - $el.outerHeight())/2;
   var offset = $el.parent().scrollTop();
   return h + offset;
}
var xpos = function(el) {
   var $el = $(el)
   var w = ($el.parent().width() - $el.outerWidth())/2;
   var offset = $el.parent().scrollLeft();
   return w + offset;
}

var $slider = $('.slider-price');

console.log(xpos($slider));
console.log(ypos($slider));

var x = xpos($slider);
var y = ypos($slider);
$slider.data('position', {x:x, y:y});

// or
$slider.data('position', x + ', ' + y);

A: There are a few issues on your snippet.

*

*You are not loading jQuery library so you cannot select a DOM element(such as p.slider-price) like $("p.slider-price"). To fix that, you should load the jQuery library (in fiddle you do that by choosing it from the frameworks & extensions menu).
Than, using jQuery you will be able to change the attributes, for example:

$("p.slider-price").attr('data-position', "2");

*You have some issues on trying to calculate the attrbt (mainly because you should first understand what this and parent means).
In your case, you are assuming that parent is the parent DOM element of your p element, but javascript or jQuery doesn't understand that.
So, first you select(and/or save) your p element, than you would be able to get its parent and than you could calculate different values.

Combining all what I explained, you will get this fiddle which does what you are expecting:
http://jsfiddle.net/p62qyvax/4/


text:
Q: Capifony php error I in the past weeks I have a problem with capifony... So I have made the deploy.rb and it was not a problem:
set :application, "Infinity"
set :domain,      "xxx"
set :deploy_to,   "/var/www/inf.sitetester.biz"
set :app_path,    "app"

set :repository,  "D:/work/test.inf.serv"
set :scm,         :git
# Or: `accurev`, `bzr`, `cvs`, `darcs`, `subversion`, `mercurial`, `perforce`, or `none`
set   :deploy_via,    :copy
set :model_manager, "doctrine"
# Or: `propel`

role :web,        domain                         # Your HTTP server,    Apache/etc
role :app,        domain, :primary => true       # This may be the same as your `Web` server

set  :keep_releases,  3
ssh_options[:port] = "xx"
set :user, "xxx"
set :use_composer, false

After this I have made:
cap deploy:setup

And after the setup
cap deploy

Here is the output

I cannot understand why the cache warmup is generating those kind of errors. Is someone familiar with this?


text:
Q: Template, statics and dll I am trying to export a function template with a static variable in the definition.
.dll/Foo.h:
#ifdef _DLL
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

class API Foo
{
  public:
  template<typename T>
  static T& Get()
  {
    static T _instance;
    return _instance;
  }

  static void Set();
}

I want the calls made by the .dll and .exe to refer to the same "_instance" object. I know I can do that by defining the static variable in the .cpp. But in this case i am dealing with templates so i am kind of stuck.
Edit:
Example of what is happening..
.dll/Foo.cpp:
void Foo::Set()
{
   Foo::Get<int>() = 10;
}

.exe/main.cpp:
int main()
{
  auto & x = Foo::Get<int>();
  x = 3;
  std::cout << x; // 3
  Foo::Set();
  std::cout << x; // 3 (I want it to be 10)
}

A: you need separate mark every template with API (__declspec(dllexport) or __declspec(dllimport)) and not inline it in class code.
Foo.h file is:
#ifdef _DLL
#define API __declspec(dllexport)
#else
#define API __declspec(dllimport)
#endif

class API Foo
{
public:
    template<typename T>
    API static T& Get();

    static void Set();
};

note that we separate mark Get() with API despite all Foo class also marked with API (class mark have no effect on template function by fact, so need it mark separate). and no implementation of Get here - exported functions anyway can not be inline.
so dll code (Foo.cpp) must look like:
#include "foo.h"

template<typename T>
API T& Foo::Get()
{
    __pragma(message("__imp_" __FUNCDNAME__)) // for debug
    static T _instance;
    return _instance;
}

void Foo::Set()
{
    Foo::Get<int>() = 10;
}

note we again explicitly use API (__declspec(dllexport)) in implementation of function body. this is critical important - compiler not warning you, if you skip API here, but without this - Get will be not exported.
for sure that at this point all correct - copy string produced by __pragma(message("__imp_" __FUNCDNAME__)) (it will be look like __imp_??$Get@H@Foo@@SAAEAHXZ) and search exactly (symbol to symbol) this string in created .lib file - after you build dll. if it exist - all ok, otherwise no sense continue (with exe)
and in exe :
#include "../foo_dll/foo.h"

Foo::Get<int>() = 3;
Foo::Set();
if (Foo::Get<int>() != 10)
{
    __debugbreak();
}


text:
Q: Write pandas data as html format inside a Html.Div I am web scraping a html table, i am able to read the table, now i just need to write back in my page.
So i need return it inside a html.Div() and see it as a real table
def table():
URL = "https://www.infrontanalytics.com/fe-en/BMG5876H1051/Marvell-Technology-Group-Ltd-/beta"
        tables = pd.read_html(URL)
        print("There are : ",len(tables)," tables")
        print("Take look at table 0")
        print(tables[7])
        htmlout = html.Div(tables[7].to_html())
        return htmlout

The result i see on the web-page is the written table with the tags, but i need the visual table:

 	 Company Name	 Ctry	 MarketCap.last (mUSD)	 Beta1-Year	 Year-To-DatePrice Change(in local currency)

 0	 Marvell Technology Grou...	 BMU	 29 073	 1.40	 63.3%

 1	 International Peers Median	 International Peers Median	 International Peers Median	 1.26	 42.1%

 2	 NXP Semiconductors NV	 NLD	 45 876	 1.26	 28.9%

 3	 Silicon Motion Technolo...	 CYM	 1 561	 0.94	 -12.4%

 4	 QUALCOMM Inc.	 USA	 178 268	 1.20	 78.6%

 5	 STMicroelectronics NV	 NLD	 36 873	 1.48	 42.1%

 6	 NVIDIA Corp.	 USA	 335 702	 1.36	 130.5%

How can I transform the tags i got from pandas in html format to return it in a html page?
I used the to_html() function but it doesn't work as i expected.

A: For security reasons you can't insert raw HTML into dash elements. You options are either to convert your dataframe manually into an html.Table element, containing html.Tr, html.Td etc., or – much better – use the Dash DataTable component.
In your case this would look something like this:
def table():
    URL = "https://www.infrontanalytics.com/fe-en/BMG5876H1051/Marvell-Technology-Group-Ltd-/beta"
    tables = pd.read_html(URL)
    print("There are : ",len(tables)," tables")
    print("Take look at table 0")
    print(tables[7])
    df = tables[7]
    htmlout = html.Div(dash_table.DataTable(
        id='table',
        columns=[{"name": i, "id": i} for i in df.columns],
        data=df.to_dict('records'),
    ))
    return htmlout

Don't forget to import:
import dash_table


text:
Q: How to create an empty, coloured CGImage canvas in Swift I want to draw some lines over an empty CGImage black canvas. Should be something trivial creating a blank CGImage of an specific size but I'm not able. I've tried to extend CGImage init? calling self.init(width:height:...bitmapInfo:provider:...) with the required information but I don't know enough about CGBitmapInfo and CGDataProvider.
Any help or guidance on how to create this empty canvas? Any other approach not using UIKit?
Thanks!

A: You don't draw on a CGImage, you draw on a CGContext.  What you want to do is create a bitmap context, draw into the bitmap context, then create an image from the context bitmap buffer.  Here is a sample that I typed up in a Playground.
import UIKit
// CGContexts like rowbytes that are multiples of 16.
func goodBytesPerRow(_ width: Int) -> Int {
    return (((width * 4) + 15) / 16) * 16
}

func drawMyImage() -> CGImage? {
    let bounds = CGRect(x: 0, y:0, width: 200, height: 200)
    let intWidth = Int(ceil(bounds.width))
    let intHeight = Int(ceil(bounds.height))
    let bitmapContext = CGContext(data: nil,
                                  width: intWidth, height: intHeight,
                                  bitsPerComponent: 8,
                                  bytesPerRow: goodBytesPerRow(intWidth),
                                  space: CGColorSpace(name: CGColorSpace.sRGB)!,
                                  bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)

    if let cgContext = bitmapContext {
        cgContext.saveGState()
        cgContext.setFillColor(gray: 0, alpha: 1.0)
        cgContext.fill(bounds)

        /* ... do other drawing here ... */

        cgContext.restoreGState()

        return cgContext.makeImage()
    }

    return nil
}

let image = drawMyImage()

This is drawing using 32 bit ARGB values.
Core Graphics likes it best when its row bytes is a mutiple of 16 (or at least it did in 2006 when I wrote a Quartz 2D book).  So goodBytesPerRow calculates, for 32-bit ARGB pixels, a rowBytes that is a multiple of 16 for a given width.
The "bitmapInfo" is a combination of constants and determines more specifics of the pixel format CGImageAlphaInfo and CGBitmapInfo.  In this case we're saying we want the alpha channel to be first (so ARGB instead of RGBA) and we want to use pixels where the color channels are premultiplied by the alpha values.
Once you have the bitmap context you can draw what you like.  You said you wanted to draw some lines on a black background - so this just gives you the black background and leaves the lines as an exercise for the reader.
At the very end you get a CGImage from the context using makeImage.  If you wanted a UIImage, you could construct one with UIImage(cgImage:)
P.S.  You would use CGImageProvider if you wanted to construct an image from a raw chunk of memory, or by streaming data out of a file, or some other source.  It basically tells the system how to get the image data.
In this case, when we create the bitmap context, we pass in "nil" as the data which asks the OS to allocate the frame buffer for the image for us.


text:
Q: Jquery: get link by class or selector I'm creating a list of images from a folder, and then I open them in a fancybox... so I have thumnails, big images, and a text link to full image.

<a href="images/download/folder/big/<?php echo $file;?>" class="fancybox"><img src="<?php echo $path;?><?php echo $file?>" />

<a href="images/download/folder/full/<?php echo $file;?>.zip" class="btn-download">DOWNLOAD

Then I'm getting images path by jquery, for each image:
var download_image = jQuery('#download_image');
var images  = download_image.find('img');

download_images.each(function(){
    var img = jQuery(this);
    var img_source = img.attr('src');

Now I need to get the url of the "btn-download" link for each image... but I don't know which selector must I use! Any advice?

A: Use $('.btn-download') to select an element by class.
If you want to get the href attribute then simply use:
var href = $('.btn-download').attr('href');

To loop through each element use:
$('.btn-download').each(function(){
    var href = $(this).attr('href');
    // do something with href
})

A: Try this
$('a[class=btn-download]').attr('href')

A: $('.btn-download').each(function() {
  console.log(this.href); // get the normalized `href` property; fastest solution
  console.log($(this).attr('href')); // get the exact `href` attribute value
});

Note that the answers advocating $('.btn-download').attr('href') are incorrect, as those would only return the href attribute value for the first element in the set.

A: var download_image = jQuery('#download_image');

download_image.each(function() {
    var imgUrl = $(this).find('p > a > img').prop('src');
    var downloadUrl = $(this).find('p > a.btn-download').prop('href');
    // do something with the urls here.
});

Sample
The each-function is kind of redundant, because you should only have one element with a specific id. Listed here just in case you want to have more than one download image and button.
In your question you mention that you are getting the path for each image. I strongly advise you to make download_image a class if you have more than one download_image element.

A: Try this:
$('#download_image').each(function(){
    var img_source = $('img', this).attr('src');
    var link_href = $('a.btn-download', this).attr('href');
});


text:
Q: How to change Vim window moving key combinations? I found this :help window-move-cursor, but I tried to call it from the command line and doesn't work.
Is there a way to change the key mapping for switch windows?

A: To add to the Ingo's answer here is a set of config that allows you to move to other panes using Control and a movement key.
nnoremap <C-h> <C-w>h
nnoremap <C-j> <C-w>j
nnoremap <C-k> <C-w>k
nnoremap <C-l> <C-w>l

A: You can invoke any normal mode mappings via :normal!. The <C-w> used by the window movements is a challenge; you need :execute to evaluate the :help key-notation:
:execute "normal! \<C-w>j"`

However, there's the special :wincmd that simplifies the invocation; the above example becomes
:wincmd j

Now, if you want to change the key mappings, that can be done via :map:
:nnoremap <F7> <C-w>j

A: The following works, it's an example in the help for the 'normal' command:
:exe "normal \<c-w>\<c-w>"


text:
Q: latest appengine-gcs-client lib produces GCS Java API deprecation warning The GCS files api is turned down on July 28th, 2015.
In my development server I got the following warning:

The Google Cloud Storage Java API is deprecated and will soon be removed. Please use the Google Cloud Storage Client library instead. Migration documentation is available here: https://cloud.google.com/appengine/docs/java/googlecloudstorageclient/migrate

I have downloaded the latest version of the appengine-gcs-client from the git repository referenced in the official migration documentation. But I still got the warning in my dev server.
I checked all my dependencies but it seems that the only reference to the files api is located inside the appengine-gcs-client library itself. It is used in LocalRawGcsService.java (which I think is used in the dev server only).
As I have not seen a deprecation warning in my productive logs I think I do not have a problem, but I seriously wonder why they annoy me with that warning.

*

*Am I missing something important?

*Will I be able to use the appengine-gcs-client library in my productive environment and/or in my dev server after they have turned down the service?

A: If you're not using com.google.appengine.api.files.FileService, you don't need to worry. You're correct to note that this is still apparently used by that local class in the GCS client libary. There's a currently-open issue on the github project to get that addressed.
So, feel free to ignore that warning.

A: Just for completeness: Beginning with Google App Engine Java SDK 1.9.28 the files api is disabled in the development server.
In Version 0.5+ of the appengine-gcs-client library the files api was replaced. The library now works fine. It could be downloaded here: http://mvnrepository.com/artifact/com.google.appengine.tools/appengine-gcs-client


text:
Q: Clever way to append 's' for plural form in .Net (syntactic sugar) I want to be able to type something like:
Console.WriteLine("You have {0:life/lives} left.", player.Lives);

instead of
Console.WriteLine("You have {0} {1} left.", player.Lives, player.Lives == 1 ? "life" : "lives");

so that for player.Lives == 1 the output would be: You have 1 life left.
for player.Lives != 1 : You have 5 lives left.
or
Console.WriteLine("{0:day[s]} till doomsday.", tillDoomsdayTimeSpan);

Some systems have that built-in. How close can I get to that notation in C#?
EDIT: Yes, I am specifically looking for syntactic sugar, and not a method to determine what singular/plural forms are.

A: You may checkout the PluralizationService class which is part of the .NET 4.0 framework:
string lives = "life";
if (player.Lives != 1)
{
    lives = PluralizationService
        .CreateService(new CultureInfo("en-US"))
        .Pluralize(lives);
}
Console.WriteLine("You have {0} {1} left", player.Lives, lives);

It is worth noting that only English is supported for the moment. Warning, this don't work on the Net Framework 4.0 Client Profile!
You could also write an extension method:
public static string Pluralize(this string value, int count)
{
    if (count == 1)
    {
        return value;
    }
    return PluralizationService
        .CreateService(new CultureInfo("en-US"))
        .Pluralize(value);
}

And then:
Console.WriteLine(
    "You have {0} {1} left", player.Lives, "life".Pluralize(player.Lives)
);

A: using @Darin Dimitrov solution, I would create an extention for string ....
public static Extentions
{
    public static string Pluralize(this string str,int n)
    {
        if ( n != 1 )
            return PluralizationService.CreateService(new CultureInfo("en-US"))
            .Pluralize(str);
        return str;
    }
}

string.format("you have {0} {1} remaining",liveCount,"life".Pluralize());

A: string message = string.format("You have {0} left.", player.Lives == 1 ? "life" : "lives");

Of course this assumes that you have a finite number of values to pluralize.

A: I wrote an open-source library called SmartFormat that does exactly that! It's written in C# and is on GitHub:
http://github.com/scottrippey/SmartFormat
Although it supports several languages, English "plural rules" are the default.  Here's the syntax:
var output = Smart.Format("You have {0} {0:life:lives} left.", player.Lives);

It also supports "zero" quantity, and nested placeholders, so you could do:
var output = Smart.Format("You have {0:no lives:1 life:{0} lives} left.", player.Lives);

A: You can create a custom formatter that does that:
public class PluralFormatProvider : IFormatProvider, ICustomFormatter {

  public object GetFormat(Type formatType) {
    return this;
  }

  public string Format(string format, object arg, IFormatProvider formatProvider) {
    string[] forms = format.Split(';');
    int value = (int)arg;
    int form = value == 1 ? 0 : 1;
    return value.ToString() + " " + forms[form];
  }

}

The Console.WriteLine method has no overload that takes a custom formatter, so you have to use String.Format:
Console.WriteLine(String.Format(
  new PluralFormatProvider(),
  "You have {0:life;lives} left, {1:apple;apples} and {2:eye;eyes}.",
  1, 0, 2)
);

Output:
You have 1 life left, 0 apples and 2 eyes.

Note: This is the bare minimum to make a formatter work, so it doesn't handle any other formats or data types. Ideally it would detect the format and data type, and pass the formatting on to a default formatter if there is some other formatting or data types in the string.

A: See the Inflector class that is part of Castle ActiveRecord.  It is licensed under the Apache license.
It has a set of regular expression rules that define how words are pluralized.  The version I have used has some errors in these rules though, e.g. it has a 'virus' → 'virii' rule.
I have three extension methods which wrap Inflector, the first of which may be right up your street:
    /// <summary>
    /// Pluralises the singular form word specified.
    /// </summary>
    /// <param name="this">The singular form.</param>
    /// <param name="count">The count.</param>
    /// <returns>The word, pluralised if necessary.</returns>
    public static string Pluralise(this string @this, long count)
    {
        return (count == 1) ? @this :
                              Pluralise(@this);
    }

    /// <summary>
    /// Pluralises the singular form word specified.
    /// </summary>
    /// <param name="this">The singular form word.</param>
    /// <returns>The plural form.</returns>
    public static string Pluralise(this string @this)
    {
        return Inflector.Pluralize(@this);
    }

    /// <summary>
    /// Singularises the plural form word.
    /// </summary>
    /// <param name="this">The plural form word.</param>
    /// <returns>Th singular form.</returns>
    public static string Singularise(this string @this)
    {
        return Inflector.Singularize(@this);
    }

A: For C# 6.0 onwards, you can use Interpolated Strings to do this tricks.
Example:
    Console.WriteLine("\n --- For REGULAR NOUNS --- \n");
    {
        int count1 = 1;
        Console.WriteLine($"I have {count1} apple{(count1 == 1 ? "" : "s")}.");
        int count2 = 5;
        Console.WriteLine($"I have {count2} apple{(count2 == 1 ? "" : "s")}.");
    }

    Console.WriteLine("\n --- For IRREGULAR NOUNS --- \n");
    {
        int count1 = 1;
        Console.WriteLine($"He has {count1} {(count1 == 1 ? "leaf" : "leaves")}.");
        int count2 = 5;
        Console.WriteLine($"He has {count2} {(count2 == 1 ? "leaf" : "leaves")}.");
    }

Output:
 --- For REGULAR NOUNS ---

I have 1 apple.
I have 5 apples.

 --- For IRREGULAR NOUNS ---

He has 1 leaf.
He has 5 leaves.

You can play around on my .NET Fiddle.

For more details, go to Interpolated String documentation.

A: With the newfangled interpolated strings, I just use something like this:
// n is the number of connection attempts
Console.WriteLine($"Needed {n} attempt{(n!=1 ? "s" : "")} to connect...");

EDIT: just ran across this answer again--since I originally posted this, I've been using an extension method that makes it even easier. This example is ordered by peculiarity:
static class Extensions {
    /// <summary>
    /// Pluralize: takes a word, inserts a number in front, and makes the word plural if the number is not exactly 1.
    /// </summary>
    /// <example>"{n.Pluralize("maid")} a-milking</example>
    /// <param name="word">The word to make plural</param>
    /// <param name="number">The number of objects</param>
    /// <param name="pluralSuffix">An optional suffix; "s" is the default.</param>
    /// <param name="singularSuffix">An optional suffix if the count is 1; "" is the default.</param>
    /// <returns>Formatted string: "number word[suffix]", pluralSuffix (default "s") only added if the number is not 1, otherwise singularSuffix (default "") added</returns>
    internal static string Pluralize(this int number, string word, string pluralSuffix = "s", string singularSuffix = "")
    {
        return $@"{number} {word}{(number != 1 ? pluralSuffix : singularSuffix)}";
    }
}

void Main()
{
    int lords = 0;
    int partridges = 1;
    int geese = 1;
    int ladies = 8;
    Console.WriteLine($@"Have {lords.Pluralize("lord")}, {partridges.Pluralize("partridge")}, {ladies.Pluralize("lad", "ies", "y")}, and {geese.Pluralize("", "geese", "goose")}");
    lords = 1;
    partridges = 2;
    geese = 6;
    ladies = 1;
    Console.WriteLine($@"Have {lords.Pluralize("lord")}, {partridges.Pluralize("partridge")}, {ladies.Pluralize("lad", "ies", "y")}, and {geese.Pluralize("", "geese", "goose")}");
}

(formats are the same).  The output is:
Have 0 lords, 1 partridge, 8 ladies, and 1 goose
Have 1 lord, 2 partridges, 1 lady, and 6 geese

A: I'm thinking the easiest way to do it is to create an Interface IPlural which has an method  .ToString(int quantity) which returns the singular form when quantity == 1 an the plural form all other times.

A: Looking at how strings are typically written that account for simultaneous single and multiple values, e.g.

"Expected {0} file(s), but found {1} file(s)."

The approach I took was to keep the same string, but add some parsing to determine whether the (s) should be removed completely, or to keep the s inside the round brackets. For irregular words, a slash can separate the singular and plural form.
Other examples:

*

*"Had {0:n2} child(ren)".Pluralize(1.0) => "Had 1.00 child"

*"Had {0} cherry(ies)".Pluralize(2) => "Had 2 cherries"

*"Had {0} calf/calves".Pluralize(1) => "Had 1 calf"

*"Had {0} son(s)-in-law".Pluralize(2) => "Had 2 sons-in-law"

*"Had {0} able seaman/seamen".Pluralize(1) => "Had 1 able seaman"

*"Had {0} sheep, {1} goat(s)".Pluralize(1, 2) => "Had 1 sheep, 2 goats"

///<summary>
/// Examples:
/// "{0} file(s)".Pluralize(1); -> "1 file"
/// "{0} file(s)".Pluralize(2); -> "2 files"
///</summary>
public static String Pluralize(this String s, params Object[] counts) {
    String[] arr = s.Split(new [] { ' ' }, StringSplitOptions.None);
    for (int i = 0; i < arr.Length; i++) {
        String t = arr[i];
        if (t.Length == 0 || t[0] != '{' || t[t.Length - 1] != '}')
            continue;

        int w = 1;
        while (w < t.Length) {
            char c = t[w];
            if (c < '0' || c > '9')
                break;
            w++;
        }

        if (w == 1)
            continue;

        int n = int.Parse(t.Substring(1, w-1));
        if (n >= counts.Length)
            continue;

        Object o = counts[n];
        if (o == null)
            continue;

        bool isSingle = false;
        if (o is int)
            isSingle = 1 == (int) o;
        else if (o is double)
            isSingle = 1 == (double) o;
        else if (o is float)
            isSingle = 1 == (float) o;
        else if (o is decimal)
            isSingle = 1 == (decimal) o;
        else if (o is byte)
            isSingle = 1 == (byte) o;
        else if (o is sbyte)
            isSingle = 1 == (sbyte) o;
        else if (o is short)
            isSingle = 1 == (short) o;
        else if (o is ushort)
            isSingle = 1 == (ushort) o;
        else if (o is uint)
            isSingle = 1 == (uint) o;
        else if (o is long)
            isSingle = 1 == (long) o;
        else if (o is ulong)
            isSingle = 1 == (ulong) o;
        else
            continue;

        for (int j = i + 1; j < arr.Length && j < i + 4; j++) {
            String u = arr[j];
            if (u.IndexOf('{') >= 0)
                break; // couldn't find plural word and ran into next token

            int b1 = u.IndexOf('(');
            int b2 = u.IndexOf(')', b1 + 1);
            if (b1 >= 0 && b2 >= 0) {
                String u1 = u.Substring(0, b1);
                String u2 = u.Substring(b2+1);
                char last = (u1.Length > 0 ? u1[u1.Length - 1] : ' ');
                String v = (isSingle ? "" : u.Substring(b1+1, (b2 - b1) - 1));
                if ((last == 'y' || last == 'Y') && String.Compare(v, "ies", true) == 0)
                    u1 = u1.TrimEnd('y', 'Y');

                arr[j] = u1 + v + u2;
                break;
            }
            int s1 = u.IndexOf('/');
            if (s1 >= 0) {
                arr[j] = (isSingle ? u.Substring(0, s1) : u.Substring(s1 + 1));
                break;
            }
        }
    }

    s = String.Join(" ", arr);
    s = String.Format(s, counts);
    return s;
}

A: I did a little bit of work with PluralizationService and came up with. I just made the PluralizationService static for performance and combined all.
Reference System.Data.Entity.Design
  using System.Data.Entity.Design.PluralizationServices;
  using System.Reflection;

  public static class Strings
  {
    private static PluralizationService pluralizationService = PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentUICulture);
    public static string Pluralize(this MemberInfo memberInfo)//types, propertyinfos, ect
    {
      return Pluralize(memberInfo.Name.StripEnd());
    }

    public static string Pluralize(this string name)
    {
      return pluralizationService.Pluralize(name); // remove EF type suffix, if any
    }

    public static string StripEnd(this string name)
    {
      return name.Split('_')[0];
    }
  }

A: I am using this extension method with .NET 4.6
public static string Pluralize(this string @string)
{
     if (string.IsNullOrEmpty(@string)) return string.Empty;

     var service = new EnglishPluralizationService();

     return service.Pluralize(@string);
}

A: If your application is English on you can use all the solutions shown here. However if you plan to localize the application the plural enabled message must be done in a proper way. This means that you may need multiple patterns (from 1 to 6) depending on the language and the rule to choose what the pattern is used depends on the language.
For example in English you would have two patterns
"You have {0} live left"
"You have {0} lives left"
Then you would have a Format function where you pass these two patterns with the liveAmount variable.
Format("You have {0} live left", "You have {0} lives left", liveAmount);

In a real application you would not hard code the string but would use resource strings.
Format would know what the active language is and if English it would use
if (count == 1)
  useSingularPattern
else
  usePluralPattern

To implement this yourself is a bit complex bu you don't have to. You can you an open source project I have made
https://github.com/jaska45/I18N
By using it you can easily get the string
var str = MultiPattern.Format("one;You have {0} live left;other;You have {0} lives left", liveAmount);

That's it. The library knows what pattern to use depending on the passed liveAmount paramter. The rules have been extracted from CLDR into library .cs file.
If you want to localize the application you just put the multi pattern string into .resx and let the translator to translate it. Depending on the target language the multi pattern string might contains 1, 2, 3, 4, 5 or 6 patterns.

A: A bit late to the party, but I wrote a library called MessageFormat.NET that handles this.
var str = @"You have {lives, plural,
                     zero {no lives}
                      one {one life}
                    other {# lives}
            } left.";
var result = MessageFormatter.Format(str, new {
    lives = 1337
});

The whitespace in the string surrounding the text is not required, but merely for readability.
This is great when translating, as languages have different rules when it comes to pluralization.


text:
Q: Minimum generator set for matrix algebras Let $A\subseteq M_n(\mathbb{R})$ a finite set, where $M_n(\mathbb{R})$ is the set of all $n\times n$ matrices. Let $S(A)$ the generated algebra by $A$.
What is the minimun number of elements of $A$ in order that $S(A)=M_n(\mathbb{R})$?
In other words: what is the minimum $k$ such that there are $A_1,...,A_k$ elements of $M_n(\mathbb{R})$ with the property that every element of $M_n(\mathbb{R})$ is a polynomial on $A_1,...,A_n$?
I know that there is a lot of articles about the exact number of elements of $A$, but i believe this is a simpler question.

A: I can do it with $2$ matrices. One matrix $X$ with all entries $0$ except for one (say the top left) where we have a $1$, and one order-$n$ cyclic permutation matrix $Y$.
Any matrix with a single entry $1$ and the rest $0$ may be written as a product $Y^aXY^b$ for natural numbers $a,b$. Any matrix in $M_n(\Bbb R)$ may be written as a linear combination of those.


text:
Q: Laravel How to store multiple JSON data to an array so that all data can be accepted by controller I have a project which I can add multiple data. ex: I will add 2 names and it will be display on the next table. Also I converted each data into json so that I can pass it to the controller. Now my problem is that every time I click the check button the controller can only read the last data I inputted. Is there any way to get all data from table and pass it to controller? Here's my script.
<!DOCTYPE html>

  <meta charset="utf-8">

<form id="form_id">
    First Name:
    <input type="text" id="firstname" name="firstname" value="" placeholder="Max" required="required" autofocus="autofocus" />
    Last Name:
    <input type="text" id="lastname" name="lastname" value="" placeholder="Max" required="required" autofocus="autofocus" />
    <input type="button" value="submit" id="submit-button" />
</form>

List of all person

<form method="post">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

             First Name
             Last Name

<button class="btn btn-lg btn-primary btn-sm">Check</button>
</form>

A: Instead of storing all the JSON data as text in the hidden field, create a new input for each new name. Instead you would add hidden inputs in your java script which would result in something like this
<input type="hidden" name="name[0]">

<input type="hidden" name="name[1]">

In your controller you can use the following (based on using request laravel5)
public function myFunction(Request $request) {
    foreach($request['name']  as $name)
    {
        //do something with your name variable
    }

}

A: Due to limited characters in comment. I will post my latest issue here.
I dont know if it is correct. Here's my latest code
Input example:
Firstname   Lastname
Kerwin      Manisan
Ivan        Sanchez

Javascript
$('table.footable tbody').append('
<input type="text" name="firstname[]" value="'+obj['firstname']+'">	<input type="text" name="lastname[]" value="'+obj['lastname']+'">
');

Controller:
public function test(Request $request){
    return $data = $request->input('firstname');
}

Result:
["Kerwin","Ivan"]

Sad to say the output that I need is something like this.
[{"firstname":"Kerwin","lastname":"Manisan"},{"firstname":"Ivan" , "lastname":"Sanchez"}]

EDIT:
Problem solved. I used count to determine how many rows and then used loop to show the rows.
Controller:
public function test(Request $request){

        $count = count($request->input('firstname'));
        for ($i=0; $i<$count; $i++){
            $data[] = array('firstname' => $request->input('firstname')[$i], 'lastname' => $request->input('lastname')[$i]);
        }
        return $data;
    }


text:
Q: PHP Regex: CSS Relative to Absolute I have a problem with a difficult regex. I have this expression to detect absolute urls (http and https
/(url {0,}\(( {0,}'| {0,}"|))(?!http|data\:).*?\)/im

What I want to do basically is with preg_replace to prepend the url with a path $path defined in my script. Basically this regex results in two capture groups:
group 1: (url {0,}\(( {0,}'| {0,}"|))(?!http).*?\)

group 2: ( {0,}'| {0,}"|)

How can I match all the way until the uri starts and then prepend it with $path? I can't seem to get the capturing groups right.

A: You can use something like this:
$re = '/\b url \s*+ \( \s*+ (?| " ([^"]*+) " | \' ([^\']*+) \' | (\S*+) ) \s*+ \) /ix';

$str = preg_replace_callback($re, function ($match) {
    $url = $match[1];
    // do some check on the url
    if(whatever)
        return $match[0]; // return without change

    // do whatever you want with the URL
    // return new url
    return "url(\"$url\")";
}, $str);


text:
Q: Can't seem to update dynamodb Java I have an item inside of dynamo db:
**User**
username
email
password
acnt_status

I am trying to update the account_status to 1 where username = 'Bob', but it wont work. SQL equivalent would be UPDATE USERS SET acnt_status = 1 WHERE username = 'Bob';
This is my Java code, but it always throws an exception with a null getMessage():
UpdateItemSpec updateItemSpec = new UpdateItemSpec()
                                    .withPrimaryKey("username", "Bob")
                                    .withReturnValues(ReturnValue.NONE)
                                    .withUpdateExpression("set #acnt_status = :val")
                                    .withNameMap(new NameMap()
                                            .with("#acnt_status", "acnt_status"))
                                    .withValueMap(new ValueMap()
                                            .withNumber(":val", 1));

A: I found the solution. I didn't include it, but late in the code i had a QueryOutcome and realized I had the query return no data so the QueryOutcome was throwing an error.


text:
Q: Do vanishing characteristic classes of the tangent bundle imply a manifold is stably frameable? Suppose we know that all stable characteristic classes of the tangent bundle of a manifold $M$ vanish, i.e. the map $f:M\rightarrow BO$ stably classifying the tangent bundle is trivial on cohomology, i.e. $0=f^*: H^*(BO, A)\rightarrow H^*(M, A)$, for all coefficients $A$. Is it then possible to find a stable framing of $M$? In other words, can we lift $f$ to a map $\tilde{f}: M\rightarrow B\{1\}\simeq *$?
I know this is not the case for a general vector bundle (as discussed in Hatcher's "Vector bundles and K-theory", p.75-76), but I was wondering whether it might be true when restricting to the case where the bundle is the tangent bundle of a manifold. And how about if it is a normal bundle?

A: Suppose that $X^n$ is a finite complex and $V \to X$ a vector bundle which has trivial characteristic classes but is not stably trivial. Examples for such bundles were given in the answers to
Non-stably trivial bundle with trivial characteristic classes
The stable normal bundle of $S^{2n}$ admits a bundle map to $V$ (because $S^{2n}$ is stably parallelizable). This gives a map $f: S^{2n} \to X$, covered by a bundle map. By surgeries below the middle dimension, we can change $S^{2n}$ and $f$ to a map $f':M \to X$ which is covered by a bundle map $\nu_M \to V$ and such that $f$ is $n$-connected.
To see that $\nu_M$ is not stably trivial, note that since $X$ is $n$-dimensional and $f: M \to X$ $n$-connected, we can find a map $g: X \to M$ with $f \circ g \simeq id_X$, by basic obstruction theory.
But  $g^* \nu_M \cong g^* f^* V  \cong V$ is not stably trivial, and so $\nu_M$ isn't, either.


text:
Q: How to write javascript regular expression that matches a string and returns modified string I am new in writing Regex in javascript. I have a use case that looks like this:

*

*Input: My {name} is {Rahul}

*Output: Array containing - name and Rahul.

I can write Regex to extract {name} and {Rahul} and then modify it. But is there a way that I search for {name} using Regex in the string but returns name in the output.
Thanks for your help.

A: You might have better luck using the split() method to just grab the last word since the word 'name' isn't changing, only the actual name value is.
var str = "My name is Rahul";

var res = str.split(" ");

var name = res[3];


text:
Q: How can I fix spring boot to serve my static files from ROOT after upgrade Recently, I upgraded my spring boot version from 2.2.6 to 2.6.1.  After the upgrade, the server no longer finds my files in ROOT.   The static files are built from an angular project which is added to my ROOT.war file at build time and the war file is moved to my server.
On the server, my static files are located at tomcat/webapps/ROOT.  Previously (before upgrading) my files were found here and there were no issues.  Since the upgrade typing myurl.com returns 404 but will return if I type myurl.com/index.html.  I've tried to set up the WebMvcConfigurer for example
public void addResourceHandlers(ResourceHandlerRegistry registry){
   registry.addResourceHandler("/**")
   .addResourceLocations("/");
}

I added to my application.properties
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
I also added server.servlet.register-default-servlet=true thinking it was the DefaultServlet removal that caused the issue but this didn't make any difference.
In the logs, I can see the ResourceHttpRequestHandler is mapped to [classpath[META-INF/resources], classpath[resources/], classpath[static/], classpath[public], ServletContext[/]]
The logs also indicate the Resource is not found.
I can move the files to webapps/ROOT/WEB-INF/classpath/static and they show up but I was hoping to avoid messing with the build process.  Was there a change in the framework to disable root level static file serving or am I missing something?