text:
Q: Can you have debs without compression? I'm in the middle of doing an upgrade on a really slow machine. It's an Intel Atom that's a few years old. It's perfect for watching video and using XBMC but it really honks at decompressing hundreds of updates (like you do in a release upgrade). I've got another upgrade to do on this once this one completes.
I mused to the General Chat room today that it would be cool if I could proxy those package downloads through a faster local server that could proxy the requests, decompress the packages and pass them on.
So still in planning, I have a few questions:

*

*Is is possible to have a deb package that isn't compressed?

*How can I remove the compression from a deb?

*Will removing the compression knacker the checksums and if so, how do I fix that?

A: 1) Not really, no. You can theoretically use the lowest level compression at build-time of the debs, but the Ubuntu builders don't do this. The slow part is probably not the decompression, but the unpacking of files and writing them to disk. Several things can affect disk I/O times here, including BIOS settings, drive rotational speed, and drive type. You could theoretically have the data archive inside the deb be data.tar though it would still have slight compression (or inflation), and wouldn't help with the speed of writing to disk.
2) See 1).
3) Yes, it would, if you were to take a binary deb and replace the data.tar.gz inside it, the size, timestamp, etc… would change. To be able to do something, you'd need to do it at build time of the deb package.
On the other hand, as I said, the speed issue is probably writing to disk. You can check your BIOS to change some settings for the disk. If your using a SATA disk, and your BIOS is set to communicate with it as IDE/ATAPI, then read/write speed is going to be extremely slow. Change the setting to AHCI if avaialble. Another common issue is disk RPM if you're not using an SSD. You didn't specify what size or RPM disk you are using, but a 2.5" 4500-5400 RPM disk is going to be slower than a 3.5" disk that does anywhere between 7200-15000 RPM. And a SATA I (1.5Gbps) disk is going to be slower than a SATA II (3.0 Gbps) or III (6.0 Gbps) disk. Disk cache size also plays an important role here. You also didn't say which Atom you had, or how much RAM, but they aren't as slow as one might think. They aren't a top shelf i7, but the amount of compression used in deb packages is not generally a problem for them.

A: For stripping the compression here's what I've come up with (this by no means answers anything else):
ar vx debianutils_4.3.4_amd64.deb
gunzip data.tar.gz
ar d debianutils_4.3.4_amd64.deb data.tar.gz
ar q debianutils_4.3.4_amd64.deb data.tar

The package is bigger. The checksums are completely off... But it's still a valid package, sans compression.


text:
Q: Regression with random input variables Take a black-box model which is expensive to evaluate. Say you have $N$ observations of this black-box model denoted $\{Y_i\}_{i=1,\ldots,N}$ at the points $\{X_i\}_{i=1,\ldots,N}$. We take an input of dimension one to simplify the problem. You know that the input $X$ follows Normal distribution $\mathcal{N}(0, 1)$. From these $N$ observations, you want to build a predictor in order to obtain a prediction at an unobserved point $x^{\star}$ through Gaussian Process Regression, for instance.
Now my question. You have the choice to pick where the points $\{X_i\}_{i=1,\ldots, N}$ are. Assume that you choose an LHS experiment design. I know that the basic LHS experiment design gives you points that follow a uniform distribution. Should you use the basic LHS experiment design or change it so that they follow a Normal distribution?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rectangular printer prgram
*

*Prompt the user for the height and width of a rectangle that will be displayed as rows and columns of asterisk (*) characters.

*Using your knowledge of loops, generate the rectangle output. The height will be the number of rows and the width will be the number of characters in each row. Since your output will be generated one row at a time, make sure you complete each row before moving on to the next.

*Modify your program so that it generates only the outside border of a rectangle rather than a filled rectangle.
I dont know how to get the asterisks to line up in rows and columns.
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

        int width;
        int height;

        Scanner input = new Scanner(System.in);

        System.out.print("Enter the width:");
        width = input.nextInt();
        System.out.print("Enter the height:");
        height = input.nextInt();
        int y = 0;
        for (int x = 0; x <= width; x++){
            System.out.println("*");
            while (y <= height){
                y++;
                System.out.println("*");
            }
        }
    }
}

I am trying to get an output that looks something like this for width = 4 height = 4
****    ****
****    *  *
****    *  *
**** or ****

A: A few tips to help you figure this out:

*

*println() always prints a newline character after the value you pass in. You probably only want that at the end of each line, not after each character.

*You don't need a while loop - you can do all of this work using two for loops.

*Break down what you need to achieve into smaller chunks and solve each chunk separately.
For example, a solid square (written as an algorithm, not as code):
loop y once for each row {

    loop x once for each column in that row {

        print a '*' character

    }

    print a newline character (because we have finished the row)

}

For example, a hollow square (written as an algorithm, not as code):
loop y once for each row {

    loop x once for each column in that row {

        if the current position is in the first row, last row, first column or last column
            print a '*' character
        otherwise
            print a ' ' character
    }

    print a newline character (because we have finished the row)

}


text:
Q: Reading data from USB Port currently I am working on a project for university where i have to create a program which controls the humidity in a terrarium.
On this purpose i've got an hygrometer.
First of all the program has to import the raw data from the hygrometer, but i have no idea how it works.
The documentation says there is an USB interface for it, but i can only find the way how to parse the raw data.
I also wrote an Email to the company which sells this hygrometer. They said theres an external software which imports and handle with this data. However I am not allowed to use external softwares.
Therefore I am forced to read the raw data directly from the USB Port. I tried to work with usb4java but i was only able to find all connected usb devices.
I have no idea how to go on. Please help me
documentation
documentation
Code below
public class DumpDevices
{
/**
 * Dumps the specified USB device to stdout.
 *
 * @param device
 *            The USB device to dump.
 */

private static void dumpDevice(final UsbDevice device)
{
    // Dump information about the device itself
    System.out.println(device);
    final UsbPort port = device.getParentUsbPort();
    if (port != null)
    {
        System.out.println("Connected to port: " + port.getPortNumber());
        System.out.println("Parent: " + port.getUsbHub());
    }

    // Dump device descriptor
    System.out.println(device.getUsbDeviceDescriptor());

    // Process all configurations
    for (UsbConfiguration configuration: (List<UsbConfiguration>) device
        .getUsbConfigurations())
    {
        // Dump configuration descriptor
        System.out.println(configuration.getUsbConfigurationDescriptor());

        // Process all interfaces
        for (UsbInterface iface: (List<UsbInterface>) configuration
            .getUsbInterfaces())
        {
            // Dump the interface descriptor
            System.out.println(iface.getUsbInterfaceDescriptor());

            // Process all endpoints
            for (UsbEndpoint endpoint: (List<UsbEndpoint>) iface
                .getUsbEndpoints())
            {
                // Dump the endpoint descriptor
                System.out.println(endpoint.getUsbEndpointDescriptor());
            }
        }
    }

    System.out.println();

    // Dump child devices if device is a hub
    if (device.isUsbHub())
    {
        final UsbHub hub = (UsbHub) device;
        for (UsbDevice child: (List<UsbDevice>) hub.getAttachedUsbDevices())
        {
            dumpDevice(child);
        }
        System.out.println(hub);
    }
}

/**
 * Main method.
 *
 * @param args
 *            Command-line arguments (Ignored)
 * @throws UsbException
 *             When an USB error was reported which wasn't handled by this
 *             program itself.
 */
public static void main(final String[] args) throws UsbException
{
    // Get the USB services and dump information about them
    final UsbServices services = UsbHostManager.getUsbServices();
    System.out.println("USB Service Implementation: "
        + services.getImpDescription());
    System.out.println("Implementation version: "
        + services.getImpVersion());
    System.out.println("Service API version: " + services.getApiVersion());
    System.out.println();

    // Dump the root USB hub
    dumpDevice(services.getRootUsbHub());
}

A: I think usb4java is very good but quite complex. You might accomplish reading data from usb port very easily with jssc
Example of reading data from usb:
SerialPort serialPort = new SerialPort("/dev/tty.usbmodem1435");
serialPort.openPort();//Open serial port
serialPort.setParams(4800, 8, 1, 0);//Set params.
while(true) {
    byte[] buffer = serialPort.readBytes(10);
    if(buffer!=null) {
        for(byte b:buffer) {
            System.out.print(b);
        }
    }
}

Notice that '/dev/tty.usbmodem1435' is just an example name, you should use the port name you are interested on.
Hope it helps.


text:
Q: 1 request exchange, 1 reply exchange, N number responses I want to push out 1 response and wait X milliseconds for N responses based on a correlation ID in the headers.
Current code is pretty simple: Send a call then start polling indiscriminately. That works ... for one call.
I know there is talk of a JMS solution ("JMSReader?") that spawns N number of listeners looking for correlation ID allowing these futures to time out, but I am not finding anything remotely related.

A: Here is a demo app that shows one way to do it...
@SpringBootApplication
public class So57377491Application {

    public static void main(String[] args) {
        SpringApplication.run(So57377491Application.class, args);
    }

    private final ConcurrentMap<String, List<String>> pending = new ConcurrentHashMap<>();

    private final ConcurrentMap<String, SettableListenableFuture<List<String>>> futures = new ConcurrentHashMap<>();

    @Bean
    public ApplicationRunner runner(RabbitTemplate template) {
        return args -> {
            this.pending.put("bar", new ArrayList<>());
            this.futures.put("bar", new SettableListenableFuture<>());
            template.convertAndSend("so57377491", "", "Foo", msg -> {
                msg.getMessageProperties().setCorrelationId("bar");
                msg.getMessageProperties().setReplyTo("replyExchange/so57377491-replies");
                return msg;
            });
            try {
                List<String> list = this.futures.get("bar").get(5, TimeUnit.SECONDS);
                System.out.println(list);
            }
            catch (TimeoutException toe) {
                System.out.println("Partial result after timeout " + this.pending.remove("bar"));
            }
            finally {
                this.futures.remove("bar");
            }

        };
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "so57377491-1"),
            exchange = @Exchange(value = "so57377491", type = "fanout")))
    public String listen1(String in) {
        System.out.println(in);
        return in.toUpperCase();
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "so57377491-2"),
            exchange = @Exchange(value = "so57377491", type = "fanout")))
    public String listen2(String in) {
        System.out.println(in);
        return in.toLowerCase();
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "so57377491-3"),
            exchange = @Exchange(value = "so57377491", type = "fanout")))
    public String listen3(String in) {
        System.out.println(in);
        return in + in;
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "so57377491-replies"),
            exchange = @Exchange(value = "replyExchange", type = "fanout")))
    public void replies(String in, @Header(AmqpHeaders.CORRELATION_ID) String correlationId) {
        System.out.println(in);
        List<String> list = this.pending.get(correlationId);
        if (list == null) {
            System.out.println("Late reply for " + correlationId);
        }
        else {
            list.add(in);
            if (list.size() == 3) {
                this.futures.get(correlationId).set(list);
                this.pending.remove(correlationId);
            }
        }
    }

}

Result
Foo
Foo
Foo
foo
FOO
FooFoo
[foo, FOO, FooFoo]


text:
Q: Error getting Google Plus Profile when authenticating with Google ID Token When I try getting The Google plus profile information using the following code,
$client = new Google_Client();
$client->setClientId(Config::get('services.google.clientId'));
$client->setClientSecret(Config::get('services.google.clientSecret'));
$client->setRedirectUri(Config::get('services.google.redirectUri'));
$client->setScopes(['profile', 'login' ]);

$id_token = $this->request->input('idToken');

$token_data = $client->verifyIdToken($id_token)->getAttributes();

$googlePlus = new Google_Service_Plus($client);
$userProfile = $googlePlus->people->get('me');

I get the error saying
exception 'Google_Service_Exception' with message 'Error calling GET https://www.googleapis.com/plus/v1/people/me: (403) Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.' in /home/bepolite/websites/goodies/vendor/google/apiclient/src/Google/Http/REST.php:110

This code used to work before and I changed nothing on my end.
Also I am using the official google php api which I downloaded using composer
"google/apiclient": "^1.1"
Thanks In advance


text:
Q: Java: How to write computing data in arraylist? Hello guys I'am beginner of the Java and i've got some problems with array&arraylist. My main problem is how to write computing, dynamic data into the array and later how to read it? Here's my weird code:
    public static void main(String[] args) {

    int yil, bolum = 0, kalan;
    Scanner klavye = new Scanner(System.in);
    ArrayList liste = new ArrayList();

    //or shall i use this? >> int[] liste = new int[10];

    System.out.println("Yıl Girin: "); // enter the 1453
    yil = klavye.nextInt();

    do{ // process makes 1453 separate then write in the array or arraylist. [1, 4, 5, 3]

    kalan = yil % 10;
    liste.add(kalan); //my problem starts in here. How can i add "kalan" into the "liste".
    bolum = yil / 10;
    yil = bolum;

    }while( bolum == 0 );

    System.out.println("Sayının Basamak Sayısı: " + liste.size()); //in here read the number of elements of the "liste"
    klavye.close();
}

Edit:
    //needs to be like that
    while( bolum != 0 );
    System.out.println("Sayının Basamak Sayısı: " + liste);

A: I think that you most likely want your loop stopping condition to be:
while( bolum != 0)

because bolum will only be 0 when there are no more digits left in your number to process. Also, as amit mentions above it could be the case that the user entered 0 when prompted for a number, so you should take that into account.

A: To obtain a string representation of your ArrayList (showing the elements it contains through their string representations), you can just use
System.out.println("Sayının Basamak Sayısı: " + liste);

No need to convert to an array. This works because it causes liste's toString method to be called (which is why we don't need to call it explicitly).

A: You must change this line:
}while( bolum == 0 );

To this:
}while( bolum > 0 );

A: If you want to print your elements in the ArrayList, update your last statement to print as below:
  System.out.println("Sayının Basamak Sayısı: " + liste);

Or you can iterate your list and print as :
 for(Object i: liste){
    System.out.println(i);
 }

This will print your individual list items in separate lines.
Also please fix your while condition as while(bolum != 0); as it may terminate after the very first iteration as bolum will be non zero i.e.  1, 2...(!= 0).


text:
Q: can not connect to the Internet via ssh I want to ssh to a server and run a docker command in it. I can run docker command locally on my pc but when I connect to the server it shows this error:
Unable to find image 'hello-world:latest' locally docker: Error response from daemon: error parsing HTTP 408 response body: invalid character '<' looking for beginning of value: "
408 Request Time-out
\nYour browser didn't send a complete request in time.\n\n". See 'docker run --help'.
What should I do?
Thank you in advance.
I thought maybe it is a proxy issue but I disabled them all and got the error again.


text:
Q: htaccess hide subdirectory name and show only parameter I wanted to hide the subdirectory name and show only parameter in my localhost so example.com refers to localhost
http://example.com/Main-folder/directory/profile.php?name=Anup
I wanted this url to show as:
http://example.com/Main-folder/Anup
please give me a simple 3-4 line of code (if possible)

A: Try:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^Main-folder/(.*)$ /Main-folder/directory/profile.php?name=$1 [L]


text:
Q: Laravel's Illuminate paginator can't find query string I'm working on a old PHP project, that is running in legacy SQL query, which is good but I like to use query builders like Laravel Illuminate SQL package!
So i have added all required package dependencies to run Illuminate SQL, and this query builder seems to work fine with pagination!
$users = Capsule::table('users')->paginate(1)->toArray();

But, the paginator seems not to be able to listen the query string! For example, by running the above code it would give some properties like, next_page , previous_page etc...

And when I try to pass the query string in the URL it can't fetch the data from query string(From the GET request)!
Visiting this page http://app.app/?page=2 would give the same result set.
How i should configure the Illuminate sql package so it can also listen to the query strings?
EDIT
Also, i've tried to use the illuminate/http package, but the $request->all() method always returns an empty array! Here is the code:
<?php
  require_once './vendor/autoload.php';
  use \Illuminate\Http\Request;

  $req = new Request();

  echo '<pre>';
  print_r($req->all());
  echo '</pre>';

It returns empty input data array,

What i am missing to use the http package, any idea would be helpful.

A: You have to set a page resolver:
\Illuminate\Pagination\Paginator::currentPageResolver(function ($pageName = 'page') {
    return (int) ($_GET[$pageName] ?? 1);
});

Laravel uses this resolver.

A: You need to notice, that paginator won't use other parameters for query string - it just uses page parameter to get valid results page. But for example if you use:
http://app.app/?page=2&price=2

it won't take from database results with price = 2 - it's your job to do this.
However the 2nd thing are urls generated by paginator.
If you do it like this:
$users = Capsule::table('users')->paginate(1);

You can also use in next line
$users->appends(request()->except('page'));

This will add all other parameters from query string (except page) to urls, so first_page_url will then contain all other parameters from request.
You can also wrap it using fluent syntax like this:
$users = Capsule::table('users')->paginate(1)->appends(request()->except('page'));

A: *

*You need to fetch the query string in the controller to pass the get parameter to
paginate.

*You can use the Illuminate\Http\Request class to receive and use the HTTP payload.
Your controller file:
<?php

use Illuminate\Http\Request;
class YourControllerClassName{
    public function someFunction(Request $request){
         echo "<pre>";
         print_r($request->all());
         print_r($request->input('page'));
         $users = Capsule::table('users')->paginate($request->input('page'))->toArray();
    }
}


text:
Q: Google line chart doesn't show Y axis labels inside a bootstrap modal I am trying to display a line chart within a bootstrap modal but I noticed that I can't display the labels of Y axis of it, if I place it inside a modal. Any idea how can I fix that?
Here is a basic demo:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>


text:
Q: Regex get specific words I need to get this regex to work but cant figure it out.

random

random

Föredrar att inte uppge

Random means random data and I want just the last tag data and it can be diffrent amount of tags aswell so every thing between the last "<li" and "Föredrar att inte uppge"


text:
Q: How to convert to date format when varchar2(7) value are being passed when there is variation? So I'm being passed data in varchar2(7) format that i need to convert into date format and then in insert in my trigger. I know that the function to_Date(date, 'dddyyyy') exists but there are  values that are in both dddyyyy and ddyyyy format. I've tried the following but still getting a 'day of month must be between 1 and last day of month' error. My code is below:
Insert into Submission
(RESPONDENT_ID, SUBMISSION_DT, SUBMISSION_TYPE_ID, SUBMISSION_NAME_TX, SUBMISSION_SEQ_NB, CREATE_DT, CREATE_USER_ID, MODIFY_DT, MODIFY_USER_ID, EFFECTIVE_DT, INACTIVE_DT)
VALUES
('2527451', CASE WHEN :new.data_date > 99999 then To_Date(:new.data_Date, 'dddyyyy') ELSE To_Date(:new.data_Date, 'ddyyyy') END, '1', '20190418', '0', sysdate, '1', null, null, null, null);

sample data for data_date:
612014 3652014 012015

desired result:
Mar-02-2014 (3/1/YYYY for leap year), Dec-31-2014 (Dec-30 for leap year), Jan-01-2015.

So my question is, even with the LPAD method, there are 9 days in the calendar year that are not accounted for (1YYYY - 9YYYY to be exact). What do i do for these dates? the dates are in varchar format so I can't use a operational conditional statement (i.e. CASE WHEN :new.data_date <= 10000 THEN to_date(lpad(:new.data_Date, 7, '00'), 'DDDYYYY')

A: How about just padding the number on the left?
Insert into Submission (RESPONDENT_ID, SUBMISSION_DT, SUBMISSION_TYPE_ID, SUBMISSION_NAME_TX, SUBMISSION_SEQ_NB, CREATE_DT, CREATE_USER_ID, MODIFY_DT, MODIFY_USER_ID, EFFECTIVE_DT, INACTIVE_DT)
    values ('2527451',
            to_date(lpad(:new.data_Date, 7, '0'), 'DDDYYYY'),
           '1', '20190418', '0', sysdate, '1', null, null, null, null
           );

Note:  If values in the table are numbers, then do not use single quotes for their values.


text:
Q: Mat-select arrow to transform on dropdown (up and down) I have a mat-select dropdown icon arrow that is faced down and when I click it transforms faced up and opens the dropdown options, and when I click on the arrow again, it closes the dropdown facing down again, so far so good, but when I select one of the options and it closes the dropdown with the option selected, the arrow doesn't face down again, unless I hold the click on the option.
I've been trying to use :focus for this transformation but I do not seem to figure out how to make it work properly.
I'm using this dropdown: https://material.angular.io/components/select/overview
(without the 'mat-form-field' in Angular 8)
My SCSS:
::ng-deep .mat-select-arrow {
  border-left: 15px solid transparent !important;
  border-right: none !important;
  border-top: 15px solid transparent !important;
  background-image: url(../../assets/icons/Icon_dropdown_Arrow_bottom.svg) !important;
  background-image: no-repeat !important;

  -webkit-transition-duration: 0.3s;
    -moz-transition-duration: 0.3s;
    -o-transition-duration: 0.3s;
    transition-duration: 0.3s;

    -webkit-transition-property: -webkit-transform;
    -moz-transition-property: -moz-transform;
    -o-transition-property: -o-transform;
    transition-property: transform;
}

:focus {
  &::ng-deep .mat-select-arrow {
    transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
  }
}

This code transforms the arrow icon that was down to up, but when I click to select the option, it doesn't get back to normal (down), unless I hold clicking. How to make it realize that when an option is selected it shouldn't be on focus anymore? Can't seem to figure out a proper transformation here. What am I missing?
I've been trying mat-select-option/mat-option to transform the arrow to 0 degree again when option selected but couldn't make it work.

A: Did you try using :checked pseudo-class to revert it to normal? I presume you could try something similar to your ':focus':
:checked {
  &::ng-deep .mat-select-arrow {
    transform: rotate(180deg);
    -webkit-transform: rotate(180deg);
  }
}

You can check :checked pseudo-selector here


text:
Q: EXCEL: Merge Multiple Rows Macro I need a MACRO that looks at all instances of COL A and combines all values of COL B into one row, while deleting the duplicates in the process. Adding a comma is a plus.
I don't know any VBA, but if someone is kind enough to explain, I would love to learn. This isn't the first VBA solution I've needed. Thanks!
Example of what I need:
COL A    COL B
100 ---- PC 245
100 ---- PC 246
100 ---- PC 247
101 ---- PC 245
101 ---- PC 246
101 ---- PC 247

INTO
COL A    COL B
100 ---- PC 245, PC 246, PC 247
101 ---- PC 245, PC 246, PC 247

This data is going into a map, so I need it concatenated for the tooltip text. Any help is appreciated. Thanks!
PS: What I need is a MACRO. What I don't need is a PIVOT TABLE.

A: Reposting this code as it was deleted by a moderator. @bill-the-lizard, prior to redeleting it, can you comment on what's wrong with my answer?
Sub ConsolidateRows()
'takes rows and consolidate one or many cells, based on one or many cells matching with above or below rows.

Dim lastRow As Long, i As Long, j As Long
Dim colMatch As Variant, colConcat As Variant

'**********PARAMETERS TO UPDATE****************
Const strMatch As String = "A"    'columns that need to match for consolidation, separated by commas
Const strConcat As String = "B"     'columns that need consolidating, separated by commas
Const strSep As String = ", "     'string that will separate the consolidated values
'*************END PARAMETERS*******************

application.ScreenUpdating = False 'disable ScreenUpdating to avoid screen flashes

colMatch = Split(strMatch, ",")
colConcat = Split(strConcat, ",")

lastRow = range("A" & Rows.Count).End(xlUp).Row 'get last row

For i = lastRow To 2 Step -1 'loop from last Row to one

    For j = 0 To UBound(colMatch)
        If Cells(i, colMatch(j)) <> Cells(i - 1, colMatch(j)) Then GoTo nxti
    Next

    For j = 0 To UBound(colConcat)
        Cells(i - 1, colConcat(j)) = Cells(i - 1, colConcat(j)) & strSep & Cells(i, colConcat(j))
    Next

    Rows(i).Delete

nxti:
Next

application.ScreenUpdating = True 'reenable ScreenUpdating
End Sub

A: The following code requires you to add a reference to "Microsoft Scripting Runtime".
VBA Editor->Tools->References, Find and select Microsoft Scripting Runtime

Its possible to use "Collections" instead of "Dictionarys". I just prefer the dictionary.
The code will read the active worksheet, (the "Do Loop") and copies the data (removing duplicates in the process)
It then clears all data on the sheet.
It then loops through the data it collected and outputs it to the now empty worksheet (the "For Each" loops)
Sub Cat()
Dim Data As Dictionary
Dim Sheet As Worksheet

Set Sheet = ThisWorkbook.ActiveSheet
Set Data = New Dictionary

Dim Row As Integer
Dim Key As Variant
Dim Keys() As Variant
Dim Value As Variant
Dim Values() As Variant
Dim List As String

Row = 1

Do
    If Data.Exists(CStr(Sheet.Cells(Row, 1))) Then
        If Not Data(CStr(Sheet.Cells(Row, 1))).Exists(CStr(Sheet.Cells(Row, 2))) Then
            Data(CStr(Sheet.Cells(Row, 1))).Add (CStr(Sheet.Cells(Row, 2))), True
        End If
    Else
        Data.Add CStr(Sheet.Cells(Row, 1)), New Dictionary
        Data(CStr(Sheet.Cells(Row, 1))).Add (CStr(Sheet.Cells(Row, 2))), True
    End If
    Row = Row + 1
    If IsEmpty(Sheet.Cells(Row, 1)) Then
        Exit Do
    End If
Loop

Sheet.Cells.ClearContents

Keys = Data.Keys
Row = 1

For Each Key In Keys
    Values = Data(Key).Keys
    Sheet.Cells(Row, 1) = Key
    List = ""
    For Each Value In Values
        If List = "" Then
            List = Value
        Else
            List = List & ", " & Value
        End If
    Next Value
    Sheet.Cells(Row, 2) = List
    Row = Row + 1
Next Key

End Sub


text:
Q: How to solve GpuAcc_64.dll exception in OpenCV 3 and C++? I get Exception thrown at 0x..... (GpuAcc_64.dll) when I try to use a uEye camera in C++ (OpenCV 3). Any idea how to solve this? This happens at code line "VideoCapture capture = VideoCapture(1);"
My Code:
#include "opencv2/highgui.hpp"
#include "opencv2/opencv.hpp"
#include "opencv2/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <fstream>

using namespace cv;
using namespace std;

int main()
{
    // The number of boards you want to capture, the number of internal corners horizontally
    // and the number of internal corners vertically (That's just how the algorithm works).
    int numBoards;
    int numCornersHor;
    int numCornersVer;

    cout << "Enter number of corners along width: ";
    cin >> numCornersHor;

    cout << "Enter number of corners along height: ";
    cin >> numCornersVer;

    cout << "Enter number of boards: ";
    cin >> numBoards;

    // We also create some additional variables that we'll be using later on.
    int numSquares = numCornersHor * numCornersVer;
    Size board_sz = Size(numCornersHor, numCornersVer);

    // We want live feed for our calibration!
    VideoCapture capture = VideoCapture(1);

A: If you are on a laptop with a dedicated and on-board GPU, try disabling one of them and see if that works.
I don't know exactly what causes the issue but this is what solved the issue for me. (more specifically, disabling my on-board GPU fixed it)


text:
Q: How expand size virtual disk in virtual server 2005? I'm using Virtual Server 2005 and working with a virtual hard disk 16GB.
I need expand this virtual disk to 20GB.
Thanks.
Beatriz

A: You could try VMToolkit. It's free!


text:
Q: Is the second moment enough to characterize the Brownian motion? In the page 14 of the book "The Malliavin Calculus and Related Topics" from Nualart one reads:

I understand that if $Z_t \sim N(0,t)$ then
$$\Bbb{E}[Z_t^{2k}] = \frac{(2k)!}{2^k k!}t^k$$
However, I can't see why this follows from the single fact that $\Bbb{E}[(W_t-W_s)^2] = t-s$

A: For each $i$, he defines $\{W^i(t), t \in \mathbb{R}^+\}$ to be a zero-mean Gaussian process with covariance function $E[W^i(s)W^i(t)] = s \wedge t$.  This means that we know that $W^i(t) - W^i(s)$ is a normal random variable with mean zero; therefore, once we know what it's variance is, we've characterized the distribution entirely.  The point of this section is to use Kolmogorov's continuity criterion to show that we can make $W^i$ continuous almost surely.

EDIT: Here's a process that has independent increments, mean zero, and the variance of increments is $t - s$ but isn't Brownian motion:
Consider a Poisson process on $\mathbb{R}^+$ with intensity $1$, and let $X_t$ denote the number of points in $[0,t]$.  Define $Z_t = X_t - t$.  Then $$\mathbb{E}[(Z_t - Z_s)^2] = \mathbb{E}[((X_t - X_s) - (t-s))^2] = \mathrm{Var}[\mathrm{Poisson}(t-s)] = t-s$$


text:
Q: Login to ASP.net application via Google account My client has a request that he wants to login to ASP.net web application via Google account. As I have never done something like that I have some concerns.
What bothers me is that he wants to add roles (administrator, user) to specific accounts and this puzzles me because I'm not sure how to connect Google account data with my database. I assume that I won't be able to get the password or username that I could store to my own database.
Where to start?

A: Use OpenID. This is implemented in ASP.NET in the DotNetOpenAuth library. It includes samples for Google logins, and it's very easy.
The roles should work to. As you build up your user table, just add users to the appropriate roles.

A: Have a look at this:
http://www.asp.net/vnext/overview/aspnet/oauth-in-the-default-aspnet-45-templates
Scott Hanselman giving a quick overview of the OpenID features in .NET4.5. This might be a good starting point for you.
On MSDN:
http://blogs.msdn.com/b/webdev/archive/2012/08/15/oauth-openid-support-for-webforms-mvc-and-webpages.aspx

A: I suggest you to take a look at this codeplex miniproject : http://loginwithgoogle.codeplex.com/.
You might find it helpful.
Regards


text:
Q: CSS Grid Layout- horizontal and vertical scrolling only for part of the content I'm trying to create a layout where I have labels on the left and header at the top which should always be in a fixed position. On the right I have some input elements. If input elements are overflowing there should be a horizontal and vertical scrollbar only for input elements (left labels and header should stay untouched). I only want to use solution with CSS grid for some other reasons. I have tried to make header and left label elements sticky, it kind of worked but I feel like there is more elegant solution. I explicitly set grid-column and grid-row on each element and then wrap my content part (which I want to be scrollable) in a div that span across multiple rows and columns. Now, how can I make this part scrollable? I have tried to set explicit width/height on parent/child elements, I have tried overflow: auto but nothing worked.
HTML

Header

leg1
leg2

Label1
Label11
Label2

<input class="input1" value="test1"/>
<input class="input2" value="test2"/>
<input class="input3" value="test3"/>

CSS
.root{
  display:grid;
  grid-template-columns: max-content max-content max-content;
}

.header{
  grid-column: 1 / span 3;
  background: blue;
}

div input{
  height:50px;
}

.content{
  grid-column: 3;
  grid-row: 2 / span 3;
  display: grid;
}

.l1{
  grid-column: 1;
  grid-row: 2 / span 2;
  background: yellow;
}
.l2{
  grid-column: 1;
  grid-row: 4;
  background: green;
}

.label1{
  grid-column: 2;
  grid-row: 2;
  background: teal;
}

.label11{
  grid-column: 2;
  grid-row: 3;
  background: pink;
}

.label2{
  grid-column: 2;
  grid-row: 4;
  background: red;
}

.input1{

}
.input2{

}

Fiddle:
https://jsfiddle.net/kzu0gf4x/3/ -test1/test2/test3 should be scrollable on overflow, so if I scroll down I should see Header, scrollbar should only be on div with class="content"

A: Is this helpful?

/* Scrollbar Customization */

.root .body::-webkit-scrollbar {
  width: 10px;
}

.root .body::-webkit-scrollbar-track {
  box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
}

.root .body::-webkit-scrollbar-thumb {
  background-color: darkgrey;
  outline: 1px solid slategrey;
}

/* Scrollbar Customization */

.root {
  display: grid;
  grid-template-columns: max-content max-content max-content;
  border: 1px solid;
  width: fit-content;
}

.header {
  grid-column: 1 / span 3;
  background: blue;
}

.root .body {
  display: grid;
  max-height: 130px;
  overflow-y: scroll;
  /* Give overflow-y: scroll to show always Vertical scrollbar */
  overflow-x: auto;
  grid-template-areas: "label b" "label b" "label b";
}

.labels {
  display: grid;
  grid-area: label;
}

.content {
  grid-column: 3;
  grid-row: 2 / span 3;
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 220px;
  overflow: auto;
  grid-area: b;
  height: fit-content;
}

.content .row {
  display: grid;
  width: 100%;
  grid-auto-flow: column;
}

div input {
  margin: 0;
  border: 1px solid rgb(218, 218, 218);
  outline: 0;
  padding: 21px 10px;
}

.l1 {
  grid-column: 1;
  grid-row: 1 / span 3;
  background: yellow;
}

.l2 {
  grid-column: 1;
  grid-row: 3;
  background: green;
}

.label1 {
  grid-column: 2;
  grid-row: 1;
  background: teal;
}

.label11 {
  grid-column: 2;
  grid-row: 2;
  background: pink;
}

.label2 {
  grid-column: 2;
  grid-row: 3;
  background: red;
}

    Header

      leg1
      leg2

      Label1
      Label11
      Label2

        <input class="input1" value="test1">
        <input class="input2" value="test2">
        <input class="input3" value="test3">

        <input class="input1" value="test1.1">
        <input class="input2" value="test2.1">
        <input class="input3" value="test3.1">

        <input class="input1" value="test1.2">
        <input class="input2" value="test2.2">
        <input class="input3" value="test3.2">


text:
Q: C# Pinvoke invalid file handle I'm having a problem with kernal32 Pinvoke functions as they keeps throwing an INVALID_FILE_HANDLE. The program reads the first sector of the current hard disk. I can't see what is wrong with the following code.
    class Program
    {
    const uint GENERIC_READ = 0x80000000;
    const uint FILE_SHARE_READ = 0x00000001;
    const uint OPEN_EXISTING = 0x00000003;
    const uint FILE_FLAG_DELETE_ON_CLOSE = 0x04000000;

    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern SafeFileHandle CreateFile(string Disk, uint Access, uint ShareMode, IntPtr SecurityAttributes, uint CreationDisposition, uint Flags, IntPtr TemplateFile);
    [DllImport("kernel32.dll", SetLastError = true)]
    public static extern uint SetFilePointer([In] SafeFileHandle Handle, [In] int DistanceToMove, [Out] out int DistanceToMoveHigh, [In] int MoveMethod);
    [DllImport("kernel32.dll", SetLastError = true)]
    unsafe public static extern int ReadFile(SafeFileHandle Handle, [Out] byte[] Buffer, int NumberOfBytesToRead, out int NumberOfBytesRead, IntPtr Overlapped);

    unsafe public static void Main(string[] args)
    {
        string Drive = @"\\.\C";
        int SectorSize = 512;
        int Sector = 0;
        int BytesRead, DistanceToMoveHigh;
        byte[] Buffer = new byte[SectorSize];

        SafeFileHandle Handle = CreateFile(Drive, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, FILE_FLAG_DELETE_ON_CLOSE, IntPtr.Zero);
        SetFilePointer(Handle, Sector * SectorSize, out DistanceToMoveHigh, 0);
        ReadFile(Handle, Buffer, SectorSize, out BytesRead, IntPtr.Zero);

        Console.WriteLine(Marshal.GetLastWin32Error()); // It gives 6 which translates to an INVALID_FILE_HANDLE error
        Console.ReadKey();
    }
}

A: Your call to CreateFile fails. Of course you cannot know that because you omitted any error checking. Read the documentation. Errors for all three functions that you call are signaled by the return value. Which you ignore.
Your call to CreateFile returns INVALID_HANDLE_VALUE. You need to test for that. When you encounter that, and only then, call GetLastWin32Error. Likely ERROR_ACCESS_DENIED will be returned then.

*

*Passing FILE_FLAG_DELETE_ON_CLOSE is a mistake. Remove that flag.

*I believe that the share flags must be FILE_SHARE_READ | FILE_SHARE_WRITE.

*The file name must be @"\\.\C:" with a trailing colon.

*And you will need the process to be executed elevated.

A: You use GetLastWin32Error in a wrong way.
The method that fails here is CreateFile and it returns an INVALID_HANDLE_VALUE (indicating that it failed). To determine what went wrong you have to call GetLastWin32Error directly after CreateFile.
When you call it after trying to read, the error is of course ERROR_INVALID_HANDLE (6) as you passed an invalid handle to ReadFile.
If you call GetLastWin32Error directly after the failing CreateFile you get error 2:

The system cannot find the file specified.

That is because the the drive name misses a :
string Drive = @"\\.\C:"; // <- add colon :

I tried with that drive name, but then got the error 32:

The process cannot access the file because it is being used by another process.

I keep trying to figure out how that can be handled...


text:
Q: Tumblr theme... trying to find the type (text, picture, etc) of the first post So I want various aspects of my theme to change depending on the most recent post. Any idea how I could do it?
I would prefer it to be by using on of the tumblr custom {html tag} things, rather than javascript or whatever. Don't know if that's even allowed on tumblr either.
Theme Documents are here:
http://www.tumblr.com/docs/custom_themes
Thanks.

A: in the first post, in the according type block (block text, block photo, etc..) put custom css that overrides the default style, and you're done

{block:Post[1-15]} {/block:Post[1-15]}
    Rendered for the post at the
  specified offset. This makes it
  possible to insert an advertisement or
  design element in the middle of your
  posts.
Example: {block:Post5}I'm the fifth
  post!{/block:Post5} will only be
  rendered on the fifth post being
  displayed.

A: You can get your most recent posts as JSON, so you can have a bit of JavaScript which would get the most recent posts then apply some extra CSS magic.


text:
Q: proxy tunneling with c I am working on a small project (C programming) to tunnel through a proxy and when I try to do it I get a error:
HTTP/1.0 400 Bad Request
Server: squid/2.7.STABLE9
Date: Mon, 07 Jan 2013 22:20:56 GMT
Content-Type: text/html
Content-Length: 1456
X-Squid-Error: ERR_INVALID_REQ 0
X-Cache: MISS from xt03
Via: 1.0 xt03:80 (squid/2.7.STABLE9)
Connection: close

The data I am sending to the proxy server is:
 char msg[] = "CONNECT example.com:80 HTTP/1.0 <CR><LF> HOST example.com:80 <CR><LF> \n";

Any help would be great!
------ UPDATE ------
I have tried the methods you guys suggested and I am still getting an error. I will post my entire set of code and see if it is something in the socket causing it to send the wrong information.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define maxlen 2048

int main(int argc, char *argv[])
{
int mysocket;
int len;
char buffer[2000];
char msg[] = "CONNECT example.org:80 HTTP/1.0 \r\n HOST example.org:80 \r\n\r\n";

mysocket = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in dest;

memset(&dest, 0, sizeof(dest));

dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr("125.39.66.150");
dest.sin_port = htons(80);

connect(mysocket, (struct sockaddr *)&dest, sizeof(struct sockaddr));

send(mysocket, msg, strlen(msg), 0);
len = recv(mysocket, buffer, maxlen, 0);

buffer[len] = '\0';

printf("%s \n", buffer);
close(mysocket);
return 0;

}
----- UPDATE ------
New error:
HTTP/1.0 400 Bad Request
Server: squid/2.7.STABLE5
Date: Tue, 08 Jan 2013 22:40:24 GMT
Content-Type: text/html
Content-Length: 1158
X-Squid-Error: ERR_INVALID_REQ 0
X-Cache: MISS from DXT-BJ-219
X-Cache-Lookup: NONE from DXT-BJ-219:80
Connection: close

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"         "http://www.w3.org/TR/html4/loose.dtd">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The requested URL could not be retrieved</TITLE>

ERROR

The requested URL could not be retrieved

While trying to process the request:

CONNECT example.com:80 HTTP/1.1

The following error was encountered:

Invalid Request

Some aspect of the HTTP Request is invalid.  Possible problems:

Missing or unknown request method

Missing URL

Missing HTTP Identifier (HTTP/1.0)

Request is too large

Content-Length missing for POST or PUT requests

Illegal character in hostname; underscores are not allowed

Your cache administrator is noc_admin@163.com.

<ADDRESS>
by DXT-BJ-219
</ADDRESS>

A: "Bad request" meant that the request you sent to the server was malformed and couldn't be understood. I think the reason for this is that you are sending the 8 characters <CR><LF> (as in, '<', 'C', 'R' etc.) rather than the 2 characters that they should represent, i.e. \r\n.
Try
char msg[] = "CONNECT example.com:80 HTTP/1.0\r\nHOST example:80\r\n\r\n";

A: Refer this: rfc2616
10.4.1 400 Bad Request
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
When you are passing:
char msg[] = "CONNECT example.com:80 HTTP/1.0 <CR><LF> HOST example.com:80 <CR><LF> \n";

Then perhaps the <CR> and <LF> parts are sent as it is as strings, instead of the ASCII 0xA and 0xD, which represent the control characters you intend to send.
The simplest fix would be using C equivalents: \r for <CR> and \n for <LF>:
char msg[] = "CONNECT example.com:80 HTTP/1.0 \r\n HOST example.com:80 \r\n\r\n";

If you intend to expand the use of the msg[] array to contain many more requests you might have to write a wrapper function to translate the CR,LF and other control strings in the msg[] into appropriate C char equivalents to form proper message.
Hope this helps.


text:
Q: Uploading multiple layers to a layer group at once in GeoServer Is it possible to upload layers to a layer group at once to geoserver? I have about 1000 data and I want to upload them to one layer group. However, as I understand, I have to select them one by one for uploading. Is there any button such as select all?

A: The GeoServer Importer Extension is what you are looking for ! :)
GeoServer Importer Extension
There are two primary advantages to using the Importer over the standard GeoServer data-loading workflow:
1. Supports batch operations (loading and publishing multiple spatial files or database tables in one operation)
2. Creates unique styles for each layer, rather than linking to the same (existing) styles.
EDIT:
A solution using python has been provided here

A: You can use a combination of geoserver-rest  (https://geoserver-rest.readthedocs.io/en/latest/), and geoservers own REST interface to achieve this.
Since i had no luck using create_layergroup() from geoserver-rest, i made this rather hacky solution:
import requests

from geo.Geoserver import Geoserver
geo = Geoserver('http://ip:8080/geoserver_USA', username='xxxx', password='xxxx')

noaa_workspaces = ["NOAA_enc_overview","NOAA_enc_harbour","NOAA_enc_approach","NOAA_coastal","NOAA_general"]

for service in noaa_workspaces:
    #file = open(service + "_layers", "w+")
    print(service)
    layers = geo.get_layers(workspace=service)

    layer_list = []
    for x in range(len(layers["layers"]["layer"])):
        layer_list.append(layers["layers"]["layer"][x]["name"])
        print(layers["layers"]["layer"][x]["name"])

    layer_list.sort()
    xml=""
    for layer in layer_list:
        #print("<layer>%s:%s</layer>" % (service,layer))
        xml += "<layer>%s:%s</layer>" % (service,layer)
        #print(xml)
        #open(service, "a")
        #file.write("<layer>%s:%s</layer>" % (service,layer))

    xml_final =  "<layerGroup><name>%s</name><layers>%s</layers></layerGroup>" % (service,xml)
    #print(xml)
    #print(xml_final)

    headers =  {'Content-type' : 'text/xml'}
   # requests.post('http://httpbin.org/post', data=xml, headers=headers).text

    print("send request for : ", service)
    print(requests.post('http://user:pass@ip:8080/geoserver_USA/rest/layergroups',data=xml_final, headers=headers).text)


text:
Q: Firebase Barcode Scanner for IOS So I am trying to use Firebase's barcode scanning API for my IOS application. Everything is running error-free (for now) but I am not sure how to access the barcode information once the picture is sent to the .detect function.
In the documentation on the firebase website it says that: "If the barcode recognition operation succeeds, the detector returns an array of VisionBarcode objects. Each VisionBarcode object represents a barcode that was detected in the image."
Could someone help me understand how to access the barcodes array? Below I have included a link to the documentation (where I am getting the code from) and pictures of my code.
Code
https://firebase.google.com/docs/ml-kit/ios/read-barcodes#swift_7
    func scanBarcode(userImage: UIImage){
    print("SCAN")
    let format = VisionBarcodeFormat.all
    let barcodeOptions = VisionBarcodeDetectorOptions(formats: format)
    var vision = Vision.vision()
    let barcodeDetector = vision.barcodeDetector(options: barcodeOptions)
    let visionImage = VisionImage(image: userImage)
    barcodeDetector.detect(in: visionImage) { features, error in
      guard error == nil, let features = features, !features.isEmpty else {
      //  print(barcodes)
        return
      }
        print("unsuccesful scan")
      // ...
    }

}

A: Your logic for a successful scan is a little off: you need to print the features after your guard
func scanBarcode(userImage: UIImage){
    print("SCAN")
    let format = VisionBarcodeFormat.all
    let barcodeOptions = VisionBarcodeDetectorOptions(formats: format)
    var vision = Vision.vision()
    let barcodeDetector = vision.barcodeDetector(options: barcodeOptions)
    let visionImage = VisionImage(image: userImage)
    barcodeDetector.detect(in: visionImage) { features, error in
        guard error == nil, let features = features, !features.isEmpty else {
            print("unsuccessful scan, either there is an error, or features is empty")
            return
        }
        print("successful scan")
        print(features)
        // ...
     }
}


text:
Q: Delete All Rows with Year != Pandas I have a huge panda df with hourly data from years 1991-2021 and I need to drop all rows with year != 2021 or the current year. In my dataframe there is a column "year" with years ranging from 1991-2021 of hourly data. I am using this line of code below but it does not seem to be doing anything for dataframe df1. Is there a better way to delete all rows that do not equal year == 2021?:
trimmed_df1 = df1.drop(df1[df1.year != '2021'].index)

My data is a 4532472 X 10 column df in this format:
df1.columns.values
Out[20]:
array(['plant_name', 'business_name', 'business_code',
   'maint_region_name', 'power_kwh', 'wind_speed_ms', 'mos_time',
   'dataset', 'month', 'year'], dtype=object)

A: This should do the job:
>>> trimmed_df1 = df1.query('year != 2021').reset_index()

Maybe you don't even need to reset the index - it's up to you.

A: Instead of deleting lines, why not use a .loc[] call to select the lines you do want?
trimmed_df1 = df1.loc[df1.year == '2021']


text:
Q: Layout Fidelity warning I am on day one here, sorry for any stupid questions...
I am using android studio 2.3.1
I made an new blank app and placed a few buttons and some text.
When I run the phone emulator it crams everything from my design page into the top left and I get a render error saying !layout fidelity warning (the graphics preview in the layout editor may not be accurate)
I followed the youtube video I was watching step by step and theirs seemed to run fine, any idea what I have to do to fix this ?


text:
Q: Cell sizes for a fractional factorial design that ignores some main effects We're designing a trial to test three behavioral interventions (call them A, B, and C) for a health condition. Treatment A is an established intervention and B and C are considered add-ons to A.
We want to test the following contrasts:

*

*Outcomes of packages involving Treatment A vs. No treatment.

*Outcomes of adding B, C, or B+C to A.

Because we're not trying to estimate effects of B or C in the absence of A, we came up with a fractional factorial design implementing the following 5 cells:
Cell    A/B/C    included?
--------------------------
1       + + +    included
2       + + -    included
3       + - +    included
4       + - -    included
5       - + +    not included
6       - + -    not included
7       - - +    not included
8       - - -    included

How many participants should we have in cell #8? (the "no treatment" cell)
Normally factorial designs put the same number of participants in each cell, but they also have equal numbers of cells with each treatment present vs. absent. Since we have only one cell without treatment A, should this cell be 4x the size of the others? Even if we're comfortable adjusting for unequal cell sizes, should the "no treatment" cell be substantially larger than the other cells?

A: Nice question. It is reassuring that some people think about this BEFORE doing the experiment (+1).
I guess that if you are not interested in the effect of B and C alone, this is because you expect strong interaction with A. So you will probably go for an additive model plus interactions. $\beta_0 + \beta_A A + \beta_B B + \beta_C C + \beta_{AB} A*B + \beta_{AC} A*C + \beta_{BC} B*C + \beta_{ABC} A*B*C$.
Because you do not investigate the role of $B$ and $C$ alone, you actually study an equivalent model which is $\beta_0 + \beta_A A + \beta_{AB} A*B + \beta_{AC} A*C + \beta_{ABC} A*B*C$ which happens to have... 5 parameters. Each of your cell estimates one of them in particular, so I think this is a good reason to put exactly the same number of people in cell #8 as in the others.

A: I think the cell size should be dictated by the variance of the outcome variable in each cell.  If you could get a guess if it based on medical knowledge and past experience with A then sample inversely proportiona to the variance. That should equalize cell means.  Even though this would only be done approximately it would be advantageous.  Realize that the basis for a balanced design is that each cell or stratum has the same variance for the response.  Otherwise the balanced design will not be optimal.


text:
Q: Fetch: set variable with fetch response and return from function I'm quite new with JavaScript and react.
I have a callback from a component that gets a customer_name from a server given a id.
The fetch works and the console.log prints the fullname correctly, but the customer_name in the last .then is not set, and the functions returns an empty string. Why is that?
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
  let customer_name = '';

 fetch(`/customers/${id}.json`, {
   headers: API_HEADERS,
   credentials: 'same-origin'
 })
 .then((response) => {
   if(response.ok) {
     return response.json();
   } else {
     throw new Error('Server response wasn\'t OK');
   }
 })
 .then((json) => {
   customer_name = json.first_name.concat(' ').concat(json.last_name);
   console.log(customer_name);
 });
 return customer_name;
}

A: I think you don't understand Promises correctly. The return statement will be called before the Promise is resolved, thus returning empty string.
One way to tackle this, is to return the whole promise like this:
// Gets the fullname of the customer from an id.
tj_customer_name(id) {
  let customer_name = '';

  return fetch(`/customers/${id}.json`, {
    headers: API_HEADERS,
    credentials: 'same-origin'
  })
  .then((response) => {
    if(response.ok) {
        return response.json();
    } else {
        throw new Error('Server response wasn\'t OK');
    }
  })
  .then((json) => {
    return json.first_name.concat(' ').concat(json.last_name);
  });
}

or you can use the ES7 approach, using async/await like this
async function tj_customer_name(id) {
    const response = await fetch('some-url', {});
    const json = await response.json();

    return json.first_name.concat(' ').concat(json.last_name);
}

As you can see, the second approach is much cleaner and readable.
The result will be the same in the code which calls your function
tj_customer_name(1).then(fullName => {
    console.log(fullName);
});

or
async function something() {
    const fullName = await tj_customer_name(1);
    console.log(fullName);
}

A: Because fetch is asynchronous and returns a promise, which by its nature can only be observed asynchronously (using .then).
You should probably just return the promise chain you create in your function and return customer_name in the last .then callback of the chain:
// Gets the fullname of the customer from an id.
tj_customer_name(id) {

 // return the entire promise chain
 return fetch(`/customers/${id}.json`, {
   headers: API_HEADERS,
   credentials: 'same-origin'
 })
 .then((response) => {
   if(response.ok) {
     return response.json();
   } else {
     throw new Error('Server response wasn\'t OK');
   }
 })
 .then((json) => {
   const customer_name = json.first_name.concat(' ').concat(json.last_name);
   return customer_name; // return the customer_name here
 });
}

// later, use the function somewhere
this.tj_customer_name(21).then((customer_name) => {
    // do something with the customer_name
});

PS: Don't forget to add a .catch handler to handle potential network issues (see: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful)


text:
Q: Making a query on my database using user input I am writing some code that will allow the user to enter there location and month of the year and be presented with stars viewable that month from their location. I have my database completed and query working on mySQl but trying to implement it on the web page and have come accross some difficulties, I have two inputs the user can make and the program below that runs the function, If anyone can spot any errors, The function will not output any data when location and month entered but when nothing is entered and submit pressed it outputs events but cannot figure out why.
The search function is below and then the event. php is below that
<?php
/**
* Performs a search
*
* This class is used to perform search functions in a MySQL database
*
*
*
*/
class search {
/**
* MySQLi connection
* @access private
* @var object
*/
private $mysqli;

/**
* Constructor
*
* This sets up the class
*/
public function __construct() {
// Connect to our database and store in $mysqli property
$this->connect();
}
/**
* Database connection
*
* This connects to our database
*/
private function connect() {
$this->mysqli = new mysqli( 'localhost', 'conor', 'trevor29', 'site_db' );
}

/**
* Search routine
*
* Performs a search
*
* @param string $search_term The search term
*
* @return array/boolen $search_results Array of search results or false
*/
public function search($search_term, $search_term1) {
// Sanitize the search term to prevent injection attacks
$sanitized = $this->mysqli->real_escape_string($search_term);
$sanitized1 = $this->mysqli->real_escape_string($search_term1);

// Run this Query
$query =$this ->mysqli->query("
SELECT event_name FROM event
INNER JOIN event_month
ON event.event_id = event_month.event_id
INNER JOIN month
ON event_month.month_id = month.month_id
INNER JOIN location
ON location.hemisphere = event.hemisphere
WHERE month_name LIKE '%{$sanitized}%'
AND city LIKE '%{$sanitized1}%'
");

// Run the query
//$query = $this->mysqli->query("
//SELECT *
//FROM event inner join location
//ON event.event_id = location.event_id
//WHERE city LIKE'%{$sanitized}%'
//");

// Check results
if ( ! $query->num_rows ) {
  return false;
}

// Loop and fetch objects
while( $row = $query->fetch_object() ) {
  $rows[] = $row;
}

// Build our return result
$search_results = array(
  'count' => $query->num_rows,
  'results' => $rows,
);

return $search_results;
}
}

this code below is the event page that calls the search function above
    ?php
//getname
session_start();

//Check if search data was submitted

$search_results="";

if  (isset( $_GET['s'])){

// Include the search class
require_once( dirname( __FILE__ ) . '/class-search.php' );

// Instantiate a new instance of the search class
$search = new search();

// Store search term into a variable
$search_term =($_GET['s']);
$search_term1 =($_GET['m']);

// Send the search term to our search class and store the result
$search_results = $search->search($search_term, $search_term1);

}
?>

This below is where the user inputs their location and month
    Search Events

    Search
    ">

<form action= "" method = "get">

Search
<input type = "type" name ="m" placeholder = "Enter the month" results="5" value = "<?php $search_term1; ?>">
<input type ="submit" value = "Search">

If anyone can see any errors or mistakes it would be great help the more I work on it the further away I am getting

A: Well the easiest error I can see from a limited snapshot like this is you are passing the month through $search_term1 HOWEVER you are searching for city with $sanitized1 which leads me to believe you have the month and city reversed in the query.


text:
Q: C# - Interlocked Increment on a Dictionary Like List I know that the int wont have a fixed position in memory so it simply cant work like that.
But The exact same portion of code will be run concurrently with different names, parameters e.t.c
I need to essentially pass a string of "Name" and then somehow increment one of the items in my int array.
Dictionary<string, int> intStats = new Dictionary<string, int>();
This dictionary stores all the stats based on the "Name" supplied as the dictionaries string key.
And since im using a LOT of multi-threading, I wish to keep the int count as synchronized as possible. Which is why im attempting to use Interlocked.Increment(ref intStats[theName]);
But unfortunately this wont work.
Is there any alternatives that would work for my situation?

A: First, I suggest creating a custom type that captures the semantics of your abstract data type. That way you can experiment with different implementations, and that way your call sites become self-documenting.
internal sealed class NameCounter
{
  public int GetCount(string Name) { ... }
  public void Increment(string Name) { ... }
}

So: what implementation choices might you make, given that this must be threadsafe?

*

*a private Dictionary<string, int> would work but you'd have to lock the dictionary on every access, which could get expensive.

*a private ConcurrentDictionary<string, int>, but keep in mind that you have to use TryUpdate in a loop to make sure you don't lose values.

*make a wrapper type:

internal sealed class MutableInt
{
  public int Value;
}

This is one of the rare cases when you'd want to make a public field.  Now make a ConcurrentDictionary<string, MutableInt>, and then InterlockedIncrement the public field. Now you don't have to TryUpdate, but there is still a race here: if two threads both attempt to add the same name at the same time for the first time then you have to make sure that only one of them wins.  Use AddOrUpdate carefully to ensure that this race doesn't happen.

*

*Implement your own concurrent dictionary as a hash table that indexes into an int array; InterlockedIncrement on elements of the array.  Again, you'll have to be extremely careful when a new name is introduced into the system to ensure that hash collisions are detected in a threadsafe manner.

*Hash the string to one of n buckets, but this time the buckets are immutable dictionaries. Each bucket has a lock; lock the bucket, create a new dictionary from the old one, put it back in the bucket, unlock the bucket. If there is contention, increase n until it goes away.


text:
Q: Enigmail + GnuPG + Thunderbird hidden key error A friend of mine recently updated his OpenPGP keys. I cannot open the encrypted email received from that friend in my Thunderbird. I use Enigmail, and I get the following error:
Enigmail Security Info

Error - no matching private/secret key found to decrypt message

gpg: decryption failed: No secret key

Note: The message is encrypted for the following User ID's / Keys:
<hidden key>,
<hidden key>

However, if I can decrypt the encrypted text using command line. So, it has been correctly encrypted using my keys. This is the same case with everyone who is receiving encrypted email from that friend.
So, what has gone wrong? How to fix this issue (I believe it has to fixed from that friend's side)?

A: Your friend is sending his mail using the "hidden recipient" option, which removes the recipient's key ID from the OpenPGP meta data. This is used for additional privacy (the recipient is not contained in the meta data any more), but forces your client to iterate over all available private keys. Hiding the recipient seems a little over-cautious for regular e-mail, though: the mail recipient must be stored with the mail, anyway (if you want the mail delivered).
But this should be well supported by Enigmail. Make sure your private keys are both available in gpg --list-secret-subkeys and gpg2 --list-secret-subkeys to make sure you're not having different key sets available among the different versions of GnuPG (they might be using different locations to store your private keys).
Otherwise, ask your friend to send mails without using the hidden recipient feature.

A: The sender should disable the option throw-keyids in his/her .gnupg/gpg.conf file.


text:
Q: How can I make certain words clickable in a TextView? I am building a twitter-like client. Assume I have a string:
"$AAPL rocks!"
I want to be able to click on "$AAPL" and do something.
How can I go about making $ clickable in a TextView?

A: Linkify should be what you are looking for.
UPDATE: You can implement your own URI and have your application listen for that Intent calls.


text:
Q: blank Row in TableView JavaFx APP i am trying to use tableview in my javafx app but it's giving me blank rows in tableview.....
Here is sample output :

Here is the code for model class:
public class Pizza {
    private final SimpleStringProperty pname;
    private final SimpleStringProperty pflavour;
    private final SimpleStringProperty psize;
    private final SimpleDoubleProperty pprice;
    public Pizza(String name, String flavour, String size, Double price) {
        super();
        this.pname = new SimpleStringProperty(name);
        this.pflavour = new SimpleStringProperty( flavour);
        this.psize = new SimpleStringProperty(size);
        this.pprice = new SimpleDoubleProperty(price);
    }
    public String getName() {
        return pname.get();
    }
    public String getFlavour() {
        return pflavour.get();
    }
    public String getSize() {
        return psize.get();
    }
    public Double getPrice() {
        return pprice.get();
    }

}

Here is the code for controller class :
        @FXML
        private TableView<Pizza> pizzatable;
        @FXML
        private TableColumn<Pizza,String> pname;
        @FXML
        private TableColumn<Pizza,String> pflavour;
        @FXML
        private TableColumn<Pizza,String> psize;
        @FXML
        private TableColumn<Pizza,Double> pprice;
        ObservableList<Pizza> pizzalist;

Here is the code for method that i call to fetch data from databse:
public void fetchpizza() throws SQLException{
        stmt = conn.createStatement();
        sql = "select * from items where itype = 'Pizza'";
        rs = stmt.executeQuery(sql);
        pname.setCellValueFactory(new PropertyValueFactory<Pizza,String>("pname"));
        pflavour.setCellValueFactory(new PropertyValueFactory<Pizza,String>("pflavour"));
        psize.setCellValueFactory(new PropertyValueFactory<Pizza,String>("psize"));
        pprice.setCellValueFactory(new PropertyValueFactory<Pizza,Double>("pprice"));
        pizzalist = FXCollections.observableArrayList();
        while(rs.next()){
            pizzalist.add(new Pizza(rs.getString("oname"),rs.getString("flavour"),rs.getString("size"),rs.getDouble("price")));
            pizzatable.setItems(pizzalist);
        }
        rs.close();
        stmt.close();
    }

A: You need to use the Strings corresponding to the getters or property getters as argument for the PropertyValueFactory constructor.
E.g. one of the following methods of the items would be used to retrieve the value/property, if you pass "name" as parameter to the constructor of PropertyValueFactory<Pizza, String>:

*

*nameProperty() (should return StringProperty). This allows to observe changes in the value without having to call TableView.refresh().

*getName() (should return String)

You pass the name of the fields however. Since the method names do not march the required pattern, the TableCells remain empty.


text:
Q: How to: clear the JPanel before repainting and the run another class and move the object I want to run the snake class after the start button its pressed the programg works until i press the start button and try to move the rectangle around the window, there is the problem the rectangle wont move at all. Please help. Thanks.
public class Main {
public static void main(String [] args) {
MenuScreen MenuScreen = new MenuScreen();
MenuScreen.menuscreen();
}
    }

The Screen Menu class
import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

    public class MenuScreen {

        Snake Snake = new Snake();

    public  void menuscreen () {

            //Window
        final JFrame window = new JFrame();
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(800, 600);
        window.setLocationRelativeTo(null);

            //Panel
        JPanel panel = new JPanel();
        window.getContentPane().add(panel);
        panel.setBackground(Color.BLACK);
        panel.setVisible(true);
        panel.setLayout(null);

            //Title
        JLabel label = new JLabel("SNAKE");
        panel.add(label);
        label.setBounds(290, 5, 204, 73);
        label.setFont(new Font("Tahoma", Font.BOLD, 60));
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setForeground(Color.RED);
        label.setBackground(Color.red);

            //Buttons
            //start button
        JButton bstart = new JButton ("Start");
        panel.add(bstart);
        bstart.setBounds(424, 200, 70, 60);
        bstart.setVisible(true);

        //start button - run snake on click
        bstart.addActionListener(new ActionListener()
              {
                public void actionPerformed(ActionEvent e)
            {

            window.getContentPane().removeAll();
            Snake Snake = new Snake();
            window.add(Snake);
            window.repaint();
            window.revalidate();

       }
              });

            //exit button
        JButton bexit = new JButton ("Exit");
        panel.add(bexit);
        bexit.setBounds(290, 200, 70, 60);
        bexit.setVisible(true);
            //exit button - close on click
        bexit.addActionListener(new ActionListener()
              {
                public void actionPerformed(ActionEvent e)
            {
                System.exit(0);
            }
              });

    }
}

The Snake class, when I click start the frame gets cleared and shows the rect but when I try to move the rect aroud the screen it wont move.
    public class Snake extends JPanel implements ActionListener, KeyListener {
     public void thicks () {}

    public Snake () {

     addKeyListener(this);
     setFocusable(true);
     setFocusTraversalKeysEnabled(false);

    }

    private static final long serialVersionUID = 1L;

    Timer FPS = new Timer( 5, this);
    double x =0 , y = 0, SpeedX = 0, SpeedY = 0;

    public void paint(Graphics g) {
        FPS.start();
        super.paintComponent(g);
        g.setColor(Color.blue);
        Graphics2D graphics  = (Graphics2D) g;

        Rectangle2D rect = new Rectangle2D.Double(x, y, 40, 40);
        graphics.fill(rect);

        }

    public void actionPerformed(ActionEvent e) {
    if(x < 0 ||  x > 740 ) {
        SpeedX= -SpeedX;
    }

    if(y < 0 || y > 520) {
        SpeedY = -SpeedY;
            }

    x += SpeedX;
    y += SpeedY;
    repaint();
}
public void down() {
        SpeedY = 2;
        SpeedX =  0;

    }

    public void up() {
        SpeedY = -2;
        SpeedX = 0;
    }

    public void right() {
        SpeedY = 0;
        SpeedX = 2;

    }

    public void left() {
        SpeedY =  0;
        SpeedX = -2;
    }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        if (keyCode == KeyEvent.VK_DOWN) {
            down();
         }

        if(keyCode == KeyEvent.VK_UP) {
            up();
        }

        if(keyCode == KeyEvent.VK_RIGHT) {
            right();
        }

        if(keyCode == KeyEvent.VK_LEFT) {
            left();
        }

    }

    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}

   }


text:
Q: How to print HTML characters without iteration(append) in Flask-SocketIO? I have prepared a basic Flask Socket IO as part of learning.
socket.on('time_update', function (results){
            const total_time = results.time1;
            const a = Math.round(total_time)
            $('#time1').css('width', a)
            $('#log').append($('<h4/>').text(total_time).html());
        })
<h4 id="log"> Time Elapsed #' </h4>

For the id="log", I see the total_time value keeps iterating in the single lines.
I just need the constant value to be updated. so i need the replacement of append if any.
Reference output image :
I need the value to be constantly updated as a single integer and not line by line. Is there a method other than append to achieve it?


text:
Q: Ornstein-Uhlenbeck-Model with irregular time intervals I have data of the form:
Time t  Price x(t)
0       80
21      82
24      82.3
32      81.5
...     ...

The point is, that the time intervals are highly irregular. I suppose an Ornstein-Uhlenbeck-Process would fit nicely:
$$
dx(t)=θ(μ−x(t))dt+σdW(t)
$$
The problem in estimating the parameters is the irregularity of the time-intervals. An exact updating formula for discrete time would be:
$$
x(t+\Delta t)=x(t)\exp(-θ\Delta t)+\mu (1-exp(-θ\Delta t))+\sigma \sqrt{\frac{1-exp(-2θ\Delta t)} {2θ}}
$$
Now, the formula above is autoregressive, so if $\Delta t$ would be constant I could very easily calculate the parameters using OLS-estimation. But I have no idea how to solve the problem of the irregular time intervals. Maybe somebody here has an idea?

A: Since the conditional transition density of an OU process is known explicitly and is Gaussian, I would suggest to use an ML-estimator. Given the observations $X_0,\dots ,X_n$ at time-points $t_0, \dots, t_n$ the log-MLE is
\begin{equation}
\operatorname{argmin}_\theta
\sum_{i=1}^n \frac{X_{i} - m(X_{i-1}, t_i - t_{i-1})}{2 s^2(t_i-t_{i-1})} + \frac{1}{2}\log s^2(t_i - t_{i-1}),
\end{equation}
with
\begin{equation}
m(x, t) = \mathbb E [X_t | X_0 =x] = x\exp(-\theta t) + \mu(1-\exp(-\theta t))
\end{equation}
and $s(t) = \sigma \sqrt{\frac{1-exp(-2\theta t)} {2\theta}}$.
Perhaps you find this book useful: S. Iacus, "Simulation and Inference for Stochastic Differential Equations".


text:
Q: CSS for a left-aligned text icon not working I'm trying to make a simple website editor and I want to make a left-align icon, like for example:

Since I can't find an SVG I like, and I can't use PNG (vectors, please), I thought of making my own in HTML.
I tried:

div#format-controls div#text-align-controls div.text-align-control
{
  width: 24px;
  height: 24px;

  bottom: 0px;

  max-width: 10%;
  max-height: 100%;

  display: inline-block;
}
div#format-controls div#text-align-controls div.text-align-control span
{
  width: 100%;
  height: calc(100% / 8);

  padding: 0px;

  display: inline-block;

  color: black;
  background: black;
}

but it is definitely not what I want. I would want something like the highlighted:

Any ideas on how I could achieve this?

A: As per comments you can use the icons from suggested sites.
But if you still want to use CSS to create the left-align icon, please modify CSS as below.

div#format-controls div#text-align-controls div.text-align-control
{
  width: 24px;
  height: 24px;

  bottom: 0px;

  max-width: 10%;
  max-height: 100%;

  display: inline-block;
}
div#format-controls div#text-align-controls div.text-align-control span
{
  width: 100%;
  height: calc(100% / 8);

  padding: 0px;

  display: block;
  margin-bottom: 3px;

  color: black;
  background: black;
}
div#format-controls div#text-align-controls div.text-align-control span:last-of-type{
  margin:0;
}
div#format-controls div#text-align-controls div.text-align-control span:nth-child(2n){
   width: 80%;
}
div#format-controls div#text-align-controls div.text-align-control.selected{
  background: #E8F0FE;
  padding: 10px;
  border-radius: 3px;
}
div#format-controls div#text-align-controls div.text-align-control.selected span{
  background: #1A73E8;
}

For selected state check below icon's html and extra css

A: You are using a lot of code for a simple icon. It can be done with one element and few line of CSS

.icon {
  width:24px;
  height:24px;
  display:inline-block;
  border:10px solid transparent;
  background:
    linear-gradient(currentColor 0 0) 0 0,
    linear-gradient(currentColor 0 0) var(--p,0) calc(100%/3),
    linear-gradient(currentColor 0 0) 0 calc(2*100%/3),
    linear-gradient(currentColor 0 0) var(--p,0) 100%;
  background-size:100% 3px, 75% 3px;
  background-repeat:no-repeat;
}

.right { --p:100%;}
.center { --p:50%;}
.full {background-size:100% 3px;}
.active {color:#1A73E8;background-color:#E8F0FE}


text:
Q: ServletContext getResource not working I'm trying to use ServletContext.getResource to retrieve a java.net.url reference to an image file (which I will then include in a PDF library using iText).
When I use ServletContext.getRealPath("picture.jpg"), I get back a string URL. However, getResource always returns null.
Example 1:
String picture = ServletContext.getRealPath("picture.jpg");
// picture contains a non-null String with the correct path
URL pictureURL = ServletContext.getResource(picture);
// pictureURL is always null

Example 2:
URL pictureURL = ServletContext.getResource("picture.jpg");
// pictureURL is always null

So what is the correct way to build a java.net.URL object pointing to a file in my webapps/ folder? Why does getRealPath work but not getResource?
In case it helps at all, here is my folder structure
webapps -> mySite -> picture.jpg

Does my picture need to be stored in either WEB-INF or WEB-INF/classes to be read by getResource?

A: getRealPath() provides the operating specific absolute path of a resource, while getResource() accepts a path relative to the context directory, and the parameter must begin with a "/".   Try ServletContext.getResource ("/picture.jpg") instead.
Doc:
getResource

A:
Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root.

So you must provide the context-relative full path. For example:
URL pictureURL = servletContext.getResource("/images/picture.jpg");

(note the lower-cased servletContext variable)


text:
Q: How can we use multi-threading while working with linked lists I am fairly new to the concept of multi-threading and was exploring to see some interesting problems in order to get a better idea.
One of my friends suggested the following:
"It is fairly straight-forward to have a linked-list and do the regular insert, search and delete operations. But how would you do these operations if multiple threads need to work on the same list.
How many locks are required minimum. How many locks can we have to have optimized linked list functions?"
Giving some thought, I feel that a single lock should be sufficient to work with. We acquire the lock for every single read and write operation. By this I mean when we are accessing a node data in a list we acquire the lock. When we are inserting/deleting elements, we acquire lock for the complete series of steps.
But I was not able to think of a way where using more locks will give us more optimized performance.
Any help/pointers?

A: The logical extension of "one lock per list" would be "one lock per item".
The case when this would be useful would e.g. be if you're often only modifying a single item of the list.
For deletion and insertion, acquiring the proper locks gets more complicated, though. You'd have to acquire the lock for the item before and after, and you'd have to make sure to always acquire them in the same order (to prevent deadlocks). And there's of course also special cases to be considered if the root element has to be modified (and possibly also if it's a double-linked list or a circular linked list). This overhead resulting from the more complicated locking logic might lead to your implementation being slower again, especially if you often have to insert and delete from the list.
So I would only consider this if the majority of accesses is the modification of a single node.
If you're searching for peak performance for a specific use case, then in the end, it boils down to implementing both, and running performance comparisons for a typical scenario.

A: You definitely need at least one semaphore/lock to ensure list integrity.
But, presumably any operation on the list changes at most two nodes: The node being insert/changed/deleted and the adjacent node which points to it. So you could implement locking on a per-node basis, locking at most two nodes for a given operation. This would allow for a degree of concurrency when different threads accesses the list, though you'd need to distinguish between read and write locks to the get full benefit of this approach I think.

A: If you're new to multi-threading, embrace the notion that premature optimization is a waste of time.  Linked lists are a very straight-forward data structure, and you can make it thread-safe by putting a critical section on all reads and writes.  These will lock the thread into the CPU for the duration of the execution of the read/insert/delete operation, and ensure thread-safety.  They also don't consume the overhead of a mutex lock, or more complicated locking mechanism.
If you want to optimize after the fact, only do so with a valid profiling tool that gives you raw numbers.  The linked list operations will never end up being the biggest source of application slowdown, and it will probably never be worth your while to add in the node-level locking being discussed.

A: Using one lock for the entire list would completely defeat most reasons for multithreading in the first place.  By locking the entire list down, you guarantee that only one thread can use the list at a time.
This is certainly safe in the sense that you will have no deadlocks or races, but it is naive and inefficient because you serialize access to the entire list.
A better approach would be to have a lock for each item in the list, and another one for the list itself.  The latter would be needed when appending to the list, depending on how the list is implemented (eg, if it maintains a node count seperate from the nodes themselves).
However this might also be less than optimal depending on a number of factors.  For instance, on some platforms mutexes might be expensive in terms of resources and time when instantiating the mutex.  If space is at a premium, another approach might be to have a fixed-size pool of mutexes from which you draw whenever you need to access an item.  These mutexes would have some kind of ownership flag which indicates which node they are allocated to, so that no other mutex would be allocated to that node at the same time.
Another technique is to use reader/write locks, which will allow read access to any thread, but write access to only one, the two being mutually exclusive.  However it has been suggested in the literature that in many cases using a reader/write lock is actually less efficient than simply using a plain mutex.  This will depend on your actual usage pattern and how the lock is implemented.

A: You only need to lock when you're writing and you say there's usually only one write, so try read/write locks.


text:
Q: $_SERVER['REQUEST_METHOD'] == "POST" Não funciona PHP wordpress Estou tentando detectar um post num formulario mas não consigo, na verdade nao funciona.
<?php /* Template Name: Contato */

get_header();
get_template_part( 'components/header/header', 'text' );
$options = get_option('theme_options');
?>

    <?php
    if ($_SERVER['REQUEST_METHOD'] == "POST"){
        // envia o form / email
        send_contact_form();
        $resposta = "FUNCIONOO";
        echo "FUNCIONO";

    } else { //mostra o formulario
        ?>

            <form class="form-horizontal" method="post">

Fale conosco

                <fieldset>

                                 Nome*
                                 <input type="text" class="form-control input-custom" name="name" id="inputName" placeholder="">

                                 E-mail*
                                 <input type="text" class="form-control input-custom" name="email" id="inputEmail" placeholder="">

                                 Telefone
                                 <input type="tel" class="form-control input-custom" name="phone" id="inputPhone" placeholder="">

                                 Mensagem
                                 <textarea type="text" class="form-control input-custom" name="message" rows="3" id="inputMensagem" placeholder=""></textarea>

                                     enviar

<?php echo $resposta ?>

                </fieldset>
            </form>

    <?php } ?>

<?php
get_footer();?>

A: Seu formulário não tem um input ou button para funcionar.
Troque
enviar

por
<input type="submit" value="enviar" />

E ele vai enviar.


text:
Q: Function is being called before await finishes I was trying out some things with async/await and for some reason my function runs before my await is finished, can someone tell me why?

(function() {
  var posts = [{
      title: "Post 1",
      body: "This is post 1"
    },
    {
      title: "Post 2",
      body: "This is post 2"
    },
    {
      title: "Post 3",
      body: "This is post 3"
    }
  ];

  function GetPosts() {
    setTimeout(() => {
      let output = '';
      posts.forEach((post, index) => {
        output += `<li>${post.title}</li>`;
      });

      document.body.innerHTML = output;
    }, 1000);
  }

  function CreatePost(post) {
    setTimeout(() => {
      posts.push(post);
    }, 4000);
  }

  async function init() {
    await CreatePost({
      title: "Post 4",
      body: "This is post 4"
    });

    GetPosts();
  }

  init();

})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

A: The function CreatePost() is not async, it does not return a Promise. This is why putting await in front of its call does not have any effect.
In order to make it async let it create and return a Promise:
  async function CreatePost(post) {
    return new Promise((resolve) => {
      setTimeout(() => {
        posts.push(post);
        resolve();
      }, 4000);
    });
  }

The same for getPosts().

A: Since setTimeout doesn't return any promise. It'll not wait till CreatePost function gets executed. So wrapping the same thing inside a Promise will help to give the output that you are looking for.

(function() {
  var posts = [{
      title: "Post 1",
      body: "This is post 1"
    },
    {
      title: "Post 2",
      body: "This is post 2"
    },
    {
      title: "Post 3",
      body: "This is post 3"
    }
  ];

  function GetPosts() {
    setTimeout(() => {
      let output = '';
      posts.forEach((post, index) => {
        output += `<li>${post.title}</li>`;
      });

      document.body.innerHTML = output;
    }, 1000);
  }

//Wrap this with a new promise
  function CreatePost(post) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        posts.push(post);
        resolve();
      }, 3000);
    })

  }

  async function init() {
    await CreatePost({
      title: "Post 4",
      body: "This is post 4"
    });

    GetPosts();
  }

  init();

})();

A: If you want to use async, await is promise

(function () {
  var posts = [{
    title: "Post 1",
    body: "This is post 1"
  },
  {
    title: "Post 2",
    body: "This is post 2"
  },
  {
    title: "Post 3",
    body: "This is post 3"
  }
  ];

  function GetPosts() {
    return new Promise(resolve => {
      setTimeout(() => {
        let output = '';
        posts.forEach((post, index) => {
          output += `<li>${post.title}</li>`;
          resolve('success');
        });
        document.body.innerHTML = output;
      }, 1000);
    })
  }

  function CreatePost(post) {
    return new Promise((resolve) => {
      setTimeout(() => {
        posts.push(post);
        resolve('success')
      }, 4000);
    })
  }

  async function init() {
    const a = await CreatePost({
      title: "Post 4",
      body: "This is post 4"
    });
    const b = await GetPosts();
    return b
  }
  init();
})();

A: function CreatePost(post) {
  //setTimeout is non-blocking
  setTimeout(() => {
    posts.push(post);
  }, 4000);
}

You will basically not wait for the post to be pushed to the list. That is the reason it is not shown. if the interval in GetPosts was smaller than the on in CreatePost than it would display.
It has nothing to do with async/await. The call to CreatePost is first of all not async because you are not returning a Promise. The Second thing is that setTimeout will not block, so every code that runs after can basically be done before the callback will be called.
To make CreatePost really async just look at the answer of @axiac Function is being called before await finishes
Note: setTimeout is still non-blocking and the code won't work as expected. If this wasn't just exercise, I would say get rid of the setTimeouts.


text:
Q: How do I create a random integer that changes with each x value in a for loop in Java? Is there a way to make it so that if the output of the randNumber is lower than say, 75, the output of the randNumber will change to a lower number than 85? Like if the random number generator chooses 75 as the first number is there a way to change the value of the rest of the outputs after that to be lower than 85 (what it is set to now).
public static void Hypothetical() {
    int x;

    for (x = 0; x <= 4; x++) {
    Random z = new Random();
    int zNumber = z.nextInt(10-5) + 5;
    Random rand = new Random();
    int randNumber = rand.nextInt(85-65) + 65;
        if (x  == 0) {
            System.out.println("You may begin running.");
            //TimeUnit.SECONDS.(2);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (x == 1 ) {
            System.out.println("Your first lap was made in " + randNumber + " seconds");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (x==2) {
            System.out.println("Your second lap was made in " + (randNumber + zNumber) + " seconds");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (x==3) {
            System.out.println("Your third lap was made in " + (randNumber + zNumber) + " seconds");
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if (x==4) {
            System.out.println("Your final lap was made in " + (randNumber + zNumber) + " seconds");
        }
    }
}

}

A: cond = false;
loop
    if (cond)
        generate values lower than 85
    else
        generate number
        if number < 75, cond = true

A: As I am understanding your question, you want to change the ceiling of your random number. The easiest way I can think of doing this is to introduce modulo ceiling, as shown below. Although, I am not sure what your trying to do.
limitRanInt = false
loop
 if( limitRanInt || <rand#> <= 75){
   limitRanInt = true
   <rand#> = <rand#> % 85
   }
endloop


text:
Q: Перенаправление обращения к внешнему адресу на внутренний Есть рабочий сервер с готовым проектом на локалке, все работает отлично. но как мне прописать локальный айпи сервера на маршрутизаторе так, чтобы при запросе на внешний (статический айпи) или на домен, было перенаправтение в сервер. Model No. TL-WR840N - модель моего маршрутизатора.
Когда добавляю Static Route, а по маршруту ставлю внешний айпи, все вылетает. к слову порт 80/tcp открыт.

A:
как мне прописать локальный айпи сервера на рутере так чтоб при
запросе на внешний (статический айпи )или на домен было
перенаправтение в сервер

Для этого придуман (давным-давно) механизм, называемый NAT - Network Address Translation. Почему "трансляция"? Потому, что он переводит (транслирует) сокет Вашего локального сервера (а это - пара IP:Port) в сокет на Вашем роутере, который привязывается к глобальному адресу вашего роутера в интернете.
Грубо говоря, пара <ваш IP>:<Ваш порт> превращается в <IP роутера>:<Некий порт на роутере> и роутер, получая от Вас пакет преобразует его по правилам NAT во внешнее представление сокета, а получив пакет из инета, выполняет обратное преобразование и отдаёт полученный пакет Вашему серверу.
Управляется весь этот механизм (изначально)с помощью iptables.
Для начала, посмотрите вот это: https://ru.wikipedia.org/wiki/NAT


text:
Q: Will Feebas' distance travelled still count towards the evolution requirement if I unbuddy it now? Feebas can be evolved to Milotic with 100 candies after walking 20km with it.
I've walked mine 20km, but I still lack candies and I would rather walk another Pokemon until I get those 100 candies. If I unbuddy my Feebas now, do I have to walk 20km with it again when I have the candies?

A: No you are safe to equip a new buddy. I also had that problem and after achieving the required 100 candy I was free to immediately evolve my Feebas.
As credited to @yoozer8

Note that the distance walked is tied to the specific Feebas that was
  your buddy. If you have more than 1 (or if you hatch/catch a better
  one later), you'll have to walk the one you want to evolve, even if
  you've already walked another 20km


text:
Q: Scraping list in R I want to scrape a list of elements (name player, cost, buyer, seller, day) from a local HTML file, but I have a problem with the 2 and 3 when i try to scrape buyer and seller (in this case for the 1st transfer 'Computer' and 'Peter') and for the 2nd transfer 'Computer' and 'james')
document.querySelector("#pressReleases > ul > li:nth-child(**2**) > ul > li.text > div > strong:nth-child(2)")

document.querySelector("#pressReleases > ul > li:nth-child(**3**) > ul > li.text > div > strong:nth-child(2)")

How can scrape the li elements making this 2 variable?
I've tried this in R:
dades<- mylocalfile

player<-dades %>% html_nodes("ul.player li.text strong") %>% html_text() %>% trimws()
cost<-dades %>% html_nodes("ul.player li.text span") %>% html_text() %>% trimws()
buyer<-dades %>% html_nodes("#pressReleases > ul > li:nth-child(2) > ul > li.text > div > strong:nth-child(2)") %>% html_text() %>% trimws()
seller<-dades %>% html_nodes("#pressReleases > ul > li:nth-child(2) > ul > li.text > div > strong:nth-child(1)") %>% html_text() %>% trimws()
day<-dades %>% html_nodes("ul.player li.text time") %>% html_text() %>% trimws()

I detected that this 2  #pressReleases > ul > li:nth-child(2)  is variable for each li class="post pressRelease"
The html code:

   Fitxatges del dia
    09/08/2019

         Player1
         <time>09/08/2019 - 05:30</time>
         16.245.485 €

           D'
         computer
           a
         peter

        2º puja
        matheu:
        15.925.828 €

       Player2
       <time>09/08/2019 - 05:30</time>
       1.111.711 €

          D'
         computer
          a
         james

A: Here is a possible solution to get the buyer/seller:
# Read the local file
URL <- 'D:/Test/Test.html'
wp <- xml2::read_html(URL, encoding = 'utf-8')
# Extract the relevant nodes
node <- rvest::html_nodes(wp, '.from')
# Extract the names
seller <- gsub('.*D\'\r\n\\s+(.*?)\r\n\\s+a\\s?\r\n\\s+(.*?)\r\n.*', '\\1', rvest::html_text(node))
# [1] "computer" "computer"
buyer <- gsub('.*D\'\r\n\\s+(.*?)\r\n\\s+a\\s?\r\n\\s+(.*?)\r\n.*', '\\2', rvest::html_text(node))
# [1] "peter" "james"

A: Have you tried for buyers
#pressReleases .from strong:nth-child(1)

and for sellers
#pressReleases .from strong:nth-child(2)

Assuming you have read html into variable page then (extend to include your other vars)
buyers <- page %>% html_nodes("#pressReleases .from strong:nth-child(1)") %>% html_text
sellers <- page %>% html_nodes("#pressReleases .from strong:nth-child(2)") %>% html_text
df <- as.data.frame(cbind(buyers,sellers))

The dataframe then should be easy to export.