text:
Q: Cross Validation with Spacy for Named Entity Recognition I am trying to train a custom NER Model on 50,000 million samples. I am using minibatch with 20 iterations for modeling. I want to understand if I should be using use Cross-Validation for more accurate out of sample accuracy. If yes then where should the cross-validation step take place? If no, then how do I split/distribute my training and testing data, since I am using annotations and 6 custom entities and it is hard to keep track of the percentages of annotated labels in each of training and test data since and evenly distribute it.
Here is the code I am using for training -
def train_spacy(data, iterations):
    TRAIN_DATA = data

    # create blank Language class
    nlp = spacy.blank('en')

    # create the built-in pipeline components and add them to the pipeline
    # nlp.create_pipe works for built-ins that are registered with spaCy
    if 'ner' not in nlp.pipe_names:
        ner = nlp.create_pipe('ner')
        nlp.add_pipe(ner, last=True)

    # Add LABELS
    for _, annotations in TRAIN_DATA:
         for ent in annotations.get('entities'):
            ner.add_label(ent[2])

    # Get names of other pipes to disable them during training
    other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']

    # only train NER
    with nlp.disable_pipes(*other_pipes):
        optimizer = nlp.begin_training()
        for itn in range(iterations):
            print("Starting iteration " + str(itn))

            for batch in batches:
                texts, annotations = zip(*batch)
                nlp.update(texts, annotations, sgd=optimizer,
                           drop=0.20,losses=losses)
            print('Losses', losses)

    return nlp

if __name__ == "__main__":

    # Train formatted data
    model = train_spacy(data, 10)

I think cross-validation step should take place somewhere inside the for loop for iterations but I am not sure. Can someone throw some light on how to use cross-validation with Spacy NER or whether is it not needed at all?

A: Ideally, you would split off a proportion of your training dataset as "development set" and use all entities in that set to tune your hyperparameters.
If you select the proportion at random (make sure not to bias towards date or name), you would expect the distributions of entities to be roughly the same, too. It's always best not over-engineer this split but take a true random sample.


text:
Q: Different output each time on multiple threads I keep getting different output each time this program is run. Also, the program never terminates, but stops using the cpu. I am not sure what is going on.
It is supposed to read a file, one character at a time, write it to a buffer, and output it if the character is a function character. Each thread handles one job of reading, writing, and outputting.
The program outputs different characters each time.
Can someone help?
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>
#include <pthread.h>

// Global variables(s) / Shared data
FILE *filePointer;
char input;
char buffer[60] = {'\0'};

// Condition variable(s)
pthread_cond_t characterInput;
pthread_cond_t printingLine;

bool charRead = false;
bool printBuffer = false;

// Mutex to control access to shared data.
pthread_mutex_t lock;

/*
 Thread 1:
 Reads input one character at a time.
 Passes the read character to Thread 2 before another is read.
*/
void *readCharacter(void *arg)
{
    // Begin Critical section
    pthread_mutex_lock(&lock);

    // Receive the character from the user.
    if ((input = fgetc(filePointer)) == EOF) pthread_exit(NULL);

    // Let the other threads know a character has been received.
    charRead = true;
    pthread_cond_signal(&characterInput);

    // End Critical section
    pthread_mutex_unlock(&lock);

    pthread_exit(NULL);
}

/*
 Thread 2:
 Stores characters as received.
 However, these characters ask Thread 2 to take action:

 * – erase last character from buffer

 @ – insert an end-of-line marker into buffer

 $ – delete the last word

 & – remove current incomplete line from buffer
*/
void *receiveCharacter(void *arg)
{
    int bufferIndex = 0;

    // Begin Critical section
    pthread_mutex_lock(&lock);

    // Wait to receive a character.
    if (!charRead) pthread_cond_wait(&characterInput, &lock);
    charRead = false;

    // Check to see if the character is an action.
    switch (input) {
        case '*':
            buffer[bufferIndex--] = '\0';
            break;

        case '@':
            buffer[bufferIndex] = '\0';
            // Signal to print the buffer.
            printBuffer = true;
            pthread_cond_signal(&printingLine);
            break;

        case '$':
            while (bufferIndex >= 0 && buffer[bufferIndex] != ' ')
            {
                buffer[bufferIndex] = '\0';
                bufferIndex--;
            }
            break;

        case '&':
            while (bufferIndex >= 0)
            {
                buffer[bufferIndex] = '\0';
                bufferIndex--;
            }
            break;

        default:
            buffer[bufferIndex] = input;
            bufferIndex++;
            break;
    }
    // END Critical Section
    pthread_mutex_unlock(&lock);

    pthread_exit(NULL);
}

/*
 Thread 3:
 Reads complete lines of characters (an end-of-line character is read).
 Prints the read line and removes it from the buffer.
*/
void *printLine(void *arg)
{
    // Begin Critical section
    pthread_mutex_lock(&lock);

    // Wait for the signal to print the buffer.
    if (!printBuffer) pthread_cond_wait(&printingLine, &lock);
    printBuffer = false;

    // Print the whole buffer.
    int i = 0;
    while (buffer[i] != '\0')
    {
        printf("%c", buffer[i]);
        buffer[i] = '\0';
        i++;
    }

    // End Critical section
    pthread_mutex_unlock(&lock);

    pthread_exit(NULL);
}

// Creates Threads 1, 2, and 3.
int main()
{
    // Thread 1, 2, and 3.
    pthread_t threadOne;
    pthread_t threadTwo;
    pthread_t threadThree;

    // Initialize the mutex.
    if (pthread_mutex_init(&lock, NULL) != 0) perror("Mutex error.\n");

    // Open the file.
    filePointer = fopen("homework4.txt", "r");

    // Wait for the threads to execute.
    while (input != EOF)
    {
        // Create and run the three threads.
        pthread_create(&threadOne, NULL, readCharacter, NULL);
        pthread_create(&threadTwo, NULL, receiveCharacter, NULL);
        pthread_create(&threadThree, NULL, printLine, NULL);
        if(pthread_join(threadOne, NULL) != 0) perror("Join error.\n");
        if(pthread_join(threadTwo, NULL) != 0) perror("Join error.\n");
        if(pthread_join(threadThree, NULL) != 0) perror("Join error.\n");
    }

    // Close the file.
    fclose(filePointer);

    // Destroy the mutex as it is no longer needed.
    if (pthread_mutex_destroy(&lock) != 0) perror("Destroy Mutex Error.\n");

    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS ALB Random 504 Gateway Timeouts Here's my setup:
ALB (listening on port 443)->NGINX (listening on port 444, as something else is using 443 on an EC2 proxy_pass by $host)
My issue is I'll only pull HTML every other time I use it through the ALB. I know it's not my Nginx config because If I do
curl --location -vvv -k 'https://$EC2_IP:444' -H 'Host: $FORWARD_HOST.LOCAL'

I pull HTML every time, even if I do a for loop and really spam it. Any ideas to resolve, or has anyone else ran into this problem before?
Update: After a bit more digging it looks like request_processing_time may be the culprit:

This value is set to -1 if the load balancer can't dispatch the request to a target. This can happen if the target closes the connection before the idle timeout or if the client sends a malformed request.

Will report back after modifying my nginx.conf. I've adjusted everything I can think of nothing works :/
nginx.conf
user nginx;

worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    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;

    resolver 127.0.0.1;
    resolver_timeout 60s;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   62s;
    types_hash_max_size 2048;

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

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    # Settings for a TLS enabled server.

    server {
        listen       444 ssl default_server;
        listen       [::]:444 ssl default_server;
        server_name  _;

        ssl_password_file /etc/nginx/my_certs/password_file;
        ssl_certificate /etc/nginx/my_certs/my.pem;
        ssl_certificate_key /etc/nginx/my_certs/my.key;
        ssl_session_cache shared:SSL:1m;
        ssl_session_timeout  1m;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location ^~ /proxycheck {
            return 200 'available';
            add_header Content-Type text/plain;
        }

        location / {
            set $upstream_endpoint https://$http_host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   Host      $http_host;
            proxy_http_version 1.1;
            proxy_set_header Connection "";
            proxy_pass $upstream_endpoint;
        }

    }

}

/etc/nginx/conf.d/timeout.conf
proxy_connect_timeout 600;
proxy_send_timeout 600;
proxy_read_timeout 600;


text:
Q: fpm .deb package docker dependencies I created a simple .deb package with fpm. The package is very basic and it simply runs a docker-compose file (see my other question here for package description).
I tried to specify that the package needs docker and docker-compose with:
fpm \
  -s dir -t deb \
  --deb-use-file-permissions \
  -p diagnosticator-0.1.0-1-any.deb \
  --name diagnosticator \
  --license agpl3 \
  --version 0.1.0 \
  --architecture all \
  --depends bash \
  --depends docker \
  --depends docker-compose \
  --description "Diagnosticator local app" \
  --url "https://diagnosticator.com" \
  --maintainer "Enrico Cocchi" \
  diagnosticator=/usr/bin/diagnosticator diagnosticator.1=/usr/share/man/man1/diagnosticator.1 docker-compose.yml=/usr/lib/diagnosticator/docker-compose.yml

but if I try to install it with sudo dpkg -i diagnosticator-0.1.0-1-any.deb:
dpkg: dependency problems prevent configuration of diagnosticator:
 diagnosticator depends on docker; however:
  Package docker is not installed.
 diagnosticator depends on docker-compose; however:
  Package docker-compose is not installed.

even if I have both installed and working for my user:
$ which docker
/usr/bin/docker

$ which docker-compose
/usr/local/bin/docker-compose

What am I doing wrong here?

A: Package dependencies are on package names, not binaries.
For docker, you can determine the appropriate package name by running
dpkg -S /usr/bin/docker

For docker-compose, you might need to create your own package first, or switch to the relevant package.
You might also want to install your package using apt install ./diagnosticator-0.1.0-1-any.deb instead of dpkg -i; that will try to resolve dependencies for you. Note too that your package file name should be diagnosticator_0.1.0-1_all.deb.


text:
Q: How to find last row that has same value as my last one and output the number of that row? I have a worksheet with stock transactions, so in column C I will input the name of the stock that I'm buying or selling at a given time.
.....A.....|....B....|...C....|
DATE  | TYPE   |  STOCK
...........|    Buy |     IBM
...........|    Sell |   Apple
...........|    Buy    |   Google
...........|    Buy |     IBM
How can I get the number of the row where the stock im trading now was last mentioned?
i.e. when I last put IBM on row 5, how can i get next to it an output of 2 which is the row of my last IBM input?

A: In D2 enter the Array formula:
=IF(MAX(IF($C$1:C1=C2,ROW($C$1:C1)))=0,"",MAX(IF($C$1:C1=C2,ROW($C$1:C1))))

and copy down

Array formulas must be entered with Ctrl + Shift + Enter rather than just the Enter key.


text:
Q: How to show that $r_1, r_2,.., r_k$ are linearly independent Prove that if $R$ is a matrix in echelon form , then a basis  for $\mathcal{R}(R)$ consists of the non zero rows  of $R$
My attempt  : For basis we must show the span and linearly independent properties
let $r_1,r_2 ,..., r_k$ be the non zero rows of $R$ starting from the $1$st row to the  $k-$th row
now we will prove  that $\mathcal{R}(A)= \operatorname{span}  \{ r_1,r_2,....., r_k\}$
for any vector  $v \in \mathcal{R}(A)$, we can write
$ v= c_1r_1 +....+c_kr_k +c_{k+1}0 +......+c_m0= c_1r_1 +....+c_kr_k$
so $v \in \operatorname{span}\{r_1,r_2,........,r_k\}$
Therefore $\mathcal{R}(R) \le\operatorname{span} \{r_1,....,r_k\}$
now trivially we also have $\operatorname{span}\{r_1,....,r_k\} \le  \operatorname{span}\{r_1,r_2,...,r_k,0,0,...,0\} =\mathcal{R}(R)$
This implies  that $\operatorname{span}\{r_1,....,r_k\}=\mathcal{R}(R)$
My doubts : How to show that  $r_1, r_2,.., r_k$ are linearly independent

A: linear independence By echelon form, you have ordered the rows by the number of zeros on the left. This number of zeros is strictly increasing. Take they order from the maximum number of zeros to the minimum (so in your row-echelon matrix you go from the lowest one up to the first row).
Let say you have $r_1,\dots, r_m$ non-zero rows. Now $r_1\neq 0$ so it is lineary independ. Now you add $r_2$, this can't by scalar multiple of $r_2$ because it have non-zero on the position where the $r_1$ has zero.
Now you have proved that $r_1,\dots r_k$ are independ. $r_{k+1}$ has non-zero on the position where all $r_1,\dots r_k$ have zero so it cant be spanned by them.


text:
Q: Laravel 5.4 Intevention Image Not Readable Exception when the image is readable I'm learning about the Intervention Image package with Laravel 5.4. I've got an image stored in my public/images folder.
I installed Image according to the instructions on Intervention's page: added intervention to my composer.json file, ran composer update, updated my config/app file, and ran composer dump-autoload.

*

*When directly accessed as an image (the printf statement in the code
block below) the image displays.

*Using the make method, I get a NotReadableException in
AbstractDecoder.php.
Does anyone see if I'm doing something wrong in the code or may have missed a step in installation?
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;

class TestController extends Controller
{
    public function imagetest()
    {
        printf('<img src="/images/j6.jpg">'); //correctly displays image on page

        $img = Image::make("/images/j6.jpg")->resize(300, 200); //throws the error
        return $img->response('jpg');
    }
}

And here's the lead of the error block that's on the page after the "printf" image:
Whoops, looks like something went wrong.

1/1
NotReadableException in AbstractDecoder.php line 339:
Image source not readable
in AbstractDecoder.php line 339
at AbstractDecoder->init('/images/j6.jpg') in AbstractDriver.php line 64
at AbstractDriver->init('/images/j6.jpg') in ImageManager.php line 50
at ImageManager->make('/images/j6.jpg') in Facade.php line 221
at Facade::__callStatic('make', array('/images/j6.jpg')) in TestController.php line 14
at TestController->imagetest()
at call_user_func_array(array(object(TestController), 'imagetest'), array()) in Controller.php line 55
at Controller->callAction('imagetest', array()) in ControllerDispatcher.php line 44
at ControllerDispatcher->dispatch(object(Route), object(TestController), 'imagetest') in Route.php line 203
at Route->runController() in Route.php line 160
at Route->run() in Router.php line 559
at Router->Illuminate\Routing\{closure}(object(Request)) in Pipeline.php line 30
at Pipeline->Illuminate\Routing\{closure}(object(Request)) in SubstituteBindings.php line 41
at SubstituteBindings->handle(object(Request), object(Closure)) in Pipeline.php line 148

A: You need to provide the full path of the image file in your filesystem.Judging from your image tag, the image should be in the images folder in your webroot. You can do this.
$imagePath = public_path('images/j6.jpg');
$img = Image::make($imagePath)->resize(300, 200);


text:
Q: TTS stops when phone's screen timesout in Android Whenever I start the TTS and keep it  onfor 30 seconds the screen times out and when it happens my TTS pauses and when I again tap the screen to unlock the phone it starts reading again..
Whether there is any way to keep the TTS up and running without pausing at any stage?

A: One solution would be to use setKeepScreenOn(true);
to keep the screen on.


text:
Q: mysql varbinary vs varchar We use varchar(255) for storing "keywords" in mysql. We are facing a problem that mysql ignores all trailing spaces for comparison purposes in "=". It does respect trailing spaces in "like" comparison, but it does not let us store same word with and without trailing spaces in a varchar column if it has a "UNIQUE" index over it.
So, we are considering switching to varbinary. Can anybody suggest what could be the implications when there are multi-byte characters in column values?

A: Andomar,
We use version 5.0.5. All mysql versions ignore trailing spaces for comparison. From the manual:

All MySQL collations are of type
  PADSPACE. This means that all CHAR and
  VARCHAR values in MySQL are compared
  without regard to any trailing spaces.
  This is true for all MySQL versions,
  and it makes no difference whether
  your version trims trailing spaces
  from VARCHAR values before storing
  them

Moreover mysql considers texts with/without trailing spaces duplicate in indexes:

For those cases where trailing pad
  characters are stripped or comparisons
  ignore them, if a column has an index
  that requires unique values, inserting
  into the column values that differ
  only in number of trailing pad
  characters will result in a
  duplicate-key error. For example, if a
  table contains 'a', an attempt to
  store 'a ' causes a duplicate-key
  error.

And, we absolutely need an index on keywords.
So, I guess we have two options: varbinary or text. We shall evaluate the performance of "text", and multibyte functionality for varbinary.

A: This is what the MySQL manual says about trailing spaces:

Handling of trailing spaces is
  version-dependent. As of MySQL 5.0.3,
  trailing spaces are retained when
  values are stored and retrieved, in
  conformance with standard SQL. Before
  MySQL 5.0.3, trailing spaces are
  removed from values when they are
  stored into a VARCHAR column; this
  means that the spaces also are absent
  from retrieved values.

Since your question says that MySQL does not repsect trailing spaces, I assume your version is lower than 5.0.3.  Consider using the TEXT type for your column; these preserve trailing spaces.  TEXT will handle the string's encoding and decoding for you, so you don't have to worry about multi-byte characters.
TEXT does perform slower than VARBINARY.  If actual data shows that performance is unacceptable, you might have to opt for VARBINARY (or a BLOB.)  In that case, it's up to you to store the string in a particular encoding, like UTF-8.  As long as all your clients use the same encoding, this would work fine for multi-byte characters.  Do test your clients with different regional settings :)

A: In addition to the trailing space problem, your UNIQUE INDEX in MySQL will be limited to 767 bytes (which makes 767/3 ~= 255 for 3-byte UTF8).  See also:

*

*http://bugs.mysql.com/bug.php?id=4541

*http://bugs.mysql.com/bug.php?id=42193

*http://code.djangoproject.com/ticket/9431


text:
Q: How to install libboost_version1.59 or newer on Ubuntu16.04 How can I install libboost1.59 ?
I have tried many methods to install it, but fail to update the version 1.58 on my Ubuntu 16.04 to the version 1.59.
I tried this and this on StackOverflow, this on linuxfromscratch.org and this blog post
Who can give me an effective method?

A: To get the latest go to boost on SourceForge, then:

*

*Download and extract with tar -xf boost_X_XX_X.tar.gz where XX is the version number, like tar -xf boost_1_62_0.tar.gz.

*cd boost_X_XX_X

*Get required libraries:
 sudo apt-get update && sudo apt-get install build-essential g++ python-dev autotools-dev libicu-dev libbz2-dev libboost-all-dev

*Build with: ./bootstrap.sh --prefix=/usr/local

*Install with: sudo ./b2 install
Please note you can also get the version currently on your version of Ubuntu can be gotten at the libboost-dev package page on UbuntuUpdates.


text:
Q: AngularJS table data not updating when uib-pagination is wrapped in another directive? I generated my project using JHipster and one of my entities uses pagination (). Everything is working fine, however I want to include a page size option along with pagination. But I don't see any option for that in UI Bootstrap documentation. Therefore I wrapped the uib-pagination directive in a custom directive.
Here is the directive:
'use strict';
//angularJS directive for Spring Pagination with page size control.

angular.module('myApp')
    .directive('springPagination', function(){
        return{
            restrict: 'AE',
            replace: true,
            scope: true,
            templateUrl: 'scripts/components/pagination/spring-pagination.html',
            controller: 'my_entity_controller'
        };
    })

Here is the template (HTML):

        <uib-pagination class="pagination-md" total-items="totalItems"
            ng-model="page" ng-change="loadAll()" rotate="false"
            boundary-links="true" boundary-link-numbers="true" max-size="7"></uib-pagination>

                Items Per Page:

                <input class="form-control" placeholder="Items per Page"
                    type="number" min="5" max="100" ng-model="newItemPerPage"></input>

                <button type="button" class="btn btn-info"
                    ng-click="setItemPerPage()">Set</button>

When i click on the item on my custom directive, for example the page number or set page size to 50, AngularJS is able to get the new value and send a REST request to the server and the server response with new data. However, my table remains the same page without any changes.
Can someone give me some directions please? Why is my data not updating like it supposed to without the custom directive? Perhaps there is a build-in option for ui.bootstrap.pagination to display page size so that I don't need to create a custom directive so that there is less hassle??

A: Silly me. Turns out my approach is doable, but I just forgot to use apostrophe on the boolean. So basically:
 scope: true

should be:
 scope: 'true'

I am pretty sure I saw other tutorials which use

scope: true

without the apostrophe too. But oh well, at least my problem is solved...
also, there is no need to put controller and replace option (well, at least for my use case i don't need to) because I want my directive to share the same controller from the html that I applied this custom directive to.


text:
Q: Distance metric for vector of functions and real numbers I want to cluster points which have the following feature vector:
$$\theta = (f_1, f_2, \cdots, f_n, y_1,y_2,\cdots,y_m)$$
i.e. the first $n$ entries are functions $f_i$ ($\mathbb{R}\rightarrow \mathbb{R}$) and the last $m$ entries are real numbers $y_i$.
Question:
What would be a good distance metric for clustering?


text:
Q: reversing non-zero-initialized chars in array I have an array that is of the form
{'1', '3', '2', '\0', '\0'}

i.e. - it has been zero initialized, and some amount of values (starting from the beginning) will have values other than '\0'
I would like to come up with a function that reverses the part of the array that is not '\0'. For example, the above array would turn into:
{'2', '3', '1', '\0', '\0'}

However, I am having trouble wrapping my brain around how to do this, since I am relatively new to array manipulation. Could someone help? Thanks :)

A: The C++ Standard Library is your friend. Note that this will work for arrays of any type - simply change the types. Other answers using functions like strlen will only work for C-strings.
#include <iostream>
#include <algorithm>
#include <array>

int main()
{
    auto arr = std::array<char, 5>{'1', '3', '2', 0, 0};
    std::reverse(arr.begin(), std::find(arr.begin(), arr.end(), 0));

    for (auto c : arr)
    {
        std::cout << c << std::endl;
    }

    return 0;
}

http://en.cppreference.com/w/cpp/container/array
http://en.cppreference.com/w/cpp/algorithm/find
http://en.cppreference.com/w/cpp/algorithm/reverse

A: Cheers guys - here's what I ended up coming up with. Seems like it works.
void reverseRelevantParts(char arr[], int size) {

int counter = 0;

    for (int i = 0; i < size; i++) {
        if (arr[i] == '\0') {
            break;
        }
        else {
            counter++;
        }
    }
    int temporary = 0;
        for (int i = 0; i < counter/2; i++) {
            temporary = arr[i];
            arr[i] = arr[counter - i - 1];
            arr[counter - i - 1] = temporary;
        }
    }

A: OK, now that you tried and made your own answer...
char const* reverse(char * arr, int size)
{
    int beg = 0;
    int end = static_cast<int>(strnlen_s(arr, size)) - 1;

    while (beg < end) std::swap(arr[beg++], arr[end--]);

    return arr;
}


text:
Q: Autosuggest input preventing text from being copied to other input text field I am trying to have text copy from one text input field to the other as a user types.  I have been able to accomplish this thanks to everyone's help, but I ran into a problem.
If you visit the following page and type "Sub" in the "Car Manufacturer" text box, you will see it duplicate in the "TestField" text box.  However, since it is an autosuggest text box, Subaru pops up.
So, if you only type "Sub" and "Subaru" is suggested and you select it, only "Sub" is duplicated over to the next box.  You will notice also that once you select "Subaru" a checkbox is generated.  Maybe it would be better to duplicate from the checkbox instead?  But I have not been able to accomplish this unfortunately.
You can see the problem here (remember to only typ "sub" in the field and select "Subaru" to see what I'm talking about:
http://www.forzazone.com/forza-car-designs-and-paint-jobs/forza-motorsport-4-car-designs-and-paint-jobs/new-listing_c66/
Here is the code I'm currently using to perform the duplication:

If you have any ideas on how to prevent this that would be great.  One idea was to simply duplicate the text from the checkbox once "Subaru" is selected from the Autosuggest.
Thanks for your help with this!

A: You can easily extend the onclick method the  tag you are using for displaying the suggestions:
inside the tag:
Subaru

Implement the clickHandler function and set the value of the link to the test field you have created.
Hope that helps.


text:
Q: Wordpress interfering with subdirectory php script I have wordpress installed in root. In one subdirectory, I have a collection of PHP scripts (a simple login system)
The same collection of scripts work on my other server (that has no wordpress in root) perfectly. They don't work on this server though. Please help!

A: Try creating an .htaccess file in your subfolder and put this inside:
RewriteEngine Off

As addition please note:

If you are using Wordpress, be sure to protect yourself from hackers, and one step to secure your website and hosting from been hacked, is to NEVER have wordpress in the root, try create a subfolder for it


text:
Q: CodeIgniter Redirect issue I am testing a server on http://example.com:8080, my CI app is here http://example.com:8080/app/
I have a port forward from 8080 (external) to 80 (internal)
My config.php looks like this:
...
$config['base_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/app';
...
$config['index_page'] = '';

How should look the .htaccess file in order to get the site working. Also I have used this https://www.codeigniter.com/userguide3/general/urls.html with success on port 80, but cant get it work on 8080. If I leave the index.php in the url then everything works well also on port 8080.
Thanks for any suggestion.

A: Try this .taccess:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Its not clear your question why your redirect not working. Hope this help you. Always put what you have tried so far so everyone can understand better.
Greetings!

A: Finally I have found the issue... The rewrite module was not enabled, so I have enabled and everything works well.


text:
Q: Merging the content of 300 cells into 1 cell I need to send group emails. The email addresses are stored in an excel sheet in different columns. How do I merge all of the email addresses into one cell so that I can easily send group emails. The CONCATENATE function works but is their a way I can do it easily involving around 300 cells?

A: Edit: I just noticed your email addresses are in "different columns". If they're in a single row instead of a single column, then you can use this same technique, but obviously use "row 2" instead of "column B".
Say your email addresses are in column A:
    A
   --------------------
1  alice@example.com
2  bob@example.com
3  charlie@example.com
4  dave@example.com

Set cell B1 to =A1:
    A                    B
   -------------------- ---------------------
1  alice@example.com    alice@example.com
2  bob@example.com
3  charlie@example.com
4  dave@example.com

Now set cell B2 to =B1 & ";" & A2:
    A                    B
   -------------------- ---------------------
1  alice@example.com    alice@example.com
2  bob@example.com      alice@example.com;bob@example.com
3  charlie@example.com
4  dave@example.com

Now fill down cell B2:
    A                    B
   -------------------- ---------------------
1  alice@example.com    alice@example.com
2  bob@example.com      alice@example.com;bob@example.com
3  charlie@example.com  alice@example.com;bob@example.com;charlie@example.com
4  dave@example.com     alice@example.com;bob@example.com;charlie@example.com;dave@example.com

In other words, every cell in column B is "whatever is in the cell above, plus a semicolon and the next email address". The last cell includes every email address.

A: Alternatively if the addresses are in a single row but in different columns, you can:

*

*copy the emails (the entire row)

*paste them in notepad

*select a tab character

*copy it

*hit Ctrl + H to get the find/replace function

*paste in the tab character in the find and replace with your email address delimiter you're looking for (comma , or semicolon ;)

It will take a little time but it does the job as well! (except it's no more in excel but spares you long the 'middle calculation' excel has to do)

A: Regardless of whether the email addresses are organised in rows and/or columns: Just select and copy them.
Then go to Outlook and paste them into the To: or CC: field. Outlook will recognize the cell delimiter as a delimiter between email addresses and will take care of the semicolon separator.
The same applies if you are using VBA to create the email. Just copy and paste. No need to concatenate the cells beforehand.

A: On Google Sheet you can use
=CONCATENATE(TRANSPOSE(A2:A),", ")

Where A is the column with emails (A1 for header).


text:
Q: Using Doctrine(odm) events to implement document versioning for MongoDB I want to keep tracks of documents changes set on each update and delete. To apply this, I would like write old document in a "shadow collection". Any collection I want to keep track of it, should has a shadow collection.
I want to implement this strategy in Doctrine ODM.

*

*Which doctrine event proper for this propose?

*Can I access other Document in above event?

A: If you want to leverage ODM events you should take a look at preUpdate and preRemove or (postRemove).


text:
Q: How to use a Linux variable as a command parameter I am trying to use a bash shell variable as a command parameter but can't
Here is what works:
sed -n '2p' <file>

gives me line 2 of file
What I want to do:
sed -n '$variable p' <file>

Of course, this does not work. I have tried every possible syntax combination without success. How can I incorporate a variable in place of a constant?

A: Variables are expanded inside doublequotes, not inside singlequotes:
sed -n "$variable p" <file>

A: @Barmar has the right answer to your question.
I fear you are going to use this as a technique to iterate over the lines of a file.
This will be very inefficient:
for linenum in $(seq $(wc -l < filename)); do
    line=$(sed -n "$linenum p" filename)
    # do something with $line
done

The idiomatic way to iterate over the lines of a file is:
while IFS= read -r line; do
    # do something with "$line"
done < filename

A: Put the variable outside the string:
    sed -n $variable'p'


text:
Q: VBA Concatenating / using Format takes too long I want to loop through a column in a range and concatenate a date and a number to generate kind of an ID. The problem is: The cell that includes the date also includes the time, for now i use Format(datum.Cells(1, 1), "dd/mm/yyyy"), this however takes ages to process. Is there any way to speed that up?
For Each datum In Range(rngDestination.Cells(1, 14),
 rngDestination.Cells(lastRow, 14))
       If Not datum.Value = "" Then
         datum.Cells(1, 10).Value = Format(datum.Cells(1, 1), "dd/mm/yyyy")
       End If
Next datum
 For Each kette In Range(rngDestination.Cells(1, 1),
 rngDestination.Cells(lastRow, 1))
  kette.Cells(1, 0).Value = kette.Cells(1, 23).text& & kette.Cells(1, 5).text
Next kette

A: Work with arrays and typed functions? Not tested.
 Dim rng As Range, arr(), i As Long
 Set rng = Range(rngDestination.Cells(1, 14), rngDestination.Cells(lastRow, 14))

 arr = rng.Value
 For i = LBound(arr, 1) To UBound(arr, 1)
   If Not IsEmpty(arr(i, 1)) Then
       arr(i, 1) = Format$(arr(i, 1), "dd/mm/yyyy")
   End If
 Next

 rng = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Index(arr, 0, 1))

A: Try bringing it together at once in an array and then dumping the values back.
dim arr as variant, tmp as variant, i as long

with rngDestination
    arr = .Range(rngDestination.Cells(1, 14),  rngDestination.Cells(lastRow, 14)).value2
    tmp = .Range(rngDestination.Cells(1, 5),  rngDestination.Cells(lastRow, 5)).value2
    for i =lbound(arr, 1) to ubound(arr, 1)
        if cbool(len(arr(i, 1))) then
            arr(i, 1) = int(arr(i, 1))
        else
            arr(i, 1) = vbnullstring
        end if
    next i
    .Cells(1, 23).resize(ubound(arr, 1), ubound(arr, 1)) = arr
    .Cells(1, 23).resize(ubound(arr, 1), ubound(arr, 1)).numberformat = "dd/mm/yyyy"
    for i =lbound(arr, 1) to ubound(arr, 1)
        arr(i, 1) = format(arr(i, 1), "dd/mm/yyyy") & tmp(i, 1)
    next i
    .Cells(1, 0).resize(ubound(arr, 1), ubound(arr, 1)) = arr
end with


text:
Q: Play Background Sound and Sound Effect in Windows Phone 8 I have researched a lot on playing sounds for Windows Phone 8 devices and found multiple solutions but they don't quite match my case.
What I need : I'm writing an app (C#+XAML) that uses a file as background sound (must be active while navigating the whole app), and also to be able to play sound effects.
What are the issues :

*

*For background sound I could use the BackgroundAudio Agent, but it doesn't meet my requirements because I want the sound to be played only in the background of my app, and to stop if my app closes or is not active.

*For sound effects - I tried MediaElement which is okay, but I couldn't manage to make it somehow play while I am navigating the whole app. Media closes if I leave that page - I guess I could use this for the sound effects trick. Also, there's the SoundEffect which is not quite a good solution since it can play only .wav files... I could use it for sound effects only but not background sound (big sized files).

So, how should I proceed to play background sound (only inside my app) if I choose MediaElement/SoundEffect to play a sound effect in the app. I need a solution that would allow me to play 2 sounds at once (background and sound effect) and the background sound to be played only while the app runs (is active)...
So far I am confused and managed only to solve the sound effects issue.
Any suggestions are greatly appreciated.

A: The issue you are seeing with your MediaElement is that you are defining it to be part of the application page and it stops playing as soon as it disappears off of the Visual Tree (i.e. after OnNavigatedFrom).
If you define a MediaElement to be "visible" as part of the application frame, audio will keep playing while your app is active (you will need to handle deactivation events, naturally).
If you do this MediaElement should work for your "background audio".
Be aware you can only have one single active MediaElement playing media in your app, however you should be able to use SoundEffect for your sound effects.
Update:
To put your MediaElement in a frame, you will need to create a custom PhoneApplicationFrame class/XAML, add the MediaElement to that XAML, and refer to your custom frame in App.xaml.cs.
// Do not add any additional code to this method
private void InitializePhoneApplication()
{
    if (phoneApplicationInitialized)
        return;

    // Create the frame but don't set it as RootVisual yet; this allows the splash
    // screen to remain active until the application is ready to render.
    RootFrame = new MyCustomPhoneApplicationFrame();
    RootFrame.Navigated += CompleteInitializePhoneApplication;

See this Dzone article for more about Frame/Page in Windows Phone.

A: In practice, MediaElement is has some gotchas like the visual tree requirement. There are ways to get around it, but they are not optimal. I would suggest scrapping using MediaElement and use XAudio2 instead. It is native so default usage would be in c++, but you can also use SharpDX to access this framework from C#.
The advantage of XAudio2 is that you would not need to worry about sound dropping out when navigating around since it is not dependent on the UI. Another advantage is you could have one SourceVoice for handling your background audio, and other SourceVoices for handling sound effect playback. This all fits well within the model of usage the framework was designed for.


text:
Q: Using VBA Macro +buttons to move back and forward through excel sheets, hidden sheets in sequence disrupting functionality I have a pair of buttons ('continue' and 'back') which move a user forward and back worksheets.
The forward button seems to be able to move forward through visible sheets with no trouble, skipping hidden sheets fine.
The back button however, fails to do anything if there is a hidden sheet between the active sheet and the previous visible sheets.
I'm confused because the code for the two is practically identical:
Forward: (works fine)
Sub MoveNext()
On Error Resume Next
Sheets(ActiveSheet.Index + 1).Activate
If Err.Number <> 0 Then Sheets(1).Activate
End Sub

Back: (fails at hidden sheet)
Sub MoveBack()
On Error Resume Next
Sheets(ActiveSheet.Index - 1).Activate
If Err.Number <> 0 Then Sheets(1).Activate
End Sub

Each button is bound to the subs above as suitable.

A: Interesting! It looks like if you try to activate a hidden worksheet, it defaults to the next highest index. So that's why it works going up, but not going down. I wrote a routine that checks whether there's a lower visible sheet, and if so, moves to it:
Sub MoveBack()
Dim PrevVisibleIndex As Long

PrevVisibleIndex = ActiveSheet.Index
With ThisWorkbook
    Do
        PrevVisibleIndex = Application.WorksheetFunction.Max(PrevVisibleIndex - 1, 1)
    Loop Until .Worksheets(PrevVisibleIndex).Visible = True Or PrevVisibleIndex = 1
    .Worksheets(PrevVisibleIndex).Activate
End With
End Sub


text:
Q: AES Encryption and decryption for android and iOS gives wrong output Android code:
private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
private static final String KEY = "SixteenCharacter";
Encryption:
private static byte[] encrypt(final byte[] key, final byte[] originalData) {
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(originalData);
        return encrypted;
    } catch (Exception ex) {
       ex.printStackTrace();
       return new byte[0];
    }
}

Decryption:
private static byte[] decrypt(final byte[] key, final byte[] encryptedData) {
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        SecretKeySpec skeySpec = new SecretKeySpec(key, ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        byte[] original = cipher.doFinal(encryptedData);
        return original;
    } catch (Exception ex) {
        ex.printStackTrace();
        return new byte[0];
    }
}

iOS code:
static let KEY = "SixteenCharacter"
private static let iv: Array = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]
Encryption:
static func getEncryptedString(normal: String?, key: String, options: Int = kCCOptionPKCS7Padding) -> String {
    guard let normal = normal else { return "" }
    if let keyData = key.data(using: String.Encoding.utf8),
       let data = normal.data(using: String.Encoding.utf8),
       let cryptData    = NSMutableData(length: Int((data.count)) + kCCBlockSizeAES128) {
        let keyLength              = size_t(kCCKeySizeAES128)
        let operation: CCOperation = UInt32(kCCEncrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(options)
        var numBytesEncrypted :size_t = 0
        let cryptStatus = CCCrypt(operation,
                                  algoritm,
                                  options,
                                  (keyData as NSData).bytes, keyLength,
                                  iv,
                                  (data as NSData).bytes, data.count,
                                  cryptData.mutableBytes, cryptData.length,
                                  &numBytesEncrypted)

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            var base64cryptString = cryptData.base64EncodedString(options: .lineLength76Characters)
            //base64cryptString = base64cryptString.replacingOccurrences(of: "/", with: "_")
                        .replacingOccurrences(of: "+", with: "-")
            return base64cryptString
        }
        else {
            return normal
        }
    }
    return normal
}

Decryption:
static func getDecryptedString(normal: String?, key: String, options: Int = kCCOptionPKCS7Padding) -> String {
    guard var normal = normal else { return "" }
    //normal = normal.replacingOccurrences(of: "_", with: "/").replacingOccurrences(of: "-", with: "+")
    if let keyData = key.data(using: .utf8),
       let data = NSData(base64Encoded: normal, options: .ignoreUnknownCharacters),
       let cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {
        let keyLength              = size_t(kCCKeySizeAES128)
        let operation: CCOperation = UInt32(kCCDecrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(options)
        var numBytesEncrypted :size_t = 0
                    let cryptStatus = CCCrypt(operation,
                                  algoritm,
                                  options,
                                  (keyData as NSData).bytes, keyLength,
                                  iv,
                                  data.bytes, data.length,
                                  cryptData.mutableBytes, cryptData.length,
                                  &numBytesEncrypted)
        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            let unencryptedMessage = String(data: cryptData as Data, encoding:String.Encoding.utf8)
            if let unencryptedMessage = unencryptedMessage, !unencryptedMessage.isEmpty {
                return unencryptedMessage
            }
        }
        else {
            return normal
        }
    }
    return normal
}

As I haven't worked with AES encryption before, I have no idea where am I going wrong
I have seen so many solutions on the internet but no luck yet
Android code is already done and the only way I have is to modify the iOS code!
Thanks in advance!

A: You are working across two different systems.  That means you cannot rely on system defaults, they may be different.  You need to specify everything: Key, IV, padding, character encoding, etc.  Crypto is designed to fail with even a small mismatch, so you have to check everything to make sure it matches across both systems.  For instance, IIRC iOS and Java use different end-of-line characters.  Something as simple as that might throw off the decryption.
If there is nothing obvious then look at all the inputs to both sides in binary/hex to make sure everything matches exactly.
You are using ECB mode.  This is insecure and shouldn't be used except for very specific and rare situations.  Better to use CBC or CTR mode.  If you need authentication as well then try GCM mode.


text:
Q: custom node module's dependency not installed on root I have a app project and 2 node module projects.
The dependencies structure is something like this:
App {
  NodeModule1 {
    NodeModule2,
    ...
  },
  ...
}

The problem I have is that my NodeModule2 instead of being installed on the root of app's node_module App/node_modules/NodeModule2, it is installed in App/node_modules/NodeModule1/node_modules/NodeModule2
This is causing some error on runtime, says my NodeModule2 is not found. My workaround is to add NodeModule2 into App directly, which is not an idea solution.
All other dependencies of NodeModule1 are installed at App/node_modules/.. as expected.
My NodeModule2's package.json
{
  "name": "NodeModule2",
  "version": "0.0.2-20210202.1.0",
  "private": false,
  "description": "",
  "author": "",
  "license": "ISC",
  "peerDependencies": {
    "react": "16.13.1",
    "react-native": "0.59.10",
    ...
  }
}

A: I HAVE GOT IT
In order for sub node_module to be appeared on the root level, all its peerDependenciess' versions must be matched with App's.
In my case both of my App and NodeModule1 has dependency of react-native-picker-select but with different versions.
App {
  dependency: {
    "react-native-picker-select": "^8.0.0"
  }
}

NodeModule1 {
  dependency: {
    "react-native-picker-select": "8.0.0"
  }
}

NodeModule2 {
  peerDependency: {
    "react-native-picker-select": "8.0.0"
  }
}

In this case, App received 8.0.4 and NodeModule1 received 8.0.0.
Yarn puts NodeModule2 under NodeModule1 and to shared the same dependency version 8.0.0.
Fix: Make sure all versions are matched in App, NodeModule1, and NodeModule2.


text:
Q: Git Bash: "fatal: remote end hung up unexpectedly" I am using a Windows Vista machine with msysgit installed and attempting to clone a remote git repository using Git Bash, but I get the error "fatal: remote end hung up unexpectedly".  I am able to SSH my company's server and get a listing of repositories, and the server admin has granted me access to the ones I'm trying to clone.  The server admin reports that I am not connecting to the server when I run "git clone ".  Also, I am not asked for the password on my private key.  I have successfully set up projects from the same repository on the same machine before.  Any ideas?

A: It might be worth explicitly adding the ssh protocol specifier:
git clone ssh://git@git.somewhere.com/path/to/project

A: Check the case in when you specify the repository name. The URLs are case sensitive.


text:
Q: HTML entity handling in Python 3/BeautifulSoup on Windows I'm having trouble handling HTML containing escaped unicode characters (in the Chinese range) in Python3/BeautifulSoup on Windows. BeautifulSoup seems to function correctly, until I try to print an extracted tag, or write out to file. I have my default encoding set to utf-8, yet a cp1252 codec seems to be getting selected...
To reproduce:
soup = BeautifulSoup("隱")

f = open("out.html", "w")
f.write(soup.text)
f.close()

Stack trace attached.
Traceback (most recent call last):
  File "scrape.py", line 143, in <module>
    test_uni()
  File "scrape.py", line 126, in test_uni
    f.write(soup.text)
  File "c:\venv\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u96b1' in position 0: character maps to <undefined>

A: You were trying to write non-english (unicode) string to file which Python expects ascii bytestring at default. This is not about your windows environment.
Encode the text before writing to file should work, and utf-8 should be fine with Chinese characters:
f.write(soup.text.encode('utf-8'))


text:
Q: On $F_k$-free extermal graphs In 1995, Erdos, Furedi, Gould and Gunderson considered the Turan-type problem for $F_k$-free graphs, and they established the following result:
For $k\geq 1$ and $n\geq  50k^2$, we have
$$
ex(n,F_k )=\lfloor \frac{n^2}{4} \rfloor +
\begin{cases}
k^2 -k, & \text{if k is odd;}\\
k^2 -\frac{3}{2}k, & \text{if k is even}.
\end{cases}
$$
Furthermore, the number of edges is best possible. If $k\; (n \geq 4k −1)$ is odd, then the
unique extremal graph is constructed by taking a complete equi-bipartite graph and
embedding two vertex disjoint copies of $K_k$ in one side; if $k\; (n \geq 4k − 3)$ is even,
then the extremal graph is constructed by taking a complete equi-bipartite graph and
embedding a graph with $2k −1$ vertices, $k^2 − \frac{3k}{2}$ edges and maximum degree $k −1$ in
one side.
Here $F_k$ denotes the $k$-fan consisting of $k$ triangles which intersect in
exactly one common vertex.
I don't understand how to construct and to plot the shape of the extermal graphs explained above. Is there anyone who plots two graphs (for two cases of $k$: odd and even) for me to understand them?
Thanks in advance.

A: Here's an example of the construction when $k=3$, with the two copies of $K_3$ highlighted in red:

In this example $n=20$, so we start with $K_{10,10}$ and add the two copies of $K_3$. If $n$ were odd, we would start with a slightly unbalanced bipartite graph: for example, for $n=21$, we would start with $K_{10,11}$. In that case, the two copies of $K_3$ can be added on either side (but both on the same side).

Here's an example of the construction when $k=4$, with the added edges highlighted in red:

There are many options for the red subgraph: when $k=4$, we are looking for a graph with $7$ vertices, $10$ edges, and maximum degree $3$.
In general, the value $k^2 - \frac32 k$ is simply the most edges a graph with $2k-1$ vertices and maximum degree $k-1$ can have. Such a graph will have degree sequence $$\underbrace{k-1, k-1, \dots, k-1}_{2k-2 \text{ times}}, k-2.$$ Not all the degrees can be $k-1$, because that would be an odd number of odd degrees.

Technically speaking, it is not correct to say that the extremal graph is unique, merely that it is always a graph that matches the description given. There are two places where we have the flexibility to get multiple extremal graphs:

*

*Whenever $n$ is odd, we start with a bipartite graph with parts of size $\frac{n-1}{2}$ and $\frac{n+1}{2}$. The extra edges we add can be put in either part, which does not produce isomorphic graphs.

*Whenever $k$ is even (and at least $4$), there are many non-isomorphic graphs with the degree sequence $k-1,k-1,\dots,k-1,k-2$, and we can add any of them to get a valid extremal example.

Only when $k$ is odd and $n$ is even do we get a unique extremal graph (or if $k$ is odd and $n=4k-1$, since then we are adding two copies of $K_k$ to $K_{2k,2k-1}$, and only the side with $2k$ vertices is big enough to fit them).


text:
Q: Efficient way to copy all bean properties into another bean I am trying to copy all properties from one bean into another:
public void copy(MyBean bean){
    setPropertyA(bean.getPropertyA());
    setPropertyB(bean.getPropertyB());
    [..]
}

This is error prone and a lot to write if you have a bean with lots of properties.
I was thinking of reflection to do this, but I cannot "connect" the getter from one object to the setter of the other one.
public List<Method> getAllGetters(Object object){
    List<Method> result = new ArrayList<>();
    for (final PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors()) {
    result.add(readMethod = propertyDescriptor.getReadMethod());
    }
    return result;
}

Edit:
 BeanUtils.copyProperties(this, anotherBean);

Works just as expected!

A: Consider using Apache BeanUtils or Spring's BeanUtils. They both have a copyProperties() method which will do what you want.
It is also conceivable that the JDK's Object.clone() will get you the results you need. Be sure to review the Javadoc and this SO post so that you are aware of its limitations.

A: If you wanna do this manually I suggest to uses what is calling "Serialization copy". The one limitation is that the bean most implement Serializable interface. As you say it could be done using reflection, but you could have more inconveniences.
Hope this help.


text:
Q: utility class in to serve different TabItems I'm new to C# and I'm trying to find out whats the way to write a utility class that could serve, in my case, a few different tabitems. In JAVA I could write an Enum class for that purpose. How do you do that in C#?

A: It's difficult to tell what exactly the question is, but if you are looking to declare an enumeration, C# has the enum keyword (see: MSDN).  E.g.:
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

You can then use the enum directly:
public void PrintDayName(Days day)
{
   //...
}

Regarding your comment:

I want to build a class that will provide access to methods for a few different classes. All the class will need access to the same instance of this "utility" class.

If you refer to the enum as above, it will effectively be the "same instance", since each enum value simply represents some integral value (e.g. 0, 1, 2, 3, etc).  If you are referring to an actual utility class, those are typically implemented as static classes, which works pretty similarly to how Java treats the static keyword.


text:
Q: Is there a way to offer multiple video qualities (resolutions) without uploading multiple videos in HTML5 video player? I'm trying to add a few videos to my website using HTML5. My videos are all 1080, but I want to give people the option to watch in a lower quality if needed. Can I do this without having to upload multiple videos (1 for each quality) without the usage of a server-side language?
I've been extensively searching for this. Haven't find anyone say that it can't be done, but no one said it can either. I am using Blogger as my host, which is why I am can't use server-side languages.
Thank you.

A:
without the usage of a server-side language?

Yes, of course.  The client can choose what version of the video to download.

Can I do this without having to upload multiple videos (1 for each quality)

Not practically, no.  You need to transcode that video and upload those different versions.

Haven't find anyone say that it can't be done

A couple things to consider... first is that a video file can contain many streams.  I don't know what your aversion is to multiple files, but yes it is possible to have several bitrates of video in a single container.  A single MP4, for example, could easily contain a 768 kbps video, a 2 Mbps video, and an 8 Mbps video, while having a single 256 kbps audio track.
To play such a file, a client (implemented with Media Source Extensions and the Fetch API) would need to know how to parse the container and make ranged requests for specific chunks out of the file.  To my knowledge, no such client exists as there's little point to it when you can simply use DASH and/or HLS.  The browser certainly doesn't do this work for you.
Some video codecs, like H.264, support the concept of scaling.  The idea here is that rather than having multiple encodings, there's just one where additional data enhances the previous video that was sent.  There is significant overhead with this mechanism, and even more work you'd have to do.  Not only does your code now need to understand the container, but now it has to handle the codec in use as well... and it needs to do it efficiently.
To summarize, is it possible to use one file?  Technically, yes.  Is there any benefit?  None.  Is there anything off-the-shelf for this?  No.
Edit: I see now your comment that the issue is one of storage space.  You should really put that information in your question so you can get a useful answer.
It's common for YouTube and others to transcode things ahead of time.  This is particularly useful for videos that get a ton of traffic, as the segments can be stored on the CDN, with nodes closer to the clients.  Yes, it's also possible to transcode on-demand as well.  You need fast hardware for this.

A: No.
I can't fathom how this could ever be possible. Do you have an angle in mind?
Clients can either download all or part(s) of a file. But to do this you would have to somehow download only select pixels of each frame. Even if you had knowledge of which byte-ranges of each frame were which pixels, the overhead involved in requesting each byte-range would be greater than the size of the full 1080p video.
What is your aversion to hosting multiple qualities? Is it about storage space, or complexity/time of conversion?


text:
Q: Will placing a battery in water short circuit it? (Performing electrolysis) I've learned about electrolysis and wanted to try it out but i've popped a couple of batteries by short-circuiting them before messing around with embedded programming so I was curious as I see on youtube videos people just placing both terminals in the water (usually a 9 volt with paper clips)
If it didn't harm the battery I was going to try dip my 10W solar panel terminals in and collect the hydrogen gas.
Complete beginner in everything psychics by the way so if you could, can you explain it to I as a nooby whether or not I will ruin my battery/solar panel.

A: The problem with a short-circuit is that enough current is generated to cause overheating in some part of the circuit.
If you put a paperclip across the terminals of a battery, the element that overheats is usually the battery.
You can measure how much current this is by including an ammeter in your battery-water circuit. If necessary, you can add some resistance to the circuit to limit the current.
You can get a multimeter, which includes an ammeter, from any hardware store for \$10-\$20.
One brand of nine-volt battery will run for about a half-hour at 500 milliamps, or for about a day at 25 milliamps.


text:
Q: stopUpdatingLocation is not working in iOS 7 I have developed both iPhone & iPad application which supports for iOS 5 and iOS 6
in that application i have grabbed user current location using CLLocationManager.
when i want to stop updating receiving GPS coordinates. I have called stopUpdatingLocation
method to stop calling didUpdateToLocation method. It was woking completely fine with iOS 5 and 6 But unfortunately its  not working with iOS 7.
Seems that stopUpdatingLocation method is not working .Any particular reason. ??
i had a keep a variable to monitor the life cycle of didUpdateToLocation method and stop executes it.

A: One thing might be possible is,
Your current location blue dot moving on your map is because you set the MKMapView's showsUserLocation to YES. It will track until you set it to NO.
Second thing,
You might be setting below thing to stop calling that method
locationManager = nil;

That does not stop monitoring, but what it does, not to refer the location manager, So now its not possible to stop monitoring.
Instead add below code & then see what happen
[locationManager stopUpdatingLocation];
locationManager=nil;

Hope it helps..

A: @tdevoy  - Here is sample
  - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations lastObject];
    latitude = location.coordinate.latitude;
    longtitude = location.coordinate.longitude;

    //stops updating current user location update
        [locationManager stopUpdatingLocation];

}


text:
Q: MySQL - Ordering IN within INNER JOIN I'm creating a system that allows a user to search a database of photo albums images for a keyword, it's working great, the only issue is that I'm ordering relevancy by the amount of times that keyword appears in an album. I'm doing this using:
SELECT collections_ids.collection_id
 FROM `keywords`
 INNER JOIN collections_ids ON keywords.id = collections_ids.photo_id
 WHERE keywords.`keyword` = 'trees'
 GROUP BY collection_id
 ORDER BY COUNT(*) DESC

As said, this works great.
The only issue is, when this is included in an "WHERE IN" query, it loses it's order and is returned randomly. For clarity, here is the query:
SELECT collections.id,
       collections.title
       images.img_small
FROM `collections`
INNER JOIN images ON images.id = collections.cover_photo
WHERE collections.`id` IN
    (SELECT collections_ids.collection_id
     FROM `keywords`
     INNER JOIN collections_ids ON keywords.id = collections_ids.photo_id
     WHERE keywords.`keyword` = 'trees'
     GROUP BY collection_id
     ORDER BY COUNT(*) DESC)

I've tried researching, and people have suggested using the FIELD function, but I don't see that working in this context.
Any suggestions?

A: you can use sub query as join and take it count(*) as order by like below
SELECT collections.id,
               collections.title
               images.img_small
        FROM `collections`
        INNER JOIN images ON images.id = collections.cover_photo
        INNER JOIN
            (SELECT distinct collections_ids.collection_id As collection_id,COUNT(*) as total
             FROM `keywords`
             INNER JOIN collections_ids ON keywords.id = collections_ids.photo_id
             WHERE keywords.`keyword` = 'trees'
             GROUP BY collection_id
             ) as A
    ON A.collection_id =collections.collection_id
    order by A.total


text:
Q: How much space is required in my SML code? I have SML code like below.
fun fact(n) =
    let fun f(n,g) = if n=0 then g(1)
                     else f(n-1, fn x=>g(x)*n)
in f(n, fn x=> x) end;

I want to know how much space is required in my code for computing fact(n).
Is it right it requires O(n)? I don't know exactly.

A: Yes, the function you wrote creates n closures before evaluating them at the end.
Here is a more space-efficient version:
fun fact n =
    let fun fact' 0 result = result
          | fact' n result = fact' (n-1) (n*result)
    in fact' n 1 end

It resolves n*result before making a recursive call, rather than delaying it, making it tail-recursive.


text:
Q: Linear forms of $L^1$ I am an engineering student who has unwittingly taken a module in functional anylysis which, unfortunately, is ever so slightly over my head.  I would greatly appreciate if you could either point me in the right direction for the questions below, or at least tell me where I might find some materials which would enlighten me in this area.
So,
$$
\varphi(f)=\int u\times f
$$$$
u\in L^\infty,    f\in L^1
$$
Show that $\varphi(f)$ is a continuous linear form on $L^1$.
Now, if
$$
A=\text{sup}{ \{ |\varphi(f)| \text{ for } f\in L^1 \text{ and } ||f||_1 \leq1 \}}
$$
can $A=\infty$?
Many thanks.

A: To show that $\varphi$ is continuous, you have to show that $A$ is finite. Let $M=||u||_\infty$.
Then for $||f||_1\le 1$:
$$|\varphi(f)|=\biggl|\int uf\,\biggr|\le\int|uf|\le \int  M|f|=M\int |f|=M||f||_1\le M.$$
That $\varphi$ is linear follows from the linearity of integration.


text:
Q: File upload with nextJS and Laravel - $request->hasFile() return false i'm trying to make a file upload with Laravel API and Next.JS front-end, but i don't know why, laravel returnl false everytime i try to call the API with Axios as POST Method.
Here is my front-end code :
const updateCompanyLogo = (e) => {
        setLogo(e.target.files[0])
        let formData = new FormData();
        formData.append("logo", logo);
        axios.post('api/company/logo',
            { formData },
            {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
        ).then((res) => {
            console.log(res)
        }).catch((err) => {
            console.log(err)
        })
        console.log("Change detected")
    }

    <input className=" mt-5 form-control block w-full px-3 py-1.5 text-base font-normal  text-gray-700  bg-gray-200 bg-clip-padding rounded transition ease-in-out h-10 m-0 dark:bg-gray-700 dark:text-white" type="file" id="logo" onChange={updateCompanyLogo} />

public function update_logo(Request $request)
    {
        if($request->hasFile('logo')) {
            return 'found';
        } else {
            return 'not found';
        }
    }

"not found" is the respond i get evrytime.
Thank's for help.

A: You have missed the name attribute in your input field.
<input name="logo" type="file" id="logo" onChange={updateCompanyLogo} />


text:
Q: Is it safe to use incremental rebuild for generating release build in visual C++? I sometimes have issues with the incremental rebuild on visual C++ (2003 currently ). Some dependencies does not seem correctly checked and some files aren't build when they should. I suppose thoses issues come from the timestamp approach to incremental rebuild.
I don't consider it a huge issue when building debug build on my desk, however for distribuable build this is a issue.
Is it safe to use incremental build for a build server or is a full build a requirement ?

A: You need a build you distrubute to be recreatable again should users experience problems that need investigating.
I would not rely on an incremental build. Also, I would always delete all source from the build machine, and fetch it from scratch from the source control system before building a release. This way, you know you can repeat the build process again by fetching the same source code.
If you use an incremental build, the build will build differently each time because only a subset of the system will need to be built. I think its just good to eliminate as many possible differences between release builds as possible. So, for this reason incremental builds are out.
It's a good idea to label or somehow mark the versions of each source file in the source control system with the version number of the build. This enables you to keep track of the exact source that went into building the release. With a decent source code control system the labels can be used to track down all the changes that were made to the code between one release and the next. This can be a real help when trying to track down a bug that you know was introduced between the two releases.
Incremental builds can still be useful on a development machine when you're not distributing the build, just for saving time during the code/debug/test/repeat development cycle.

A: I would always prefer to do a full clean and rebuild for any release for peace of mind if nothing else. Assuming that you're talking about externally released builds and not just builds using the Release configuration, the fact that these builds are relatively infrequent means that any time saving will be minimal in the long run.

A: I'd argue that you should avoid the "is it safe" question. It's simply not worth looking into.
The advantage of incremental builds is the cost saving. Small per build, it adds up for all the debug builds a developer typically makes, and then adds up further for all developers on your team.
On the other hand, release builds are rare. The costs of a release build are not in developers waiting on them, they're found much more in the team of testers that need to validate it.
For that reason, I find that incremental builds are without a doubt cost-saving for debug builds, but I refuse to spend any time calculating the small saving I'd get out of incrementally building a release build.

A: Binaries built using with the incremental build feature are going to be bigger and slower, even for release builds, because they necessarily contain scaffolding to enable the incremental builds that isn't necessary for fully optimized builds. I'd recommend you not to use incremental builds for this reason.


text:
Q: Create shadow root/dom in firefox? I am building Javascript widget that embeded's form on website. I am encapsulating my widget by putting it in shadow dom. It works fine in Chrome but in firefox it does not work at all.

A: You can use the webcomponents.js library in order to polyfill the Shadow DOM features in Firefox, IE and Edge.


text:
Q: Azure DevOps Server as NuGet "proxy" server I have Azure DevOps Server which will run build tasks on workstations without internet connection. The DevOps server itself can connect to internet.
I'm trying to configure Devops server in a way that when the build on one of the workstations needs a Nuget package, the server connects to the internet and downloads it, virtually serving as "proxy server" for build agents which are running on workstations without internet access.
I've configured Nuget feed and created service connection which points to that feed. However, whenever I try to use feed in build tasks, tasks fail either with "timed out" error

The nuget command failed with exit code(1) and error(Unable to load
  the service index for source
  https://**************/_packaging/nuget_feed/nuget/v3/index.json. The
  HTTP request to 'GET
  https://**************/_packaging/nuget_feed/nuget/v3/index.json' has
  timed out after 100000ms.)

or with:

Response status code does not indicate success: 500 (Internal Server
  Error - Failed to retrieve data from the upstream package source
  'https://api.nuget.org/v3/index.json': An error occurred while sending
  the request

Can Azure DevOps Server function as "Nuget package proxy", and, if yes, how can it be configured to perform this task?

A: It happened to me too,
I deleted upstream source and it worked out:

Best regards


text:
Q: How to install NLB on 2 win 7 machines with IIS 7.5 Is it possible to make a load balancing cluster that uses 2 win7 machines with IIS installed.
I want to make a cluster between 2 such machines.
I figured out how to add the Network Load Balancing Manager feature to WIN7 and I am using this tutorial.
Can this be done, because so far by trying to connect to those machines? I haven't managed to make them work as a Win2008Server R2.
The error I receive is :

Could not locate NLB on specified computer.

A: Windows 7 does not support network load balancing. You will need to install a Server OS such as Windows Server 2008, trial versions of which can be found on the Microsoft website.


text:
Q: What is my error in the dated if macro? The value returned is in a a time format Below is the Sub to count the years between 2 dates.  No value is displayed in the cell(i,3) and when i update to a MsgBox a time value is displayed.  Thanks in advance for the help.
Sub EE_DatedIF()
    Dim wb1 As Workbook
    Dim i As Long
    Dim LastRow1 As Long
    Dim yrDiff As Long
    Dim d1 As Date
    Dim d2 As Date

    Set wb1 = Workbooks("macro all client v.01.xlsm")

    LastRow1 = wb1.Sheets("Carrier").range("E:E").Find("", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row

    For i = 10 To LastRow1
        d1 = wb1.Sheets("Settings").Cells(i, 1)
        d2 = wb1.Sheets("Carrier").Cells(i, 24)
        yrDiff = DateDiff("yy", d1, d2)
        wb1.Sheets("Settings").Cells(i, 3) = yrDiff
    Next i
End Sub

A: Among other problems, your attempt to retrieve the last populated row in column E should not be deemed reliable. Better with something closer to this.
With wb1.Sheets("Carrier").Range("E:E")
    lastRow1 = .Find("*", after:=.Cells(1), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
End With


text:
Q: Download Not Working It Just Exits. What's the problem ?
I can't find anything wrong.
If there Is a better Way to download XML to inputstream please let me know.
Or a good way to read 3 or more XMLs simultaneously
package com.some.some;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Bundle;
import android.app.Activity;
import android.util.Base64;
import android.view.Menu;
import android.view.View;

public class Login extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        InputStream stream1 = downloadXmlFileStreamUsingUrl("URL IS CORRECT :|");
        // Parse check is login or not ...
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.login, menu);
    return true;
}
public InputStream downloadXmlFileStreamUsingUrl(final String url) {

    final HttpGet getRequest = new HttpGet(url);
    String encodedStr = Base64.encodeToString("user:pass".getBytes(), 0);
    getRequest.setHeader("Authorization", "Basic " + encodedStr);
    HttpClient client = null;
    try {
      client =  new DefaultHttpClient();
      client.getConnectionManager();
      final HttpResponse getResponse = client.execute(getRequest);
      final int statusCode = getResponse.getStatusLine().getStatusCode();

      if (statusCode != HttpStatus.SC_OK) {
        return null;
      }

      final HttpEntity getResponseEntity = getResponse.getEntity();
      final InputStream content = getResponseEntity.getContent();
      return content;

    } catch (final IOException e) {
      getRequest.abort();
    }
    finally {
          client.getConnectionManager().shutdown();
        }

        return null;

      }

}

A: First thing you have to understand is where we have to perform network operation.
On google developer docs they had explain step by step process here is the link and here is one more important link about network operation we perform.
Because the code you have posted I think your running network operation on main thread.

A: I assume you are getting a NetworkOnMainThreadException because are trying to access the network from UI.
Starting with Android 3.0 the network access should be done on a separate thread. With other words, downloadXmlFileStreamUsingUrl() should run in a separate thread.
You could use an AsyncTask for this purpose.


text:
Q: Laravel Forge - PHP Artisan SQLState error Ive just pushed one of my latest apps to laravel forge and i am getting this error when i try to run php artisan. All environment variables are set correctly in forge so i have no idea where this is coming from.
This app is built in laravel 4.2 there are no local configs as far as i can see and everything works fine locally (use an env file for local use too)
{"error":{"type":"PDOException","message":"SQLSTATE[HY000] [1045]
Access denied for user ''@'localhost' (using password:
NO)","file":"\/home\/forge\/default\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connectors\/Connector.php","line":47}}

database config:
<?php

return array(

/*
|--------------------------------------------------------------------------
| PDO Fetch Style
|--------------------------------------------------------------------------
|
| By default, database results will be returned as instances of the PHP
| stdClass object; however, you may desire to retrieve records in an
| array format for simplicity. Here you can tweak the fetch style.
|
*/

'fetch' => PDO::FETCH_CLASS,

/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/

'default' => 'mysql',

/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/

'connections' => array(

    'sqlite' => array(
        'driver'   => 'sqlite',
        'database' => __DIR__.'/../database/production.sqlite',
        'prefix'   => '',
    ),

    'mysql' => array(
        'driver'    => 'mysql',
        'host'     => getenv('DB_HOST'),
        'database' => getenv('DB_NAME'),
        'username' => getenv('DB_USERNAME'),
        'password' => getenv('DB_PASSWORD'),
        'unix_socket'   => (App::environment('local') ? '/Applications/MAMP/tmp/mysql/mysql.sock' : ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),

),

/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/

'migrations' => 'migrations',

/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer set of commands than a typical key-value systems
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/

'redis' => array(

    'cluster' => false,

    'default' => array(
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ),

),

);

ENV FILE:
SMTP_USERNAME=
SMTP_PASSWORD=
SMTP_FROM_ADDRESS=
SMTP_FROM_NAME=
DB_HOST= SERVER IP
DB_NAME=
DB_USERNAME=
DB_PASSWORD=

Thanks

A: As the error says:

SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using
  password: NO)

You must have a misconfiguration in your database config. You're not specifying any user for the connection and no password.
You should have a .env.php file in your project's folder for the configuration to parse the values.


text:
Q: If $S=A[T_0,\cdots,T_d]$, $X=\operatorname{Proj}S$, then $O_X(n)(X)=S_n$ if $n\geq0$, $0$ otherwise. Here, $A$ is just some ring, $d>0$
In the following, $O_X(n)=\widetilde{S(n)}$, and $S(n)$ is $S$ with the graduation shifted (i.e. $S(n)_d=S_{n+d})$
and $S_{(f)}$ are elements of degree $0$ of $S_f$, i.e. elements of the form $\frac{P}{f^k}$ with $\operatorname{deg}P=k\operatorname{deg}f$
I have a proof I don't understand of this fact.
First I don't get why I can't just say that $O_X(n)(X)=\widetilde{S(n)}(D_+(1))=S(n)_{(1)}=S_n$ for all $n$ (and in particular, $S_n=0$ for negative degree since I assume the convention is that the only polynomial of negative degree is $0$, and we would be done. The proof I read is more involved and I don't get it.
Secondly, the proof is the following:
Let $B=A[T_0,\cdots,T_d,T_0^{-1},\cdots,T_d^{-1}]$, then a global section of $O_X(n)(X)$ is an element $f$ of $T_1^nO_X(D_+(T_1))$, so $f$ is of the form $P/T_1^m$
Why?
Then it concludes using the same argument with $T_0$ to deduce that $f$ has to be some homogeneous polynomial of degree $n$.
I understand that a section of $O_X(n)(X)$ restricted to $D_+(T_1)$ yields something of the form $\frac{P}{T_1^k}\in S(n)_{(T_1)}$ with $\operatorname{deg'}P=k\operatorname{deg'}T_1$, but here $P$ has degree $\operatorname{deg'}P=\operatorname{deg}P-n$ because of the shift, I mean, $P$ lies in $S(n)_{\operatorname{deg}P-n}=S_{\operatorname{deg}P}$.
If for some reason, $T_1$ still has degree $1$ then the argument in the proof makes sense in that we must have $k=\operatorname{deg}P-n$ to compensate $\operatorname{deg'}P$, so $\frac{P}{T_1^k}=T_1^n\frac{P}{T_1^{\operatorname{deg}P}}\in T_1^nO_X(D_+(T_1))$
but if $P$ has its degree shifted in $S(n)$, why wouldn't it be the same for $T_1$? Why isn't the degree of $T_1$ $1-n$? If it is the case then the argument does not make sense, we would need $\operatorname{deg}P-n=k(1-n)$ and I don't even know if such a $k$ exists now. Could somebody please clear that up?

A:
First I don't get why I can't just say that $O_X(n)(X)=\widetilde{S(n)}(D_+(1))=S(n)_{(1)}=S_n$ for all $n$ (and in particular, $S_n=0$ for negative degree since I assume the convention is that the only polynomial of negative degree is $0$, and we would be done. The proof I read is more involved and I don't get it.

The statement that for $M$ a graded module over a graded ring $S$, the sections of $\widetilde{M}$ on $\operatorname{Proj} S$ over the open set $D(f)$ are equal to $M_{(f)}$ is only guaranteed by the construction of $\operatorname{Proj}$ when $f$ is of homogeneous of positive degree. $1$ is not of positive degree.
As for your confusions on the provided proof, let's recall a few definitions first so that we can be sure we're all on the same page.

Definition: Let $S$ be a graded ring and $M$ a graded $S$-module. Then for $f\in S$ homogeneous of positive degree, the sections of $\widetilde{M}$ on the open set $D(f)$ are exactly $M_{(f)}$, the degree-zero elements of the localization of $M$ at the multiplicative set $\{f,f^2,f^3,\cdots\}$.

In particular, this means that if $m\in M_d$ and $f\in S_1$, then $\frac{m}{f^d}$ is an element of $M_{(f)}$.
Now we get to your trouble. You write:

I understand that a section of $O_X(n)(X)$ restricted to $D_+(T_1)$ yields something of the form $\frac{P}{T_1^k}\in S(n)_{(T_1)}$ with $\operatorname{deg'}P=k\operatorname{deg'}T_1$, but here $P$ has degree $\operatorname{deg'}P=\operatorname{deg}P-n$ because of the shift, I mean, $P$ lies in $S(n)_{\operatorname{deg}P-n}=S_{\operatorname{deg}P}$.
If for some reason, $T_1$ still has degree $1$ then the argument in the proof makes sense in that we must have $k=\operatorname{deg}P-n$ to compensate $\operatorname{deg'}P$, so $\frac{P}{T_1^k}=T_1^n\frac{P}{T_1^{\operatorname{deg}P}}\in T_1^nO_X(D_+(T_1))$
but if $P$ has its degree shifted in $S(n)$, why wouldn't it be the same for $T_1$? Why isn't the degree of $T_1$ $1-n$? If it is the case then the argument does not make sense, we would need $\operatorname{deg}P-n=k(1-n)$ and I don't even know if such a $k$ exists now. Could somebody please clear that up?

Here it is important to remember that $T_1$ has in general different degrees considered as an element of $S(n)$ versus $S$. We know $T_1\in S_1$, which is the degree-$1$ piece of $S$, but the degree $1-n$ part of $S(n)$. This confusion between the degree of $T_1$ in the ring and the module appears to be a major source of your issues. You also appear to have a strange idea about what $\deg P$ ought to be.
Let's refer back to the comment after the definition and get things correct. The statement $\frac{P}{T_1^k}\in S(n)_{(T_1)}$ means that we should have $P\in S(n)_k$, which is to say that $P\in S_{n+k}$ by the definition of $S(n)$. So $P$, viewed as an element of $S$, is a homogeneous polynomial of degree $n+k$.


text:
Q: Form of notice to indicate children's prices, and those that are free of cost Our company finds it difficult to word the notice indicating that infants under certain ages are either "free" or go at "half-price".
What should we use?
"Free child age?" or ...? we're not native english talker so it make it lot harder...
thank you
I'm not sure what tags should be used. I will leave it up to the moderator to decide if more should be added.

Edit
As people suggested, i moved the question to: https://ell.stackexchange.com/questions/155126/form-label-to-indicate-childrens-prices-group-and-those-that-are-free-of-cost

A: Just put:
KIDS (maximum age) &  UNDER 1/2 OFF
edit:  actually if you're looking for the shortest word count possible you could even get away with taking kids off.
Example:  10 & UNDER 1/2 OFF

A: I think I've cracked it.
Age**:
That's it.
The * symbol indicates a requirement, even though there are age requirements for free or half price it doesn't make sense for the key value entry
The double ** symbol indicates special conditions, and everyone knows to look at the bottom to understand what ** means.   We use the expression 'reading the fine print'


text:
Q: laravel where condition for related eloquent I have to Models User and UserAttr
User is like :

id
name

1
john

2
doe

UserAttr is like

id
user_id
job

1
1
seller

2
2
teacher

them relation is :
for user :
    //User MODEL
    public function UserAttr(){
        return $this->hasOne(UserAttr::class);
    }

for UserAttr :
    //UserAttr MODEL
    public function UserAttr(){
             return $this->belongsTo(User::class);
    }

Inside of controller i want to return this
Return all Users Where They job is Seller
i try
$users = User::where(User::UserAttr()->where('job','teacher'));
return $users;

but it not works

A: First, 'where' requires two arguments. where('column', 'value'). Second, until you use a function dedicated for returning the results, like find(1), first(), get(), you will always get a builder object.
In this particular case, you need to query the relationship. Something like this should work for you.
User::with('userAttr')->whereHas('userAttr', function($query){
   return $query->where('job', 'teacher');
})->get();

For reference:
https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence


text:
Q: Method in session scoped bean returns null for non-null field When I am trying to get the value from the bean (annotated @SessionScoped) using method getContractNumber() I am getting null. However, when directly accessing the field parameters.contractNumber the result is the correct value from request. I understand that JavaEE is proxying my bean object and in this case I would have expected the reversed effect. How can I access my bean field value? I don't want to use the field directly.
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.Serializable;

import static org.apache.commons.lang3.StringUtils.isNotBlank;

public class InitialRequestParametersFilter implements Filter {

    @Inject
    private Provider<InitialRequestParameters> parameters;

    @SessionScoped
    public static class InitialRequestParameters implements Serializable {
        private String contractNumber = null;

        InitialRequestParameters() {}

        private void setContractNumber(String contractNumber) {
            this.contractNumber = contractNumber;
        }

        public Optional<String> getContractNumber() {
            return Optional.fromNullable(contractNumber);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        final String contractNumberFromRequest = servletRequest.getParameter("contractno");
        if(isNotBlank(contractNumberFromRequest)) {
            parameters.get().setContractNumber(contractNumberFromRequest);
        }
        // this returns the request parameter
        System.out.println(parameters.get().contractNumber);
        // this returns Optional.absent() !!!
        System.out.println(parameters.get().getContractNumber());
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
    }
}


text:
Q: show image in div on click not working I am new to jquery and javascript. I want some picture in a div to change on click on another picture. I did look around here and found something similar to what i want but can't seem to make it work.
Here is my code:

<TITLE></TITLE>

You can see it life here: http://www.thebruises.be/TEST/test.html
But as I said above it doesn't work; tried moving the ... inside the body but doesn't change anything.
Any help would be appreciated ... and as I mentionned above I has zero javascript/jquery skills.
Thx

A: you're using the same id for all  tags. an ID has to be unique within the page  your javascript is applying the on click function only to the first image
change id to class and your code should work
your code should look like this:

...

A: Change your id="changeImage" to class="changeImage" since id is unique.
Then you can use each to iterate over all of your anchors with class changeImage:
$('.changeImage').each(function() {
    $(this).click(function(){
        var rel = $(this).attr('rel');
        $("#imageBox img").attr('src', 'image' + rel + '.jpg');
    })
});

Copy and paste this to your jQuery code:
$(document).ready(function(){
    $('.changeImage').each(function() {
        $(this).click(function(){
            var rel = $(this).attr('rel');
            $("#imageBox img").attr('src', 'image' + rel + '-thumb.jpg');
        })
    });
});

Demo


text:
Q: How do I create a dataset in VB.NET from this code? I currently have the following code in my project which populates a DataGridView object with the results of an SQL query.
Sub PerformQuery(ByVal SQLText As String)
    Dim DbConnection As New OleDb.OleDbConnection(createConnectionString)

    Dim SQLQuery As String = SQLText

    Dim Adapter As New OleDb.OleDbDataAdapter(SQLQuery, DbConnection)

    Try
        Using Table As New DataTable
            Adapter.Fill(Table)
            Table.Locale = Globalization.CultureInfo.InvariantCulture
            DbConnection.Close()
            DataGridView1.DataSource = Table
        End Using
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
End Sub

Elsewhere in my project I can create a DataSet object using the code
Dim ds As New DataSet

And then extract data from it using code like:
MaxRows = ds.Tables("Dataset_Users").Rows.Count

Rather than populating a DataGridView, how can I use the PerformQuery code to create a dataset?
Thank you in advance for your help.

A: I think you are after the following:
Try
    Dim ds As New DataSet
    Using Table As New DataTable
        Adapter.Fill(Table)
        Table.Locale = Globalization.CultureInfo.InvariantCulture
        DbConnection.Close()
        DataGridView1.DataSource = Table
        ds.Table.Add(Table)
    End Using
Catch ex As Exception
    MsgBox(ex.Message)
End Try

Or as in your example you was after the Number of rows in the dataset you can do the same with the DataTable, For Example:
Try
    Dim MaxRows As Integer
    Using Table As New DataTable
        Adapter.Fill(Table)
        Table.Locale = Globalization.CultureInfo.InvariantCulture
        DbConnection.Close()
        DataGridView1.DataSource = Table

        '' Getting the number of rows in the DataTable
        MaxRows = Table.Rows.Count
    End Using
Catch ex As Exception
    MsgBox(ex.Message)
End Try

A: Think in a more functional style. Return the table instead of setting to grid. While we're here, let's update the method so you don't have to write queries anymore that leave you wide open to sql injection attacks:
Function PerformQuery(ByVal SQLText As String, ByVal ParamArray Parameters() As OleDbParameter) As DataTable
    Dim result As New DataTable()

    Using cn As New OleDb.OleDbConnection(createConnectionString), _
          cmd As New OleDb.OleDbCommand(SQLText, cn), _
          Adapter As New OleDb.OleDbDataAdapter(cmd, cn)

        If Parameters IsNot Nothing AndAlso Parameters.Length > 0 Then
            cmd.Parameters.AddRange(Parameters)
        End If
        Adapter.Fill(result)
    End Using

    Return Result
End Function

Note that I also removed the error handling and locale code. You still need to do that stuff, but when you want to just return a datatable instead of interact directly with the user interface in a method you have effectively moved your code to a lower level of abstraction. When you do that, you probably don't want to deal with the error handling at this lower level any more; instead let the exceptions bubble up where you can handle them closer to the user interface.
Now you call the updated method like this:
Dim sql As String = "SELECT * FROM Customers WHERE CustomerID = ?"
Dim CustID As New OleDb.OleDbParameter("CustomerId", OleDbType.Integer)
CustID.Value = 123456

Try
    DataGridView1.DataSource = PerformQuery(sql, CustID)
Catch Ex As Excpetion
    MsgBox(Ex.Message)
End Try


text:
Q: No package information is being reported to landscape Hi I have recently added some new machines to our infrastructure.
I was able to register the computers with the UI, I can see CPU information, process etc.
However I still see:
2 computers have not reported package information

No packages.
I have followed and check information found on the page: https://help.landscape.canonical.com/FAQ#No_packages

There can be several situations where the server will report no
  installed or available packages for a Landscape client:
bug: please make sure you are running the latest version of the
  landscape-client package. Run a apt-get update && apt-get install
  landscape-client session. the client machine was recently added to
  Landscape: it can take up to 1h30min for a new Landscape client
  machine to start uploading package information the client machine has
  no access to Ubuntu package repositories for some reason, cron is
  disabled on the client machine. Please make sure it's working properly
  If you still have problems with packages not showing up in the web
  interface, please use the Feedback option to report it to us.

The machines affected

*

*running landscape-client version:15.06+bzr823-0ubuntu0~ubuntu14.04.1

*Can access the Ubuntu repositories

*Do have cron running.

*Have been up and running for a few days.

Any ideas how to troubleshoot the issue further?


text:
Q: JAPE grammar sentence boundaries in GATE please if I need to specify to check the pattern if it in one sentence or not?
My patterns are:
{person}
{Token}*
{Token.string = "call"}
{Token}*
{person}
to be in one sentence.
how could I do this please using JAPE
Thank you


text:
Q: I'm trying to make a live updating Heatmap, but jupyter-dash freezes, errors appear, and then the jupyter kernel dies I am trying to make a live updating heatmap using Jupyter Dash. My main requirement is that dash works equally well with both small dataframes and large ones (several million elements).
So I decided that the application should be as simple as possible. An example of my code implementation is below:
# Build App
app = JupyterDash(__name__)
app.layout = html.Div(
    [
        dcc.Graph(id="heatmap", animate=True),
        dcc.Interval(id="interval-component", interval=1*1000),
    ],
)

@app.callback(Output('heatmap', 'figure'),
              Input("interval-component", "n_intervals"))
def doUpdate(i):
    traces = list()
    traces.append(go.Heatmap(z=data.get_result_for_plot(),
                             colorscale='RdBu'))
#   data.get_result_for_plot() just returns new version of np array
    return {'data': traces}

However the code doesn't work correctly and first of all the following error pops up: Callback error updating heatmap.figure, and then another one: Error from API call: _reload-hash. On top of that the jupyter kernel dies.
So I have several questions:

*

*what did I do wrong in my implementation?

*Is there any way to improve this code?
For example, I would like to create a figure outside of doUpdate() function and update only z coordinate, to reduce load.

I would be very glad to get advice on these issues. Thanks!