text:
Q: How to check if a file already contains an object? I am trying to add objects (people's names, phone numbers etc.) to a file and then reading it. When I run the program and add a few objects to the file, only the first object contains the header and the ones after the first one does not, which is what I want.
However, if I close the program and then rerun it, the previous objects are still there and functioning, but if I add a new object to the file, the program treats it as "the first object", so gives it a header, which causes an error when the program tries to read the information stored in the object.
This is my "add to file" code:
try {
        FileOutputStream fos = new FileOutputStream("outputfile.ser", true);
        oos = new ObjectOutputStream(fos);
    }
    catch (NotSerializableException e1) {
        System.out.println("An object was not serializable, it has not been saved.");
        e1.printStackTrace();
    }
    catch (IOException e1) {
        e1.printStackTrace();
    }

    JButton btnAddContact = new JButton("Add Contact");
    btnAddContact.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

                Address newContact = new Address(firstNameTextField.getText(), lastNameTextField.getText(), homePhoneNumberTextField.getText(), mobilePhoneNumberTextField.getText(), addressTextArea.getText(), emailTextField.getText());

                try {
                    oos.writeObject(newContact);
                }
                catch (IOException e1) {
                    System.out.println("An object was not serializable, it has not been saved.");
                    e1.printStackTrace();
                }

            dispose();
            firstNameTextField.setText("");
            lastNameTextField.setText("");
            homePhoneNumberTextField.setText("");
            mobilePhoneNumberTextField.setText("");
            addressTextArea.setText("");
            emailTextField.setText("");
        }
    });
    btnAddContact.setBounds(165, 384, 110, 46);
    contentPane.add(btnAddContact);

I also thought that if i checked if the file is empty or not using if (file.length() == 0) would work, but it still doesn't work. sample of my code with this implemented:
File file = new File("outputfile.ser");
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
ObjectOutputStream oas = AppendingObjectOutputStream(new FileOutputStream(file, true));
if (file.length() == 0){
                    try {
                        oos.writeObject(newContact);
                    }
                    catch (IOException e1) {
                        System.out.println("An object was not serializable, it has not been saved.");
                        e1.printStackTrace();
                    }
                } else {
                    try {
                        oas.writeObject(newContact);
                    }
                    catch (IOException e1) {
                        System.out.println("An object was not serializable, it has not been saved.");
                        e1.printStackTrace();
                    }
                }

public class AppendingObjectOutputStream extends ObjectOutputStream {

    public AppendingObjectOutputStream(OutputStream oas) throws IOException {
        super(oas);
    }

    protected void writeStreamHeader() throws IOException {
        // do not write a header, but reset:
        reset();
    }
}

Is there any way to solve this problem?

A: Your first FileOutputStream fos = new FileOutputStream(file); will overwrite any existing file.
Try at first to change it FileOutputStream fos = new FileOutputStream(file, true);.
But I discourage opening at the same time the same file. You probably need to rework the logic.


text:
Q: SQL : picking distinct values based on rank I'm trying to find out the rank/row_number of IDs in a dataset and assign one ID to one cluster based on rank. The catch is, the same ID can be rank 1 for two different clusters. In this case, if one ID has already been assigned to one cluster, then the next rank should be assigned to the other cluster.

CLUSTER
ID
RNK

CLST1
ID1
1

CLST1
ID2
2

CLST2
ID1
1

CLST2
ID2
2

In this dataset, if ID1 is assigned to CLST1, then ID2 must be picked for CLST2 based on rank. How can I achieve this in Redshift?

A: If you don't want duplicate rank numbers nor gaps use row_number().
The following script shows the difference between rank(), dense_rank() and row_number() when there is a duplicate value.

select
  id,
  rank() over (order by id) "rank",
  dense_rank() over (order by id) "dense_rank",
  row_number() over (order by id) "row_number"
from t;

id | rank | dense_rank | row_number
-: | ---: | ---------: | ---------:
 1 |    1 |          1 |          1
 2 |    2 |          2 |          2
 3 |    3 |          3 |          3
 3 |    3 |          3 |          4
 4 |    5 |          4 |          5
 5 |    6 |          5 |          6

MySQL db<>fiddle here
PostgreSQL db<>fiddle here

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a variable that contains an Operator in Java? I'm trying to write a program in 30 lines or less for my class (self imposed challenge).
The program asks the user a simple addition, division, multiplication, or subtraction question and the player answers, rinse and repeat 10 times, then the player is asked if they want to continue or end the program. The type of question (add, mult, etc.) should be selected randomly.
So that I don't need to use a huge switch case or if-else tree, I want to know if there is any way to contain an operator in a variable, and then use it later.
Example:
var operator = +;
int[] n = {1, 2};
System.out.println(n[0] operator n[1]);

And the output would be "3"
That's an example of what kinda thing I want to do. Is this possible?

A: No, you can't do that directly.  You will have to make a type that represents an operator.
The most common way to do this is with an enum:
enum Operator {
  PLUS {
    @Override int operate(int a, int b) {
      return a + b;
    }
  };

  abstract int operate(int a, int b);
}

Operator operator = Operator.PLUS;
int[] n = {1, 2};
System.out.println(operator.operate(n[0], n[1]));

A: It's not possible to assign an operator to a variable.

in 30 lines or less ... the program asks the user a simple addition, division, multiplication, or subtraction

If you want to implement it using as fewer lines as possible, build-in functional interfaces will be a good choice. For that, you need IntBinaryOperator that represents an operation done on two int arguments.
Functional interface can be implemented either by using a lambda expression or a method reference (also, you can do that with an anonymous inner class as well by it'll not be shorter). Addition operation can be represented like that:
IntBinaryOperator add = Integer::sum; // or (i1, i2) -> i1 + i2

The type of question (add, mult, etc.) should be selected randomly

For that, firstly, you need to define a Random object. In order to obtain a random integer in the given range, use nextInt() method that expects an int bound, and returns a value from 0 up to the bound (exclusive):
rand.nextInt(RANGE)

To avoid hard-coding, RANGE should be defined as a global constant.
Because your application has to interact with the user, every operation should be associated with a name that will be exposed to the user.
It can be done by declaring a record (a special kind class with final field and auto-generated constructor, getters, hashCode/equals, toString()). Syntax for declaring records is very concise:
public record Operation(String name, IntBinaryOperator operation) {}

Records representing arithmetical operations can be stored in a list. And you can pick an operation by generating a random index (from 0 up to list size).
operations.get(rand.nextInt(operations.size()))

Unlike the common getters, names of getters that will be generated by the compiler for the record will identical to names of its fields, i.e. name() and operation().
In order to use the function retrieved from the record, you need to invoke the method applyAsInt() on it, passing the two previously generated numbers.
That's how it might look like.
public class Operations {
    public static final int RANGE = 100;
    public static final Random rand = new Random();

    public record Operation(String name, IntBinaryOperator operation) {}
    public static final List<Operation> operations =
            List.of(new Operation("add", Integer::sum), new Operation("sub", (i1, i2) -> i1 - i2),
                    new Operation("mult", (i1, i2) -> i1 * i2), new Operation("div", (i1, i2) -> i1 / i2));

    public static void main(String[] args) {
        // you code (instansiate a scanner, enclose the code below with a while loop)
        for (int i = 0; i < 10; i++) {
            Operation oper = operations.get(rand.nextInt(operations.size()));
            int operand1 = rand.nextInt(RANGE);
            int operand2 = rand.nextInt(RANGE);
            System.out.println(operand1 + " " + oper.name() + " " + operand2); // exposing generated data to the user
            int userInput = sc.nextInt();                                      // reading user's input
            int result = oper.operation().applyAsInt(operand1,operand2);       // exposing the result
            System.out.println(result + "\n__________________");
        }
        // termination condition of the while loop
    }
}

That's an example of the output the user will see:
38 add 67
105 // user input
105
_____________________
97 sub 15
...

A: Unfortunately java supports neither operator overloading nor infix notation, making it impossible to do so in source code.


text:
Q: I need to redirect a file from server to a folder without htaccess i have a file on my "website/folder/file" which i would like to redirect to prevent user to access that file, without using htaccess.
My file is a huge DB containing url's,  i don't want the users access to that file by typing the direct URL to the file.
That file is called & used by my chrome extension, who block access to the user if he tries to reach one of the url's in that DB.
Problem is by typing the direct url to that file we have access...
i tried everything with the .htaccess file, i know we can block, redirect, etc with the .htaccess file but if i redirect or block the url of the DB with the htaccess, my extension doesn't work anymore because the DB is blocked by the htaccess file.
so i'm trying to find a solution, maybe is an !
my background.js
'use strict';
let db = []; // session Global
// ----- parse & cache the database data
fetch('http://thmywebsite.com/folder/db.dat')
.then(response => response.text())
.then(text => { db = text.trim().split(/[\r\n]+/); })
.catch(error => console.log(error));
chrome.webRequest.onBeforeRequest.addListener(details => {
let url = new URL(details.url);
return { cancel: url && url.hostname && db.includes(url.hostname) };
},
{ urls: ["http://*/*", "https://*/*"] },
["blocking"]
);
chrome.extension.isAllowedIncognitoAccess(function (isAllowedAccess) {
if (isAllowedAccess) return; // Great, we've got access
})

A: You can't realistically do this. You can't block a resource that needs to be available publicly (by your client-side script).
You can potentially make this a little harder for someone wanting your DB, by perhaps sending a unique HTTP request header as part of your fetch(). You can then check for the presence of this header server-side (in .htaccess) and block the request otherwise. This prevents a user from casually requesting this file directly in their browser. However, this is trivial to bypass for anyone who looks at your script (or monitors the network traffic) as they can construct the request to mimic your script. But let's not forget, your script downloads the file to the browser anyway - so it's already there for anyone to save.
You need to rethink your data model. If you don't want the DB to be publicly accessible then it simply can't be publicly accessible. Instead of your script downloading the DB to the client and processing the request locally, you could send the request to your server. Your server then performs the necessary lookup (on the "hidden" database) and sends back a response. Your script then acts on this response.


text:
Q: Contact form returns a 404 error I have a contact form on my website (https://www.clay-and-paint.com). Before it works normally, I received emails from customers but now (I have an https) it doesn't work anymore.
I have a 404 error.
My code on my CMS page contact is:
{{block type="core/template" name="contactForm" form_action="/contacts/index/post" template="contacts/form.phtml"}}

My code on my form.phml is:

<?php echo $this->getMessagesBlock()->getGroupedHtml() ?>

<?php echo Mage::helper('contacts')->__('Contact Us') ?>

<?php
   $url = Mage::getUrl();
   if(isset($_SERVER['HTTPS']))
   {
    $url = str_replace ('http://', 'https://', $url);
   }
?>
<form action="<?php echo $this->getFormAction(); ?>" id="contactForm" method="post">

<?php echo Mage::helper('contacts')->__('Contact Information') ?>

...

<?php echo Mage::helper('contacts')->__('* Required Fields') ?>

        <input type="text" name="hideit" id="hideit" value="" style="display:none !important;" />
        <button type="submit" title="<?php echo Mage::helper('contacts')->__('Submit') ?>" class="button"><?php echo Mage::helper('contacts')->__('Submit') ?></button>

</form>

For the

<form action="<?php echo $this->getUrl('contacts/index/post', array('_secure'=>true)) ?>

or:
<form action="https://www.clay-and-paint.com/index.php/contacts/index/post/" id="contactForm" method="post">

But it always returns me an 404 error.
Thank for your help.
Warui
PROBLEM SOLVED! I've made a mistake on my config.xml.


text:
Q: How can I customize tab completion in Perl's Term::Shell? I am using Term::Shell package to implement a CLI tool. This package provides a API: comp_CMD.
This function is invoked whenever the user presses the TAB.
My requirement here is:
shell> stackTAB
over under
`shell>stack overTAB
flow sample junk
But the default comp_CMD provides only one set of TAB options like
shell> stack TAB
over under
`shell>stack overTAB
over under ### THE PROBLEM IS HERE
Instead of over under  here, I want to get flow sample junk.

A: With the comp_* style handlers one can only match one's completions against the last incomplete word. Fortunately, however, you can get the desired result by overriding the catch_comp function like below; it lets one match against whole command line:
my %completion_tree = (
    stack => { under => [],
               over  => [qw(flow sample junk)] }
);

sub catch_comp {
    my $o = shift;
    my ($cmd, $word, $line, $start) = @_;

    my $completed = substr $line, 0, $start;
    $completed =~ s/^\s*//;

    my $tree = \%completion_tree;
    foreach (split m'\s+', $completed) {
        last if ref($tree) ne 'HASH';
        $tree = $tree->{$_};
    }

    my @completions;
    $_ = ref($tree);
    @completions =      @$tree if /ARRAY/;
    @completions = keys %$tree if /HASH/;
    @completions =      ($tree)if /SCALAR/;

    return $o->completions($word, [@completions]);
}

A: One more thing i want to add here..
After overriding rl_complete subroutine, we also have to override comp__ (Default subroutine called for TAB) to avoid repeated printing of the subcommands.


text:
Q: Java SE - Advice RE: storing configuration data I'm writing a Java SE 7 desktop application.  I will need to store data such as configuration settings and 2 user accounts (an admin and everyone).  The simplest method seems to be just writing a text file but I don't see any effective means for protecting that data and it is sensitive.  I'm thinking SQLite is probably the best tool for me but I was wondering if anyone might have any suggestions as to something even smaller, more lightweight, simpler -- as there just isn't enough data that needs storing to justify a whole database it seems.
Thanks!
Irongleet

A: You can (and should) use the Preferences API for that. On Windows, it will write to the Registry (so it's different for each user).


text:
Q: ios detect bluetooth state changes in terminated state I initialized CBCentalManager in my app. I see bluetooth state changes in foreground and background. But when I swipe/kill application from task manager. It's stopped and doesn't work. How can I detect bluetooth state changes when app terminated by user ? Is it possible ?

A: When the app is killed by the user you cannot detect your bluetooth state. You can detect the bluetooth state when your app is active again.


text:
Q: When I try to apply Circle function to folium map it gives a "NAN' error Here is the code:
    import folium
    import pandas as pd

        corona_map = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_d

ata/csse_covid_19_daily_reports/07-07-2020.csv')
    corona_map.head()
    worldMap = folium.Map(location = [ 31.7917 , -7.0926 ], tiles = 'cartodbpositron', zoom_start = 6)
    folium.Circle(location = [ 31.7917 , -7.0926 ], radius = 100*1000, color = 'yellow', fill = True, popup='Confirmed: {}'.format(20)).add_to(worldMap)

    def map_marker(x):
      folium.Circle(location= [x[0], x[1]],
      radius = float(x[2])*10,
      popup = 'Confirmed: {}'.format(x[3])).add_to(worldMap)

    corona_map[['Lat', 'Long_', 'Confirmed', 'Combined_Key']].apply(lambda x: map_marker(x), axis  = 1)

the Error:
ValueError                                Traceback (most recent call last)
<ipython-input-146-36a6b307c9ea> in <module>()
     10   radius = float(x[2])*10,
     11   popup = 'Confirmed: {}'.format(x[3])).add_to(worldMap)
---> 12 corona_map[['Lat', 'Long_', 'Confirmed', 'Combined_Key']].apply(lambda x: map_marker(x), axis  = 1)

7 frames
pandas/_libs/reduction.pyx in pandas._libs.reduction.compute_reduction()

pandas/_libs/reduction.pyx in pandas._libs.reduction.Reducer.get_result()

/usr/local/lib/python3.6/dist-packages/folium/utilities.py in _validate_coordinates(coordinates)
     53     if _isnan(coordinates):
     54         raise ValueError('Location values cannot contain NaNs, '
---> 55                          'got:\n{!r}'.format(coordinates))
     56     coordinates = _iter_tolist(coordinates)
     57     return coordinates

ValueError: Location values cannot contain NaNs, got:
[nan, nan]

when I execute the last line of code it gives me this error, I searched on stackoverflow but couldn't fix it,
thank you everyone.

A: I found the solution, I just added these two line from this question:
Removing NaN Values from csv
here is the two lines:
corona_map = corona_map.replace('',np.nan)
corona_map = corona_map.dropna(axis="rows", how="any")

I added them before the last line in the code.


text:
Q: UI didn't update because of NSOperationQueue waitUntilFinished YES I got an issue. The scenario is like this: I got an NSOperationQueue that contain various NSOperationQueue that need to waitUntilDone:YES. And I need to update the UI too as the queue or the operation is running. What is the best way to handle this situation?
I have tried performSelectorOnMainThread, but is it necessary to use this method every time I need to update the UI. It is seems not a good solution.
- (void)loadPreviewPageWithMagazineID:(NSString *)magazineID userID:(NSString *)userID {
NSMutableArray *operationArray = [NSMutableArray array];
for (NSInteger i = 1; i <= _numTotalPages; ++i) {
    //NSLog(@"currenpage = %d, index = %d",_selectedPage,pageIndex);
    NSDictionary *arguments = [NSDictionary dictionaryWithObjectsAndKeys:magazineID,
                               @"itemID", userID, @"userID", [NSNumber numberWithInt:i],
                               @"pageNumber", nil];
    AFOperation *imageOperation =
        [[AFOperation alloc] initWithTarget:self
                                   selector:@selector(savePageToDisk:)
                                     object:arguments];
    [imageOperation addObserver:self forKeyPath:@"isFinished" options:0 context:nil];
    [imageOperation setUserInfo:arguments];
    [operationArray addObject:imageOperation];
    [imageOperation release];
}
[_imageQueue addOperations:operationArray waitUntilFinished:YES];
}

- (void)processingMagazine:(NSDictionary *)arguments {
// load pdf document from decrypted data
NSString *userID = [arguments objectForKey:@"userID"];
NSString *magazineID = [arguments objectForKey:@"itemID"];

[self loadPreviewPageWithMagazineID:magazineID userID:userID];
}

So each time to update UI I need to call
[_collectionCoverView performSelectorOnMainThread:@selector(setDownloadProgress:)
                                       withObject:[NSNumber numberWithFloat:progress]
                                    waitUntilDone:YES];

Is there any appropriate way to handle the UI?

A: I didn understand much from your code. But to accomplish what you want, you can add the UI update  code at the end of your AFOperation method. I mean to say, UI will be updated automatically once  some processing is done, if you add it in the operation method.
Also generally UI update happens in MainThread. SO there is nothing wrong in calling performSelectorInMainThread.


text:
Q: Java Kafka Stream - Avro Serializer Error I am sending avro data to sink topic using kafka streams in java using generic avro serde.
error stack:
org.apache.kafka.common.errors.SerializationException: Error serializing Avro message
caused by java.lang.IllegalStateException: Too many schema objects created for TestTopic!
   at io.confluent.kafka.schemaregistry.client.CachedSchemaRegistryClient.register(CachedSchemaRegistryClient)

java code:

public Topology createTopology(String inputTopic, String outputTopic, String badRecord, String schemaRegistryUrl) {
        StreamsBuilder builder = new StreamsBuilder();
        try {
            KStream<String, String> textLines = builder.stream(inputTopic,
                    Consumed.with(Serdes.String(), Serdes.String()));
            GenericAvroSerde gserde = new GenericAvroSerde();

            gserde.configure(Collections.singletonMap(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG,
                    schemaRegistryUrl), false);

            KStream<String, String>[] branches = textLines.branch(
                    (k,v) -> validateData(v) ,
                    (k,v) -> true
                    );

            branches[0].to(badRecord,Produced.with(Serdes.String(), Serdes.String()));
            branches[1].mapValues(v -> someProcessing(v, avObj.convert(v)))
                         .filterNot((k, v) -> v == null)
                         .to(outputTopic, Produced.with(Serdes.String(), gserde));

        } catch (Exception e) {
            logger.error("Error while consuming message:", e);
        }
        return builder.build();
    }

Requesting you to kindly help with the solution.


text:
Q: libusb basic example wanted I'm writing user-space program that is intended to control some device via usb so I decided to use libusb (libusb-1.0) to send control messages to and receive responses from that device.
But I constantly receive the following bunch of errors from my code (even when it's executed using 'sudo'):
USB error: could not set config 0: Device or resource busy
set configuration: failed
Check that you have permissions to write to 007/012 and, if you don't, that you set up hotplug (http://linux-hotplug.sourceforge.net/) correctly.
USB error: could not claim interface 0: Device or resource busy
claim interface: failed
USB error: error submitting URB: No such file or directory
bulk writing: failed
USB error: error submitting URB: No such file or directory
bulk reading: failed
response was:

The code is:
usb_dev_handle* find_device ();

int
main (int argc, char *argv[])
{
    usb_dev_handle* udev;
    int status;
    char request[] = "K1"; // 'ping' command used to check communication
    char response[256];

    udev = find_device ();
    // udev is successfully found here

    status = usb_set_configuration (udev, 0);
    printf ("set configuration: %s\n", status ? "failed" : "passed");

    status = usb_claim_interface (udev, 0);
    printf ("claim interface: %s\n", status ? "failed" : "passed");

    status = usb_bulk_write (udev, 3, request, sizeof (request), 500);
    printf ("bulk writing: %s\n", status ? "failed" : "passed");

    status = usb_bulk_read (udev, 2, response, sizeof (response), 500);
    printf ("bulk reading: %s\n", status ? "failed" : "passed");

    printf ("response was: %s\n", response);

    usb_close (udev);

    return 0;
}

What's wrong with the code? And how it could be fixed?
OS: Ubuntu 10.10

A: Don't you need to open() the device before you set its configuration and claim it?

A: here's a generic example of a libusb program that you can adapt as needed.
also see the API, which is great!
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <libusb.h>
#include <err.h>

#define MFGR_ID 0 // given manufacturer ID
#define DEV_ID 0  // given device ID

/* If device IDs are not known, use libusb_get_device_list() to see a
list of all USB devices connected to the machine. Follow this call with
libusb_free_device_list() to free the allocated device list memory.
*/

int main() {
    int init = libusb_init(NULL); // NULL is the default libusb_context

    if (init < 0) {
        errx(1,"\n\nERROR: Cannot Initialize libusb\n\n");
    }

    struct libusb_device_handle *dh = NULL; // The device handle
    dh = libusb_open_device_with_vid_pid(NULL,MFGR_ID,DEV_ID);

    if (!dh) {
        errx(1,"\n\nERROR: Cannot connect to device %d\n\n",DEV_ID);
    }

    // set fields for the setup packet as needed
    uint8_t       bmReqType = 0;   // the request type (direction of transfer)
    uint8_t            bReq = 0;   // the request field for this packet
    uint16_t           wVal = 0;   // the value field for this packet
    uint16_t         wIndex = 0;   // the index field for this packet
    unsigned char*   data = ' ';   // the data buffer for the in/output data
    uint16_t           wLen = 0;   // length of this setup packet
    unsigned int     to = 0;       // timeout duration (if transfer fails)

    // transfer the setup packet to the USB device
    int config =
    libusb_control_transfer(dh,bmReqType,bReq,wVal,wIndex,data,wLen,to);

    if (config < 0) {
        errx(1,"\n\nERROR: No data transmitted to device %d\n\n",DEV_ID);
    }

    // now you can use libusb_bulk_transfer to send raw data to the device

    libusb_exit(NULL);
}

A: Answering this question as I had faced this issue on the same OS and was able to solve in the following manner:
Download and Compile the latest libusb source code 1.0.8.
Following are some API calls that I used in order to claim USB interface 0:
libusb_init(NULL);
libusb_open_device_with_vid_pid(NULL, vendor_id, product_id);
libusb_detach_kernel_driver(devh, 0);
libusb_claim_interface(devh, 0);
libusb_close(devh);
libusb_exit(NULL);

Description of the variables in the above example:
static struct libusb_device_handle *devh = NULL;
uint16_t vendor_id;
uint16_t product_id;

To get the vendor ID and product ID, you may run the following commands (Ex. my device info)

$ lsusb
  ...
  Bus 001 Device 013: ID 0930:6544 Toshiba Corp. Kingston DataTraveler 2.0 Stick (2GB)
  ...

The bold colon delimited string contains vendor and product id respectively.
How to compile the code:
I used the following command to compile my code:

/bin/bash libtool --silent --tag=CC --mode=link g++ -Wall -Wundef -Wunused -Wshadow -D_DEBUG -I../libusb -g -O2   -o read read.cpp ../libusb/libusb-1.0.la -lusb-1.0 -lrt

Copy libtool to the compilation area from the extracted libusb-1.0.8 directory.
Hope this helps.


text:
Q: PhoneGap file transfer plugin parameters to ASP.NET service I want to pass parameters from the PhoneGap file transfer plugin to an ASP.NET MVC web service.
So I prepared Params in JavaScript :
 var Params = {};
    Params.Order = $("#Order").val();
alert($("#Order").val());//It works it is not null
    Params.latitude = $("#latitude").val();
    Params.longitude = $("#longitude").val();
    options.Params = Params;
    ft = new FileTransfer();
    ft.upload(sPicData, encodeURI("../Mobile/UploadPhoto"), win, fail, options);

Now I want to acces the Params from my ASP.NET MVC web service, but this code gives an error (Null exception).
   [HttpPost]
    public JsonResult  UploadPhoto()
    {
         // File upload code here and it works well.
         // File upload work but there is problem with Params
         System.Collections.Specialized.NameValueCollection parameters = Request.Params;
         string[] imageNum = parameters.GetValues("Order");
// string order=imageNum[0]
         string[] latitude = parameters.GetValues("latitude");
         string[] longitude = parameters.GetValues("longitude");
//other codes
    }

A: function photoUpload() {

    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = sPicData.substr(sPicData.lastIndexOf('/') + 1);
    options.mimeType = "image/jpeg";
    options.chunkedMode = false;
    var params = new Object();

    navigator.geolocation.getCurrentPosition(
        function(position) {
        params.fileKey = "file";
        params.longitude = position.coords.longitude;
        params.latitude = position.coords.latitude;
        params.altitude = position.coords.altitude;
        params.accuracy = position.coords.accuracy;
        params.altitudeAccuracy = position.coords.altitudeAccuracy;
        params.heading = position.coords.heading;
        params.speed = position.coords.speed;
        params.timestamp = position.timestamp;

        //alert(params.longitude + ',' + params.latitude);

        options.params = params;

        ft = new FileTransfer();
        ft.upload(sPicData, "http://YOURSERVER/upload.aspx", win, fail, options);
        });

}
Try this, it works for me.
Just grab the geo data in the different params as ordinary posted form fields.

A: I ran into the same problem here.  How to use phonegap FileTransfer parameters with .asmx web service
Try changing
System.Collections.Specialized.NameValueCollection parameters =
    Request.Params;

to
System.Collections.Specialized.NameValueCollection parameters =
    HttpContext.Current.Request.Params;


text:
Q: vb.net downloading a file without popups I am trying to download tracking information from FedEx's website. First I have to pass login credentials and then navigate to a webpage which triggers an automatic download. My code so far works fine for this. However; as soon as the download is triggered a popup comes up asking if I want to save the file and then when I click save I asks where I want to save the file to. I want to disable the popups and have the file just automatically saved in my downloads folder. Is there a way to do this? Thanks in advance for any help!
Here is my code so far.
    Dim WebBrowser1 As New WebBrowser
    Dim url As String = "https://www.fedex.com/insight/manifest/manifest.jsp?&__QS=252D0F3B4E380B211B122B1A09251510050E0F5C273A223E34360539237976645E45745E57776C&"
    WebBrowser1.Navigate(url)
    WebBrowser1.ScriptErrorsSuppressed = True
    Threading.Thread.Sleep(2000)
    Application.DoEvents()
    Do Until WebBrowser1.IsBusy = False
        Threading.Thread.Sleep(1000)
        Application.DoEvents()
    Loop
    WebBrowser1.Document.GetElementById("username").SetAttribute("value", "MyUsername")
    WebBrowser1.Document.GetElementById("password").SetAttribute("value", "MyP@ssw0rd")
    WebBrowser1.Document.GetElementById("login").InvokeMember("click")
    Threading.Thread.Sleep(1000)
    Application.DoEvents()
    Do Until WebBrowser1.IsBusy = False
        Threading.Thread.Sleep(1000)
        Application.DoEvents()
    Loop
    WebBrowser1.Navigate("https://www.fedex.com/insight/manifest/download_post.jsp?VIEW=|Outbound_View&INFOTYPE=STATUS")
    Do Until WebBrowser1.IsBusy = False
        Threading.Thread.Sleep(1000)
        Application.DoEvents()
    Loop

So I tried this code but all this does is still just download the page's source.
Using client As New WebClient()
        client.Headers("User-Agent") = "Mozilla/4.0"
        client.Credentials = New NetworkCredential("Username", "P@sword")
        client.Credentials = CredentialCache.DefaultCredentials ' << if Windows Authentication
        Dim content As String = client.DownloadString("https://www.fedex.com/insight/manifest/download.jsp?VIEW=/Outbound_View")
        Console.WriteLine(content.Substring(0, 15))
    End Using

I checked the webpage's source again to try to find a different url but also could not find anything else. I was wondering if it would be easier to download using WebBrowser.Navigate and then suppress the popups. Is there away to suppress or get rid of the download popups in vb? I am just not having much success with the WebClient. Thanks for all the help as I am still pretty new at vb.net!


text:
Q: Android Table Layout add button programmatically I am using reflection on my project. And I am adding a button dynamically of fields.
But I need orders for add button. 3 button per line.
How can I do this in code?
Like this:


text:
Q: UWP Grid Transitions I tried to create a transition for my pop up grid (usercontrol).
It work well, but just once, after that, the transition doesn't work, furthermore, I havn't the reverse transition when I close my grid
Xaml UserControl:
<UserControl Visibility="Collapsed">

    <Grid Background="red">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid.Transitions>
            <TransitionCollection>
                <EdgeUIThemeTransition Edge="Bottom"/>
            </TransitionCollection>
        </Grid.Transitions>

        <StackPanel>
            <Button Content="Close" Click="close_Click"/>
        </StackPanel>
    </Grid>
</UserControl>

C# UserControl:
public sealed partial class MyUserControl1 : UserControl
{
    public MyUserControl1()
    {
        this.InitializeComponent();
    }

    private void close_Click(object sender, RoutedEventArgs e)
    {
        Visibility = Visibility.Collapsed;
    }
}

Xaml Page:
<Page>
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <local:MyUserControl1 x:Name="popUp"/>
        <Button Content="Open" Click="Open_Click"/>
    </Grid>
</Page>

C# Page:
private void Open_Click(object sender, RoutedEventArgs e)
{
    popUp.Visibility = Visibility.Visible;
}

i think the probleme is Visibility, but i need it to show and hide my control, should i use visual state in my usercontrol ?

A: Now i use:
C# UserControl(delete the usercontrol):
private void close_Click(object send, RoutedEventArg e)
{
    ((Panel)this.Parent).Children.Remove(this);
}

Xaml UserControl(i set the transition here)
<UserControl.Transitions>
    <TransitionCollection>
        <EdgeUIThemeTransition Edge="Botom"/>
    </TransitionCollection>
</UserControl.Transitions>

c# page(create an user control):
MyUserControl cont = new MyUserControl();
MygridName.children.Add(cont);

A: In the click_Close statement have you tried using
this.Visibility = Visibility.Collapsed;

because the way I am reading it, there doesn't seem to be a targeted element right now.
I admit, I have not tested this - it is just something I noticed and hopefully it works and saves you some coding. (I know just enough C# to be dangerous >=D )


text:
Q: Best practices to build multi room (video and chat) with permissions in django and flutter So past couple of days I have been looking into building multi room, where users are able to either chat, spectate or make a video calls dependent on their permissions in Django(DRF) backend and flutter frontend.
For Django I found that I need to use, channels and web socket.
Alternatively for flutter I found about stream platform (getstream.io) that helps to do that.
At the end of the day I got overwhelmed and confused. I do not know where to begin, or what is the best approach to what I am looking for. I am very comfortable with working DRF and using dryrestpermissions to permit users some actions, however I am not sure how to integrate that with the multi room, websockets and then access that through flutter...
Either way please give me your ideas about this, best practices and where should I begin?
Thank you!

A: You could use Django backend as room server, which is named signaling server for WebRTC. The room server used to create and manage rooms, to allow flutter clients to list the room, to enter the room and get the streams of other clients.
While from the point of view of streaming, you should use WebRTC, rather than live streaming. Because for video chat, the lagging should <400ms, which is easy for WebRTC to do this, generally ~100ms.

Never use live streaming, whatever neither RTMP/HLS nor LLHLS/DASH, normally >1s latency.

If you want a fast overview, please try the demo of SRS: VideoRoom, or other WebRTC sfu like mediasoup or janus.


text:
Q: How to return a connection from a callback in node I want to create a db.js file that all my other files can use. The idea is that the connection created in this db.js file can be reused without reconnecting to database everytime i make a call.
db.js
var nodeq = require("node-q");
var connection;

nodeq.connect({host: "192.168.1.1", port: 5000}, function(err, con) {
    if (err) throw err;
    connection = con;
    console.log("KDB connected");
  });

module.exports=connection;

I want to do something like above(doesnt work) But the idea is in my app.js i will set
var db = require("./db")

and it will return the connection.

A: You could wrap the .connect() call in a promise and return this promise from your module, e.g.
const nodeq = require("node-q");

module.exports = new Promise( (resolve,reject) => {
  nodeq.connect({host: "192.168.1.1", port: 5000}, function(err, con) {
    if (err) return reject(err);
    console.log("KDB connected");
    resolve(con);
  });
});

Then in your caller you can await this promise (still needs error handling, but should give you a start):
const dbConnection = await require("./db");

or you do:
const dbConnPromise = require("./db");
//... then somewhere in your code where you need the db-connection, you can do:

async function doDbStuff() {
   const db = dbConnPromise();
   const result = await db.query(...);
}


text:
Q: If JavaScript Object Properties Are Empty Strings I am making a form in Angular JS and want the submit button to be disabled (ng-disabled) until the models associated with the form are all populated, meaning that the strings are no longer empty and the integers are no longer zero.
Dealing with the numbers is easy enough, but the other models that aren't prices are all stored in one object, and are all empty strings. I was hoping there was an easy one line solution I could use in an ng-disabled to test if this object no longer contained empty strings for any of its properties.
Anyway, here is some code to make it clear:

    Pickup Date
    <select name="pickupDate" ng-model="Oproperties.pickupDate">
        <option value="Tuesday">Tuesday - November 22nd</option>
        <option value="Wednesday">Wednesday - November 23rd</option>
        <option value="Thursday">Thursday - November 24th</option>
    </select>

        First Name
        <input type="text" class="form-control" ng-model="Oproperties.firstName" placeholder="Jill">

        Last Name
        <input type="text" class="form-control" ng-model="Oproperties.lastName" placeholder="Smith">

    Phone
    <input type="text" class="form-control" ng-model="Oproperties.phone" placeholder="Phone Number">

    Email
    <input type="text" class="form-control" ng-model="Oproperties.email" placeholder="yourname@email.com">

    @{{key}}

        @{{bread.Name}}
        <select name="@{{bread.Name}} quantity" ng-options="quantityOption as quantityOption.value for quantityOption in quantityOptions track by quantityOption.value" ng-model="bread.quantity" ng-change="calculate()"></select>
        </select>

@{{bread.Price|currency}} @{{bread.details}}

<button ng-disabled="Oproperties.containsEmptyString()&&totalPrice===0" ng-click="submitOrder()" class="btn btn-default">Submit</button>

The object looks like:
 $scope.Oproperties=
    {
    pickupDate:"",
    firstName:"",
    lastName:"",
    phone:"",
    email:""
    }

So basically, what would I do instead of Oproperties.containsEmptyString() which is currently just conceptual filler?

A: You can wrap all your inputs inside a form element named myForm, then add the required attribute to your inputs and then set
ng-disabled="myForm.$invalid"
to your submit button.

A: You want to wrap your elements in a form and move the ng-click="submitOrder()" to the form at ng-submit="yourFormName.$valid && submitOrder()".
This will mean that the form only gets submitted if all the field are validated properly.


text:
Q: Mode for _mm_cmpistrm SSE4.2 intrinsic I'm trying to figure out how to set the "mode" flag for the _mm_cmpistrm SSE4.2 intrinsic. I have a regular C string (char*) that I am loading into an __m128i type with _mm_lddqu_si128. I was going to use unsigned bytes with regular string comparison:
    _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_EACH

But I'm confused about what to set for the unit vs. bit mask. Here are the macros from smmintrin.h in GCC 4.3.2:
    /* These macros specify the output selection in _mm_cmpXstrm ().  */
    #define _SIDD_BIT_MASK          0x00
    #define _SIDD_UNIT_MASK         0x40

I think I understand what the bit mask is: I will get a 1 in bits 0..15 if the char in that position differs between the two strings. But what does the unit mask do?

A: For _SIDD_BIT_MASK you'll get a mask that is all 1 if the strings are equal and all 0 if they are unequal; if you're doing a _SIDD_UBYTE_OPS then you'll get 16 bits returned (one for each character in the string).
With _SIDD_UNIT_MASK however you'll get the same mask but expended to 16 bytes instead. Eg bits 0..15 will all be 1 if the comparison of the first two characters in the string is true. And bits 16..31 for character two etc.


text:
Q: Getting Date in HTTP format in Java I'm trying to get a String of a date in Java in the format specified in HTTP 1.1. Which, as far as I can tell, is:

Fri, 31 Dec 1999 23:59:59 GMT

With the time always being GMT.
What would be the easiest way to get this from Date/Calendar/?

A: If you are not afraid of additional dependencies, you can use apache DateUtils:
import org.apache.http.impl.cookie.DateUtils;
DateUtils.formatDate(new Date(System.currentTimeMillis()));
// Tue, 17 Apr 2012 18:59:02 GMT

This will format your date with respect to RFC 822 RFC1123.

A: java.time
EDIT:
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH).withZone(ZoneId.of("GMT"))
is the way to do it with pure java.time. HTTP 1.1 is to not a 100% match with RFC 1123, so using the java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME formatter will fail for day-of-month less than 10. (thanks to @PavanKamar and @ankon for pointing that out)
Note: to be backwards compliant, you would need to also support the other two formats specified by RFC 2616

A: In case someone else will try to find the answer here (like I did) here's what will do the trick:
String getServerTime() {
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat(
        "EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    return dateFormat.format(calendar.getTime());
}

in order to set the server to speak English and give time in GMT timezone.

A: I know this is a late response but just wanted to add it for completeness.
You did not mention what you need the string for. But if you need it for an HTTP response header, you can use HttpServletResponse.setDateHeader(). It does all the formatting for you.

A: If you're using Joda-Time (which I would highly recommend for any handling of dates and times in Java), you can do:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

...

private static final DateTimeFormatter RFC1123_DATE_TIME_FORMATTER =
    DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss 'GMT'")
    .withZoneUTC().withLocale(Locale.US);

...

RFC1123_DATE_TIME_FORMATTER.print(new DateTime())

A: Calendar calendar = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
System.out.println("Date: " + dateFormat.format(calendar.getTime()));

You can play with it. The documentation is here:
http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

A: Two-digit day-of-month
Some applications require the format to include a two digit day-of-month as per RFC7231. The Java 8 DateTimeFormatter.RFC_1123_DATE_TIME uses a single digit:
System.out.println(DateTimeFormatter.RFC_1123_DATE_TIME.format(ZonedDateTime.now(ZoneOffset.UTC)));

Output: Wed, 1 Aug 2018 14:56:46 GMT
Some applications don't like that. Before you use the old answers that use Joda-time or a pre-java8 SimpleDateFormat, here's a working Java-8 DateTimeFormatter:
DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss O")
Now, when you do this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss O");
System.out.println(formatter.format(ZonedDateTime.now(ZoneOffset.UTC)));

You get Wed, 01 Aug 2018 14:56:46 GMT - note the leading zero in the day-of-month field.

A: If you, like me, are trying to format a Java 8 java.time.Instant you need to explicitly add the time zone to the formatter. Like this:
Instant instant = Instant.now();
String formatted = DateTimeFormatter.RFC_1123_DATE_TIME
        .withZone(ZoneOffset.UTC)
        .format(instant);
System.out.println(formatted);

Which prints:

Tue, 15 Mar 2016 14:45:34 GMT


text:
Q: Probability to roll a sum of less than 3600 with 1000 dice throws I try to estimate the probability that the sum of the numbers when rolling a die 1000 times is less than 3600. I am confident that I can approximate the probability with a normal distribution with expectation value $\mu=3500$ and the correct standard deviation. Is $\sigma=\sqrt{\frac{35n}{12}} (n=1000)$ the correct value? If I use this $\sigma$ then $p=96.8\%$ which looks pretty high to me. How can I verify my result?

A: Pretty easy to simulate in python.
import numpy as np
num_rolls = 1000
num_trials = 100000
cutoff = 3600

samples = np.random.choice(range(1,7),size=(num_trials, num_rolls)).sum(axis=1)

print((samples<cutoff).mean())

My sim agrees with your calculation.

A: You should have a continuity correction in your normal approximation.  For example in R, depending whether "less than $3600$" is intended to be strict or not:
maxrolls <- 1000
faces <- 6
pnorm(3600-0.5, (faces+1)*maxrolls/2, sqrt(maxrolls*(faces^2-1)/12))
# 0.9672904
pnorm(3600+0.5, (faces+1)*maxrolls/2, sqrt(maxrolls*(faces^2-1)/12))
# 0.9686207

and it is possible to do a more exact calculation of the probabilities
maxrolls <- 1000
faces <- 6
probs <- numeric(faces*maxrolls+1) # offset by 1
probs[1] <- 1
for (roll in 1:maxrolls){
  matprobs <- matrix(
    rep(c(rep(0,faces+1), probs), faces)[-(1:(faces))],
    ncol=faces)
  probs <- (rowSums(matprobs) / faces)[1:(faces*maxrolls+1)]
}
sum(probs) # should be 1
# 1
sum(probs * (0:(faces*maxrolls))) - (faces+1)*maxrolls/2 # should be 0
# 1.818989e-12
sum(probs[1:3600]) / sum(probs) # prob strictly less than 3600
# 0.9672951
sum(probs[1:3601]) / sum(probs) # prob 3600 or less
# 0.9686258

and this shows that the normal approximation with a continuity correction is very close in this case, with both calculations within $0.000005$ of the correct values

A: The mean value $\mu$ for throwing dice $\mu=\frac16(1+2+...+6)=3.5$, and the standard deviation is
$$
\begin{align}
\sigma&=\sqrt{\frac16\{(6-\mu)^2+...+(1-\mu)^2\}}\\
&=\sqrt{35\over 12}
\end{align}
$$
so your numbers for the normal approximation for the distribution after $n$ trials seem to be OK.
Numerically,
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    nTrials := 100000
    nRolls := 1000
    over := 0
    rand.Seed(time.Now().UnixNano())
    for t := 0; t < nTrials; t++ {
        total := 0
        for r := 0; r < nRolls; r++ {
            total += rand.Intn(6) + 1
        }
        if total >= 3600 {
            over++
        }
    }
    fmt.Printf("%d %d %g\n", over, nTrials,
        float64(over)/float64(nTrials))
}

gives a value of
3246 100000 0.03246

which is the same as your answer
Run online here.
so it looks good.


text: Q: Is there a way to put a description on a SQL Server permission itself? It would be nice if I could put a description on a permission itself, e.g. "This insert permission is granted on this table because application foo needs it in order to bar."  Is there a way to do this?  Or of not, where would I go to suggest it to the SQL Server team?


text:
Q: Error connecting installing mysqlclient to my django project please help, when i try to run pipenv install mysqlclient it gives me an error indicating that visual c++ 14 or greater is needed and now i have gotten 14.29 but still not working.I also tried usimg Unofficial Windows Binaries for Python Extension Packages and this showed that mysqlclient installed successfully but when i tried to run mysqlclient it gave an error saying do you have mysqlclient installed? please help.

A: You can try to use mysql-connector-python
pip install mysql-connector-python

in you settings.py you must add this line:
'ENGINE': 'mysql.connector.django',

or you can use alternative
pip install PyMySQL

settings.py:
'ENGINE': 'django.db.backends.mysql'


text:
Q: Optimization problem involving eigenvalue problem I want to find the ${\bf x} \in \mathbb{R}^n$ that minimizes a function $f: \mathbb{R}^n \to \mathbb{R}$. $f$ is not linear, but it can be broken down in the following way:

*

*Let ${\bf v} \in \mathbb{R}^m$ be the solution (with $\|{\bf v}\| = 1$) to the eigenvalue problem $A({\bf x}){\bf v} = \lambda \mathbb{v}$ with the smallest eigenvalue (or in general, any solution to this eigenvalue problem), where $A$ is an $m \times m$ tridiagonal, symmetric matrix whose diagonal entries are continuous functions of ${\bf x}$, $A_{ii}: \mathbb{R}^n \to \mathbb{R}$ for $i = 1, ..., m$.

*The objective function $f$ can then be written as $f({\bf x}) = (h \circ g)({\bf x})$, where $g: \mathbb{R}^n \to \mathbb{R}^m$ maps to ${\bf x}$ the solution ${\bf v}$ to the above eigenproblem, and crucially, $h: \mathbb{R}^m \to \mathbb{R}$ is a linear function.
Ideally, I would like the entire problem to be linear, in which case the question is whether there are additional assumptions under which the function $g$ is linear, and what these might be. In the more general case, what "desirable" properties (e.g. convexity) should I look for to make this problem more feasible?


text:
Q: Smarty: how to include php in template? I've tried {include_php file="phpfile.php"} and {php} tags but both cause deprecated error. Can you not do this in Smarty anymore? I can't find anything in the docs.

A: I circumvented this problem. Create a plugin file named block.php_code.php with this function in it:
function smarty_block_php_code($params, $content, &$smarty)
{
    if (is_null($content))
    {
        return;
    }
    if ('<?php' == substr($content,0,5) && '?>' == substr($content, -2))
        $content = substr($content,5,-2);
    ob_start();
    eval($content);
    return ob_get_clean();
}

In your template, you can then write:
{php_code}{literal}<?php

    print "Hello, world!";

?>{/literal}{/php_code}

A: They are depreciated for a reason as they allow poor practices. Smarty recommends putting the included script into the PHP logic or creating a plugin (which is simple).

{php} tags are deprecated from Smarty, and should not be used. Put your PHP logic in PHP scripts or plugin functions instead.

Source

{include_php} is deprecated from Smarty, use registered plugins to properly insulate presentation from the application code.

Source
If you include what you are trying to do in your phpfile.php, we can help you write a plugin function.

A: {include_php} is marked as deprecated in both Smarty2 and 3; {php} in Smarty3 only:

*

*http://www.smarty.net/docsv2/en/language.function.include.php.tpl

*http://www.smarty.net/docs/en/language.function.include.php.tpl

*http://www.smarty.net/docs/en/language.function.php.tpl


text:
Q: parse chr string into a dataframe using delimiters My data is in a format, that looks like this:
t2 <- "a = 10\n   b = 2\n   c =20\n"

How can I parse it so that I get a dataframe that looks like this?
# a 10
# b 2
# c 20

I'm trying to use readr::format_delim(), but I'm happy to use any solution. The code below doesn't give me the right answer.
library(readr)
t2 <- as_tibble(t2)
format_delim(t2, delim = "\n")

A: Use read.table or the likes with sep argument.
read.table(text = t2, sep = "=")

#     V1 V2
#1    a  10
#2    b   2
#3    c  20

Or read.csv(text = t2, sep = "=", header = FALSE)

A: We can use fread from data.table.  Would be faster
library(data.table)
fread(text = t2, sep="=")
#   V1 V2
#1:  a 10
#2:  b  2
#3:  c 20


text:
Q: What is the purpose of Fame in Torchlight? Apart of the additional skill point gained on every fame level, is there any other purpose for this - practical or not?
Also, I reached the max fame level of 50 really early in the game which is quite disappointing.. every single Champion killed gives almost full fame level which is pretty insane - any reason behind this design?

A: I believe you an additional retain a fame level each time you retire, but beyond that, there isn't much else.
What difficulty are you playing on? The lower difficulties are really easy and you may want to try changing it. I know Champions don't give me as much Fame as you describe on Very Hard or even Hard.


text:
Q: Can't able to call web3 api(getTransactionReceipt) wia npm For access erc20 token api calling, I have followed the stack ticket (Send ERC20 token with web3)
And tried to call a test method to fetch the transaction details with the below code in nodejs,
var Tx = require('ethereumjs-tx')
var Web3 = require('web3')
var web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:5000/'))

var receipt =  web3.eth.getTransactionReceipt('0x3265c1461d3f167c756fbc062ae3a2dc279b44a9c3ca2194271d4251cd0c1655')

But as in result I got the error : errors.InvalidResponse(request.responseText);Error: Invalid JSON RPC response: undefined
I have also tried the 'geth' for RPC but cant't work for me as expected;Please let me know some way to deal with this.


text:
Q: mini batch backpropagation clarification Read through a lot of articles and now I am in my braindrain end, and need a fresh perspective on the concept of mini batch. I am new to machine learning and would appreciate any advice on whether my process is correct. Here is my premise:
I have a dataset of 355 features and 8 class output. A total of 12200 data. This is a rough visualization of my neural network:

I decided on 181 neurons for Hidden layer 1, 96 neurons for Hidden Layer 2. I used ReLu activation for the hidden layers and Logistic for the output layer.
To do the mini-batch, I set my batch size to 8. So I have a total of 1525 batch with 8 dataset per batch. Here is my step:

*

*Get 1st Batch of data (8 sets of 355 inputs and 8 outputs).

*Forward Propagation of the Batch.

*Get the Errors and calculate the sum of squares of error.
For the sum of squares, I averaged the errors of the batch first, used the formula
SumError = (1/8)*sum(error^2)

*Back Propagation of the Batch

*Get the average of the weights value after back propagation.

*Use the new weights as the weights for the next batch.

*Get next Batch of Data (8 sets of 355 inputs and 8 outputs).

*Repeat 2-7 using the new set of weights.

*When all batch is done, get the average of the SumError to get the Sum of Squares per epoch.

*Repeat 1-9 until SumError per epoch is small.

*Get the final weights to be used for validation

That is the process of my mini batch. Is this correct? I mean, for the weights, do I use the weights calculated after each batch as the input weights for the next batch, or do I collect all the weights first (the starting weights will be used for all the batch), and then average the weights for all the batches? Then use the average weights as input to the next epoch?

A: Actually, u have to define your epoch, and each epoch should spread all your input data once at least(not only 2-7times).And after one epoch has one weight updated and repeat the steps until finish all epoch.


text:
Q: How to disable out of order execution of CPU As we know, modern CPU is able to execute multi commands concurrently: https://en.wikipedia.org/wiki/Out-of-order_execution
As a result, we may get such a fact as below:
When we execute the c++ code: x = a + b; y = c + d;, y = c + d; may be executed before x = a + b;.
My question is if it is possible to disable the out-of-order execution of CPU?

A: No, you can't deactivate such hardware mechanism when it has it. That's what gives you performance. That's how the CPU is designed.
What C++ guarantees is that you won't be able to see the difference between what you want with the proper order, and what you will get. And that's also something that vendors like Intel will make sure for the assembly.
Have a look at https://www.youtube.com/watch?v=FJIn1YhPJJc&frags=pl%2Cwn for the C++ execution model.

A: All you should care about is the meaning of your program. That's not being pedantic, it is the fundamental basis around which the entire language has been designed.
A C++ program describes the meaning of a program. It is not a one-to-one mapping of source code to what a computer should literally do.
If you want that, you will have to code in assembly or perhaps some old-fashioned language from the middle ages, but even then you are going to have a hard time telling a modern CPU not to do all the clever things that it is designed to do in order to support useful programs. Certainly I'm not aware of any out-of-the-box switch, flag or setting that makes this happen; it would go against the grain of the very architecture of a CPU.
Ultimately you may be better off building and programming a Difference Engine ;)

A: You cannot deactivate the reordering at the hardware level (CPU level).
However, you can ensure that the compiler will not reorder by using the optimization level of debug.
This will help in debugging the program, but it will make your code slow. It is not recommended in production code.

A: It's not possible to disable out-of-order execution from the program, this is the well-known problem of Memory Barrier. As the problem consequences appear in multi-threading programs only, you have to use synchronization primitives to ensure the execution order.


text:
Q: Core Data many-to-many predicate I have two entities which are related by a many-to-many relationship:
Database <<----->> Category
In other words, a database can have many categories and a category can be associated with many databases.
I need an NSPredicate that will return all Category objects associated with a given database object. Any help would be appreciated.

A: You don't need a predicate.  Given that you have a relationship called categories that is the to-many relationship to your Category entities, then
NSSet *categoriesForDatabase = database.categories;

If you really want to use a predicate then it would be:
[NSPredicate predicateWithFormat:@"ANY databases = %@", database];

where "databases" is the name of the to many relationship on the Category entity and database is an instance of a Database entity.

A: You want to compare a collection (all Category objects) to a given object, you can try something like this :
[NSPredicate predicateWithFormat:@"ANY categories = %@", category];

or
[NSPredicate predicateWithFormat:@"ANY databases = %@", database];


text:
Q: System.Net.Http.HttpClient vs Windows.Web.Http.HttpClient - What are the main differences? When developing .NET 4.5 desktop apps for Windows I have been used to use System.Net.Http.HttpClient for all communication with a backend Web API. I am now developing a Windows Store app and has noticed the existence of Windows.Web.Http.HttpClient. I have looked for information on what the main differences are between the two clients but without any luck.
From MSDN I know that I should start using Windows.Web.Http.HttpClient in my Windows Store app since System.Net.Http.HttpClient might be removed from the API:

Note The System.Net.Http and System.Net.Http.Headers namespace might not be available in future versions of Windows for use by Windows Store apps. Starting with Windows 8.1 and Windows Server 2012 R2, use Windows.Web.Http.HttpClient in the Windows.Web.Http namespace and the related Windows.Web.Http.Headers and Windows.Web.Http.Filters namespaces instead for Windows Runtime apps.

But apart from this information, I have a hard time figuring out what are the main differences and what is the main benefit of using Windows.Web.Http.HttpClient? What does it add that we don't already got in System.Net.Http.HttpClient?
Answers backed by official documentation are greatly appreciated.

A: Windows.Web.Http is a WinRT API available in all the WinRT programming languages supported: C#, VB, C++/CX and JavaScript. This enables the option to write the same code in the language of your choice.
System.Net.Http is a .NET API, and it is only available for C# and VB developers.
Windows.Web.Http advantages

*

*WinRT APIs are written in native code, which translates in better performance.

*Windows.Web.Http is on top of a common Windows HTTP stack, and reuses resources already in use by other Windows components. System.Net.Http is a separate implementation of the HTTP protocol that is not frequently used by other Windows components. So, in some cases, you save resources by choosing Windows.Web.Http.

*Windows.Web.Http has better integration with WinRT types, such as IInputStream, IOutputStream and IBuffer. Avoiding the .NET extensions that convert System.IO.Stream into IInputStream or IOutputStream and System.Array into Windows.Storage.Streams.IBuffer can improve performance and save resources in some cases.

*Windows.Web.Http has the new features, such as HTTP/2 support.

*Windows.Web.Http is COM based and can be used by any programming language that understands COM.

System.Net.Http advantages

*

*System.Net.Http is available since Windows 8 or .NET 4.5 and Windows.Web.Http is only available since Windows 8.1 and Windows Phone 8.1.

*It is straight forward to port WinRT code using System.Net.Http to ASP.NET or Xamarin (Portable Class Library)

*Windows 8 and 8.1 projects or desktop projects: †

*

*Authentication headers and credentials are isolated per HttpClient (example)

*Cookie container isolated per HttpClient

*Does not cache HTTP responses, so subsequent requests will never come from the cache, a common issue with servers that does not set the correct Cache-Control header (example)

*Works with System.Net.NetworkCredential
† For Windows Universal Projects (UWP), System.Net.Http is a wrapper on top of Windows.Web.Http, as described here.
Further reading: Demystifying HttpClient APIs in the Universal Windows Platform

A: There is not much to find about it. Some things that come in my mind:

*

*The new API doesn't have dependencies to some low-level Windows functions, like the current API does.

*The new API is better capable handling new methods related to the HTTP protocol, like WebSockets, etc.

Some useful information can be found in this blog post which also referenced this Build video. They speak about better cache control, and a way to add filters for authentication, easy access to cookies, reconnecting, etc.


text:
Q: Get Output parameter from stored procedure without calling execute() I want to call a PL/SQL stored procedure from within a Java program via an entity manager:
StoredProcedureQuery storedProcedureQuery = entityManager.createStoredProcedureQuery("someProcedure");

Now my understanding was that I have to call execute() on this storedProcedureQuery in order to execute the procedure and be able to retrieve the OUT-parameters. However, I can retrieve these values without calling the execute()-Method by simply calling
someValue1 = (Integer)storedProcedureQuery.getOutputParameterValue(1);
someValue2 = (Integer)storedProcedureQuery.getOutputParameterValue(2);

How is this possible ? When exactly will the stored procedure be executed in this code snippet? Will the procedure be executed every time when getOutputParameterValue() is called ? Is there any official documentation for this behaviour ?

A: I am a new learner in his field and as curious as you with the question. However i have taken this opportunity to test it and below is my observation,
According to the documentation execute() returns:
> Return true if the first result corresponds to a result set,
> and false if it is an update count or if there are no results
> other than through IN OUT and OUT parameters, if any.

therefore I would say, the returned true or false doesn't mean a successful or not execution.
Again we must register the parameters before we call to getOutputParameterValue. If we looked into the implementation of getOutputParameterValue, we would able to find exactly where the hibernate provider ( which is JPA in case of mine) calls to the actual execution.
Further to how many times the execution happened I tested it in a way to check it by inserting to another table inside the calling procedure.
create table test_procedure_call(msg varchar2(100));

CREATE OR REPLACE PROCEDURE test (
    p_in_1  IN    NUMBER,
    p_out_1 OUT   VARCHAR2,
    p_out_2 OUT   VARCHAR2
) AS
BEGIN
    insert into test_procedure_call values ('Executed..');
    commit;
    select 'FirstName'||' '||'LastName','HR' into p_out_1,p_out_2
      from dual
     where p_in_1=1;
END;
/

@Test
    public void testStoredProcedureQuery() {
        StoredProcedureQuery sp = em.createStoredProcedureQuery("test");
        // set parameters
        sp.registerStoredProcedureParameter("p_in_1", Integer.class, ParameterMode.IN);
        sp.registerStoredProcedureParameter("p_out_1", String.class, ParameterMode.OUT);
        sp.registerStoredProcedureParameter("p_out_2", String.class, ParameterMode.OUT);
        sp.setParameter("p_in_1", 1);

        String name = sp.getOutputParameterValue("p_out_1").toString();
        String dept = sp.getOutputParameterValue("p_out_2").toString();

        System.out.println("Name : " + name);
        System.out.println("Department : " + dept);
    }

select * from test_procedure_call;

MSG
----------------------------------------------------------------------------------------
Executed..

By this out of the table test_procedure_call, we can confirm it executes only once per test. (as we saw in above example).


text:
Q: Find the minimal sum of the local maximum of the subarrays of an array I need to write a function to calculate minimal sum of the local maximum of the subarrays of an array where every item is a positive integer with possible duplicates.
For example, we have an array [2, 3, 1, 4, 5, 6] and the number of sub arrays is 3. We want to get the min sum of the local max of the sub arrays. What that means is that, for example, one possible way to divide the current array into 3 sub arrays is [[2,3], [1], [4,5,6]] and the local maxs for each subarray is 3, 1, 6 respectively. And the sum of the local maxs is 3 + 1 + 6 = 10. For this particular array, [2, 3, 1, 4, 5, 6], this is the minimal sum of all its possible sub-array variations.
My approach is to first get all the possible sub-array variations for a given array. and get the min sum of them.

function getSubarrays(array, numOfSubarray) {
  const results = []

  const recurse = (index, subArrays) => {
    if (index === array.length && subArrays.length === numOfSubarray) {
      results.push([...subArrays])
      return
    }
    if (index === array.length) return

    // 1. push current item to the current subarray
    // when the remaining items are more than the remaining sub arrays needed

    if (array.length - index - 1 >= numOfSubarray - subArrays.length) {
      recurse(
        index + 1,
        subArrays.slice(0, -1).concat([subArrays.at(-1).concat(array[index])])
      )
    }
    // 2. start a new subarray when the current subarray is not empty

    if (subArrays.at(-1).length !== 0)
      recurse(index + 1, subArrays.concat([[array[index]]]))
  }

  recurse(0, [[]], 0)
  return results
}

function getMinSum(arrays) {
  return arrays.reduce(
    (minSum, array) =>
      Math.min(
        minSum,
        array.reduce((sum, subarray) => sum + Math.max(...subarray), 0)
      ),
    Infinity
  )
}

getMinSum(getSubarrays([[2,3], [1], [4,5,6]], 3)) // 10

However, I think the time complexity for my solution is really high. My guess is that it is on the order of 2^n (feel free to correct me if I am wrong). I wonder if there is a more efficient way to calculate this.

A: The first thing that comes to mind is dynamic programming.
Let dp[i][j] be the minimal sum of local maximums of array[0..i] (left border included, right border excluded) divided into j subarrays. dp[0][0] = 0 (this is an initial value for empty array[0..0]), and for simplicity initialise all other dp[i][j] with some large enough number to denote meaningless of not calculated values (larger than sum of elements in array in this case is enough).
Your answer obviously is the value of dp[array.length][numOfSubarray].
How do you calculate values of the dp? Actually pretty easy. dp[i][j] is the minimum among dp[k][j - 1] + max(array[k..i]) (where k < i). Let's analyse this formula:
dp[k][j - 1] + max(array[k..i])
#    ^                ^
# This term is the minimal sum of local maximums
# of array[0..k] divided into j-1 subarrays.
#                     |
#           This term is maximum of your new j-th subarray.

Also make sure that all the dp[k][j - 1] were calculated beforehand (for example by calculating dp[i][1] at first, then dp[i][2], then dp[i][3] and so on).
Now let's write it altogether (naive approach just for now).
dp[0][0] = 0

for newSubarrayNumber in range(1, numOfSubarray + 1):
  for previousEnd in range(0, array.length):
     for newEnd in range(previousEnd + 1, array.length + 1):
       # Formula from above.
       dp[newEnd][newSubarrayNumber] =
           min(dp[newEnd][newSubarrayNumber],
               dp[previousEnd][newSubarrayNumber - 1] + max(array[previousEnd..newEnd]))

 # Your answer.
print(dp[array.length][numOfSubarray])

As you can see we've got polynomial complexity, now it's O(numOfSubarray * array.length^3) (two array.length for two nested loops and one more because of max(array[previousEnd..newEnd])).
Also we can optimise our algorithm. It makes no sense to always calculate min(array[previousEnd..newEnd]), because previously we did that for newEnd - 1 and we can reuse that value. That brings us to the following algorithm:
for newSubarrayNumber in range(1, numOfSubarray + 1):
  for previousEnd in range(0, array.length):
     maxElement = 0
     for newEnd in range(previousEnd + 1, array.length + 1):
       # maxElement replaces max(array[previousEnd..newEnd]).
       maxElement = max(array[newEnd - 1], maxElement)
       dp[newEnd][newSubarrayNumber] =
           min(dp[newEnd][newSubarrayNumber],
               dp[previousEnd][newSubarrayNumber - 1] + maxElement)

That's O(numOfSubarray * array.length^2) (just because of loops, no extra complexity multiplier).
I believe one can optimise it even more (maybe using some advanced data structures), feel free to comment. Also even better approach for this particular problem could be some sort of greedy algorithm (like having small subarrays closer to border of an array and one big chunk in the center but that needs to be proven).

A: We can have O(n^2) by using a dynamic program where the state is (1) the index of the rightmost element considered so far, and (2) the length of the subarray ending at (1).
The information we need to store about those two things is deterministic -- we need the maximum value in subarray (2) and the best solution overall ending at (1).
Then, to consider the next element, we have two choices for each length in (2): either add the element to the subarray, or start a new subarray.
For each element, we would examine O(n) lengths for a total of O(n^2).


text:
Q: destroy test in rails with minitest capybara I'm trying to get the syntax just right. I think I'm close but I'm trying to make a test to show that my admin can destroy a user. The error I get right now is :
Ambiguous match, found 2 elements matching link or button "delete

and I totally understand that. That means I get to the users index page and I see the delete button for a regular user and the admin. How do I exactly specify which user I want to click the delete button on so I can delete them in the test.
here is my users.yml file
user:
  name: user
  email: user@examle.com
  admin: false
  password_digest: <%= BCrypt::Password.create('password') %>

admin:
  name: admin
  email: admin@admin.com
  admin: true
  password_digest: <%= BCrypt::Password.create('password') %>

here is my admin_test.rb file
require "test_helper"

feature "as a blog owner I want a working user delete so I can remove trolls" do
  scenario 'admin can delete profile' do
    visit new_session_path
    fill_in 'Email', with: users(:admin).email
    fill_in 'password', with: 'password'
    click_on 'Log In'
    visit users_path(:admin)
    click_on 'delete'
    click_on 'OK'
    page.must_have_content "User deleted"
  end
end

I think the problem is caused on the line
click_on 'delete'

anyone know what the right syntax is or what I'm messing up?

A: First issue is that you probably don't want to be able to delete an admin.  You also don't want to delete yourself.  I would suggest adding an admin? boolean method to test for whether a user is an admin or not so that it doesn't show the delete option for admins.  Something like this in your view would work then:
<% if current_user.admin? && !current_user?(user) %>
    | <%= link_to "delete", user, method: :delete,
                                  data: { confirm: "You sure?" } %>
<% end %>

Second is the issue when have two of the same element and get an ambiguous match.  For testing a lot of times you only want to select one out of the many.  You could just select the first one:
first('.item').click_link('Agree')

You can check out this answer for more info: How to click first link in list of items after upgrading to Capybara 2.0?


text:
Q: Finding distance to a plane in a rotating system I have this pre-school-level problem, I just don't know what direction to start, i'm pretty lame at math. Let me simplify my question through an example: We have a flying helicopter with a distance measuring equipment at the bottom, it is looking down. The ground is flat, the chopper can tilt forward and back and left or right. (can do both axes simultaneously) If the helicopter is completely in level my distance measure shows the altitude of the heli above the ground.
How to calculate the altitude with a given theta and phi tilt angles of the helicopter?
I have this feeling, it can be done by using simple 2D trigonometry, instead of 3D vector algebra to calculate line-plane intersections.
Thanks in advance!

A: I guess it would be:
altitude = D*cos(theta)*cos(phi)

Where D is the distance to the ground as measured from the helicopter?


text:
Q: Oracle query fails with added COLLATE clause In sqlplus,  this query works:
SQL> SELECT DISTINCT
  2  CNTPTY_TYPE
  3  FROM visn_exp.V_IHCVSN_CERT_DEP
  4  WHERE as_of_dt = '08-may-20'
  5  ;

CNTPTY_TYPE
----------------------------------------

Retail
PSE
Non-Financial Corporate
FI

BUt this one fails, with the collate clause:
SQL> SELECT DISTINCT
  2  CNTPTY_TYPE COLLATE latin1_general_CI_AI AS CNTPTY_TYPE
  3  FROM VISN_EXP.V_IHCVSN_CERT_DEP
  4  WHERE as_of_dt = '08-may-20'
  5  ;
CNTPTY_TYPE COLLATE latin_general_CI_AI AS CNTPTY_TYPE
                    *
ERROR at line 2:
ORA-00923: FROM keyword not found where expected

What should I do to fix this?
Update:  Tried the suggested query in the answer.  Got
SQL*Plus: Release 12.2.0.1.0 Production on Mon May 11 21:03:20 2020
Copyright (c) 1982, 2017, Oracle.  All rights reserved.
Enter password:
Last Successful login time: Mon May 11 2020 16:51:34 -04:00
Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP,
Advanced Analytics and Real Application Testing options
SQL> SELECT DISTINCT
  2  CNTPTY_TYPE COLLATE LATIN_AI AS CNTPTY_TYPE
  3  FROM VISN_EXP.V_IHCVSN_CERT_DEP
  4  WHERE as_of_dt = '08-may-20';
CNTPTY_TYPE COLLATE LATIN_AI AS CNTPTY_TYPE
                    *
ERROR at line 2:
ORA-00923: FROM keyword not found where expected

A: The unary operator COLLATE was introduced only in Oracle 12.2, so you get the error because your version is 12.1.
Why do you get the error "FROM keyword not found where expected", and exactly where you found it? Because in Oracle 12.1, the word COLLATE has no special meaning. Finding it after a column name in the SELECT clause, Oracle thinks it's an alias for the column. And since this alias (what it thinks it's an alias, anyway) is not followed by comma for additional expressions to select, it expects the keyword FROM. It finds LATIN_AI instead (or whatever you tried originally) and that's where it throws the error - it was expecting FROM in exactly that place.
Workaround in 12.1? There is one, but it has disadvantages. The benefit of COLLATE is that you can indicate a collation in the query, without affecting your overall session. The same as using a date format model when you call TO_DATE in the query, without having to change NLS_DATE_FORMAT.
Alas, in 12.1 you can't control the collation at the query level; you must change it for the session (and then change it back, if other queries or other things you do in the session need a different collation). You do that by running
alter session set nls_sort = 'LATIN_AI';

before you run your query.
If you need to revert to the "old" nls_sort after you run this query, you would do well to know what it is, before you change it to 'LATIN_AI'. You do that by running the following query before the alter session shown above.
select value from v$nls_parameters where parameter = 'NLS_SORT';

Then, after you are done with your query, you will need to run alter session again to change nls_sort back to the old value.
Side note - why do you compare a date to a string in the where clause? (Or is as_of_date in string data type - which is an even worse practice?)

A: When using collations there are three suffixes that alter the behaviour of sorts and comparisons.
"_CI" : Case insensitive, but accent sensitive.
"_AI" : Both case and accent insensitive.
"_CS" : Both case and accent sensitive. This is default if no extension is used.

Though not sure on the purpose of _general usage above. However only using LATIN_xx, replacing xx with any of the above option must do your job.
Query to check valid NLS_SORT Values for Latin :-
SELECT *
FROM V$NLS_VALID_VALUES
WHERE parameter = 'SORT' and value = 'LATIN';

Additional Info : Collations in Oracle
Summarized Query :
SELECT DISTINCT
CNTPTY_TYPE COLLATE LATIN_AI AS CNTPTY_TYPE
FROM VISN_EXP.V_IHCVSN_CERT_DEP
WHERE as_of_dt = '08-may-20';


text:
Q: How high are the monster levels on Inferno difficulty? The effectiveness of armor and resistances depends on the level of the monster that is causing damage to the hero. According to one post on the Diablo III forums, the formula for armor is

DR from Armor = Armor / (Armor+(50*mLvl))

Now, I would assume that for most of the game the monsters are close in level to the player, at least while the player is still gaining levels. But how do the monster levels far on Inferno difficulty? The player is fixed at level 60 there, are the monsters also fixed to this level or does their level increase further in higher acts?
The reason I'm interested in this specifically is that a further increasing monster level would make armor and resistances less effective compared to just increasing the HP by stacking vitality. Knowing the approximate monster level is necessary to calculate whether adding more HP or more armor/resistances is more effective at a specific point.

A: Inferno is only for level 60 characters. Therefore the monsters need to be much tougher.
EDIT: Ok I have found a bluepost by Bashiok:

Previously, Inferno difficulty was mlvl 61 across all of Inferno, and now it starts at mlvl 61 and ramps up quickly in Act I and ends somewhere around 65 (?) in Act IV. We've only increased the difficulty.

If you are interested in the subject and want more details I'd also suggest his previous bluepost where he compares the difficulty of d3 with d2 and gives some insight into how they intended/patched the difficulties.
Have fun in Inferno ;)


text:
Q: Finding alternate form of entire function? So we were given a problem and it follows some of the stuff we did with Picard's theorems in class, but we were never shown how to actually find the form, just what they looked like for a few cases like not equal to a constant, or not equal to z.
f(z) is entire and $$f(z)\ne\frac{1}{z}$$ for $$z\ne0.$$ We have to show that this can be rewritten as $$\frac{1-e^{zh(z)}}{z}$$ where h(z) is entire. I have no clue where to get started. I know we would use the fact the function is entire and you have a branch of the Log, but not sure how to use that in this case.

A: $F(z)\ne1/z$ is the same as $1-zf(z)\ne0$; $f(z)$ entire implies $1-zf(z)$ entire; so we have an entire function $1-zf(z)$ which is never zero. I take it you know this implies $1-zf(z)=e^{g(z)}$ for some entire $g$, so you get $$f(z)={1-e^{g(z)}\over z}$$ Now $g(0)$ had better be $2\pi in$ for some integer $n$, lest this formula force an unwanted pole at zero on $f$, so $g(z)=2\pi in+zh(z)$ for some entire $h$, and away we go.


text:
Q: Work on home server over the internet? I was wondering how I could safely and securely perform SFTP throught the internet to my server so that I could work in code from home. Should the data be encrypted and tunneled? I don't have an exact idea. Which ports should the server have open? ( I would also need SSH... or similar...)

A: Set up an SSH server, that's the server side of SFTP.
openssh includes a client and server and an sftp command you use at the client side.  I am not sure about other implementations.. You can install openssh with cygwin.
The connection will be encrypted when you have the SSH server.  The encryption helps stop MITM attacks. You wouldn't be using tunneling. Tunneling is when you make a connection through the connection. (tunneling the connection within the encrypted connection/tunnel)


text:
Q: Unity DOTween UI scale yoyo effect I'm having a problem in creating a yoyo scaling effect with DOTween. I have tried using DoScale, DOScaleShake and DOPunchScale. None seem to work. The rotation that I made works just fine, but I need it to scale as well and that is something I somehow cannot create.
Here is the current code
void Update()
    {
        DOTween.Sequence()
            .Append(crownGlow.transform.DOLocalRotate(new Vector3(0, 0, 360), rotationSpeed, RotateMode.FastBeyond360).SetRelative())
            .Append(crownGlow.transform.DOPunchScale(new Vector3(0.5f, 0.5f, 0.5f), scaleSpeed, 10, 1f));
    }

I even tried it this way and it didn't work
    DOTween.Sequence()
            .Append(crownGlow.transform.DOScale(new Vector3(originalScale.x + 0.5f, originalScale.y + 0.5f, originalScale.z + 0.5f), scaleSpeed).SetEase(Ease.Linear))
            .Append(crownGlow.transform.DOScale(originalScale, scaleSpeed).SetEase(Ease.Linear));

EDIT: With the help of Ryanas, I managed to figure out the solution
void Start()
    {
        originalScale = crownGlow.transform.localScale;
        crownGlow.transform.DOLocalRotate(new Vector3(0, 0, 360), rotationSpeed, RotateMode.FastBeyond360).SetEase(Ease.Linear).SetLoops(-1, LoopType.Incremental).SetRelative();

        var sequence = DOTween.Sequence()
            .Append(crownGlow.transform.DOScale(new Vector3(originalScale.x + 0.5f, originalScale.y + 0.5f, originalScale.z + 0.5f), scaleSpeed))
            .Append(crownGlow.transform.DOScale(originalScale, scaleSpeed));

        sequence.SetLoops(-1, LoopType.Restart);
    }

A: What you're probably looking for is something like this. Sequences shouldn't be created in update every frame because then it means you're applying several sequences on this object every second.
Instead, you want to create the sequence in another function such as Awake or Start. You mentioned that you want it to Yoyo but you need to supply that when you set the number of loops it does. I recommend looking at the documentation for more information: http://dotween.demigiant.com/documentation.php
Here, I've set loop amount to be -1, which means it infinitely loops. You need to add .Join instead of .Append so the two tweens occur at the same time.
void Start()
{
    var sequence = DOTween.Sequence()
           .Append(crownGlow.DOLocalRotate(new Vector3(0, 0, 360), rotationSpeed, RotateMode.FastBeyond360).SetRelative())
           .Join(crownGlow.DOPunchScale(new Vector3(0.5f, 0.5f, 0.5f), scaleSpeed, 10, 1f));
    sequence.SetLoops(-1, LoopType.Yoyo);
}


text:
Q: "Can't find a source file ...random.cc" with Eclipse CDT while debugging in c++ caption2
i've been stucked with the generation of random numbers on one code i've been working lately. If i run the code, everything works fine. It only gets stucked while debugging... With this being said i share with you the code (of the .cpp file):
#include "RWS.h"
#include "Utilitaries.h"
#include <random>
#include <stdio.h>
#include <iostream>
#include <fstream>
using namespace std;

...
std::random_device rd;  //Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
    std::uniform_real_distribution<> U_01(0.0, 1.0);

We are trying to generate random numbers (differents than 0). This is the error from the debugger:
Can't find a source file at "/home/gfortran/gcc-home/workshop/gcc/objdir64/x86_64-w64-mingw32/libstdc++-v3/src/c++11/../../../../../gcc-8.2.0-mingw/libstdc++-v3/src/c++11/random.cc"
Locate the file or edit the source lookup path to include its location.

I have a similar problem with another random generator, but i fixed it by Locating the file in the minGW folder. The problem now, is that i can't find the random.cc file, i can only see one file (in one minGW folder: C:\MinGW\include\c++\8.2.0\bits) which is named random.tcc and i believe it has something to do with that. But i'm not really familiar with this. Actually, i haven't seen any .cc file in these folders... Can you explain me why the debugger is not working and how i can overcome this please?


text:
Q: Grunt and ES6 modules in node - incompatible without the use of .mjs? So, I'm dabbling a bit with Typescript and Grunt at the moment to see if it's worth it for me. The thing is: Typescript does not compile to *.mjs files but only regular *.js files. Node does support ES6 Modules but only if you either mark them as '*.jsm' files or by setting "type": "module". Setting this top-level field in package.json however has global scope for any *.js file in the same directory and any following ones.
This breaks the Gruntfile.js file as it seems since it uses CommonJS modules, see my very basic Gruntfile as example:
module.exports = function (grunt) {
   grunt.initConfig({
      ts: {
         default: {tsconfig: "./tsconfig.json"}
      }
   })
   grunt.loadNpmTasks("grunt-ts");
   grunt.registerTask("default", ["ts"]);
}

Without expecting much success I naively changed the export syntax from module.exports = to export default which expectedly did no work since it didn't make much sense.
Questions

*

*Is there any option to use Grunt with ES6 modules enabled in node?

*Is there a proper way to tell TypeScript to compile to *.mjs files?

A: If you set "type": "module" in your package.json, you need to rename Gruntfile.js to Gruntfile.cjs, and run it with grunt --gruntfile Gruntfile.cjs.

A: The suggested approach with Babel running before Grunt makes Grunt a bit redundant. Since TypeScript does not yet support exporting ES6 modules to *.mjs files (and you have to use the *.mjs suffix in your import when node should still be running with its CommonJS system) and will probably never fully (see Design Meeting Notes 11/22/2019) I have to conclude that ES6 modules still have serious implications and issues. Changing the file extension is not enough since the extension-less imports fail with node. You'd need to go through every compiled file and change the import to specifically load *.mjs files.
However, the TypeScript Compiler can be set up in a way that it does understand ES6 module syntax and to compile to CommonJS (see TS handbook).
{
  "compilerOptions": {
    "module": "CommonJS",
    // [...]
  },
}

This way the TypeScript code be written with ES6 module syntax and the output can be CommonJS compatible without braking other code. As a bonus you can skip the Babel approach and grunt can run TS compiler.

A: You can using babel-node to compile first. Which will resolve ES6 export and import problem.
npm install --save-dev @babel/core @babel/node
npx babel-node server.js


text:
Q: How to save the content of an imageView to internal storage I would like someone to tell me a method of how to save the contents of an imageView to internal storage as I am not quite sure how to do it and it is not like I know much about kotlin as I am learning
Any help is appreciated from the heart
This is the method I am using:
private fun imageRandomFun() {
        val quest1 = "https://proxxcraft.com/"
        Picasso.get().load(quest1).memoryPolicy(MemoryPolicy.NO_CACHE).into(memeRandomView)
        Picasso.get().isLoggingEnabled = true
    }

private fun saveImageToStore() {
        val externalStoreState = Environment.getExternalStorageState()
        if (externalStoreState.equals(Environment.MEDIA_MOUNTED)) {
            val storeDirectory = Environment.getExternalStorageState().toString()
            val file = File(storeDirectory, "testimage.jpg")
            try {
                val stream: OutputStream = FileOutputStream(file)
                var drawable = ContextCompat.getDrawable(requireActivity(), R.drawable.logo)
                var bitmap = (drawable as BitmapDrawable).bitmap
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
                stream.flush()
                stream.close()
                Toast.makeText(
                    requireContext(),
                    "Imagen gaurdada ${Uri.parse(file.absolutePath)}",
                    Toast.LENGTH_SHORT
                ).show()
            } catch (e: Exception) {

            }
        } else {
            Toast.makeText(requireActivity(), "ASDASDA", Toast.LENGTH_SHORT).show()
        }
    }

A: I believe your problem is that you used the getExternalStorageState () method to get your directory in this line:
var storeDirectory = Environment.getExternalStorageState().toString();

according to the official documentation it

Returns the current state of the primary shared / external storage
media

So try with this :
class MainActivity2 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main2)
        val image = findViewById<ImageView>(R.id.image);
        image.setImageResource(R.drawable.common_full_open_on_phone)
        val storeDirectory = this.getExternalFilesDir(Environment.DIRECTORY_DCIM) // DCIM folder
        Log.d(TAG, "onCreate: $storeDirectory")
        val file = File(storeDirectory, "testimage.jpg")
        val stream: OutputStream = FileOutputStream(file)
        val drawable = image.drawable
        val bitmap = (drawable as BitmapDrawable).bitmap
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
        stream.close()
    }
}

If you have added the right permission and grants it should work And you'll find the images in the DCIM folder


text:
Q: Excel IF and or value range I have a formula that currently works pretty well for the most part.  It originally was a scoring factor of  90%-100= 5, and 85% to 89.99% = 4 and 80% to 84.99% = 3 and so on.  This is represented using the formula below:
=IF($B10>=90%,5,IF($B10>=85%,4,IF($B10>=80%,3,IF($B10>=75%,2,IF($B10<=74.99%,1)))))

So the new requirement came down as follows:
Range value picture
95  to 100% = 5
85 to 89.99%  or 101.1 to 105%  = 4
80 to 89.99% or 105.1 to 110%   = 3
75 to 79.99% or 110.1 to 115%   = 2
Less than 74.9   = 1

So the dilemma I'm in is I have not been able to figure out how to create a range for values 2, 3 and 4 to be either or side for the scoring value to become true.  So score value 4 should be the ranges of 85% through 89.99% OR 101.1% through 105% to be true.
Does anyone have any ideas on how to restructure this to include the ranges so that if either range is true it would show the correct scoring values?  Thanks in advance for your help.

A: Instead of nested ifs consider using a table then use a VLOOKUP to find the correct value:
I created this table:

Then I can use this formula to get the proper score:
=VLOOKUP(B10,E:F,2,TRUE)

This method has the advantage of being able to easily expand to accomadate new rules.  The only caveat is that your table must be sorted on the first column to get the proper return.


text:
Q: Facebook Live's Emoji unicode convert issue Did anyone know how can i convert facebook emoji from \ud83e\udd79 into emoji  in php?
I tried this, but still cannot, as the emoji is load from image from facebook, got any otherway to do this?
and tried php emoji also cannot, there is no unicode for that..
https://github.com/iamcal/php-emoji/
$str2 = preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/', function ($match) { return mb_convert_encoding(pack('H*',$match[1]), 'UTF-8', 'UTF-16'); }, $str2);


text:
Q: How to make a CASE function return multiple columns? Us there a way to return multiple columns from the CASE function in T-SQL? The query I tried:
SELECT

CASE
    WHEN Street IS NOT NULL AND City IS NOT NULL
    THEN Name, Surname, Street, City, ZipCode
    ELSE BackUpAddr
END

FROM Table

But as expected after "THEN" I am allowed to enter only one column. Any ideas on how to solve the problem?

A: You can use multiple CASE statements for each column that you want to return:
SELECT
   Name,
   Surname,
   CASE WHEN Street IS NOT NULL THEN Street ELSE BackUpAddr END AS
   Street,
   CASE WHEN City IS NOT NULL THEN City ELSE BackUpAddr END AS City,
   ZipCode
FROM Table

A: The first issue here is each option from the case expression produces a different number of results. Since this is per row, what you're asking for is results that might have varying numbers of columns. That's not allowed. Every row in a result set MUST have the same number (and type) of columns.
You won't be able to find a way around this. Whether you use CASE or something else, the columns in a result have to be consistent. No exceptions. Either you'll need to a bunch of extra null values for the columns in the case where you choose the BackUpAddr column, or you'll need to concatenate everything into a single long string for the case where you choose the other columns.
The second issue is misunderstanding that case expressions really are expressions. This is a common mistake. What this means is a case expression is not like an if block in procedural code. Instead, the result of a case expression must always be a single (scalar) value.


text:
Q: How to change the Cinnamon system theme from the command line? How can I change the Cinnamon system theme from the commandline?

A: yesterday I first-time installed cinnamon on Ubuntu and asked the identical question(s). Here's what I have found so far.
Question 2: How can I change the Cinnamon system theme from the commandline?
Answer 2:
You can change cinnamon theme settings in a terminal with:
gsettings

*

*To get allowed values gsettings, you can first set them via the GUI:
cinnamon-settings themes

*Then you filter for that new value across all gsettings - here Menta:
gsettings list-recursively | grep -i Menta
Some examples:
        gsettings set org.cinnamon.desktop.interface clock-show-date true

        gsettings set org.cinnamon.theme name 'Menta'

        gsettings set org.cinnamon.desktop.interface icon-theme 'menta'

        gsettings set org.cinnamon.desktop.wm.preferences theme 'Menta'

P.S:
From above screenshot to the original question I deduct, you were asking
Question 1: How to change the terminal settings from command line?
Answer 1: This works via dconf.

*

*check what terminal you are using: gnome-terminal or mate-terminal
    [ ! -z `which mate-terminal` ] && echo "Terminal:mate" || \
    [ ! -z `which gnome-terminal` ] && echo "Terminal:gnome" || \
    echo "Terminal:??"

Example for gnome-terminal:
        GNOME_TERMINAL_PROFILE_ID=`gsettings get org.gnome.Terminal.ProfilesList default  | cut -d "'" -f 2`

        GNOME_TERMINAL_PROFILE_PATH="/org/gnome/terminal/legacy/profiles:/:$GNOME_TERMINAL_PROFILE_ID"

        dconf write "$GNOME_TERMINAL_PROFILE_PATH/background-color" \"#FDF6E3\"

        dconf write "$GNOME_TERMINAL_PROFILE_PATH/foreground-color" \"#657B83\"

        dconf write "$GNOME_TERMINAL_PROFILE_PATH/use-theme-colors" false

Have Fun!
Volker Fröhlich

A: Open the terminal (Ctrl-Alt-T) and select the three lines on the top bar:

Then select Preferences - you can change the theme here:

Hope that helps?