text:
Q: Is it possible to simultaneously infer possible keys and enforce object values interface? I have an config object in which every object value should be typed according to specified interface, but I also want to infer possible keys from that same object without defining them dynamically as strings.
I have interface for each object value:
interface PageConfig {
    url: string;
    title: string;
    allow?: string;
    path?: string;
    icon?: SpriteSymbol | string;
    component?: () => any;
}

So basically what I'm trying to do (obviously this won't work cause of recursive reference):
type PagesConfig {
    [key in keyof PagesConfig]: PageConfig
}

const pages: PagesConfig = {
    home: {
        url: '/',
        title: 'home',
        component: () => import('Home'),
    },
    rules: {
        url: '/static/rules',
        title: 'rules',
        component: () => import('Rules'),
    },
    about: {
        url: '/static/about',
        title: 'about',
        component: () => import('About'),
    },
};

I've came up with two solutions that actually work as intended but are a bit ugly.

*

*Use function to create config

function createPages<Pages extends { [key: string]: PagesConfig }>(pages: Pages): { [key in keyof Pages]: PageConfig } {
    return pages;
}

*Use helper variable to obtain keys

const proto = {
    home: {
        url: '/',
        title: 'home',
        component: () => import('Home'),
    },
    rules: {
        url: '/static/rules',
        title: 'rules',
        component: () => import('Rules'),
    },
    about: {
        url: '/static/about',
        title: 'about',
        component: () => import('About'),
    },
};

const pages: {
    [key in keyof typeof proto]: PageConfig
} = proto;

Is there a cleaner way to achieve this?
Edit: I forgot to mention that my goal is to ensure that simultaneously every value (page object) in pages config follow structure specified by PageConfig interface (otherwise developer should see typescript error indicating that it doesn't) and also benefit from autocomplete when using pages config in other files - so any developer will know that for example rules page has component property when using pages.rules.component but see error when trying to access property that isn't there like pages.rules.icon.
So basically I need to make sure that pages config is built properly and also know it's structure when importing it elsewhere.

A: One way to do this is to use const assertions:
const pages = {
    home: {
        url: '/',
        title: 'home',
        component: () => null,
    } as PageConfig,
    rules: {
        url: '/static/rules',
        title: 'rules',
        component: () => null,
    } as PageConfig,
    about: {
        url: '/static/about',
        title: 'about',
        component: () => null,
    } as PageConfig,
} as const;

Note the as const at the bottom.
And then you can define your PagesConfig like this:
types PagesConfig = typeof pages;

This requires using the as PageConfig in the creation of your pages object... you can remove this by using a more complicated type setup using mapped types:
const pages = {
    home: {
        url: '/',
        title: 'home',
        component: () => null,
    },
    rules: {
        url: '/static/rules',
        title: 'rules',
        component: () => null,
    },
    about: {
        url: '/static/about',
        title: 'about',
        component: () => null,
    },
} as const;

// this is now very specific and does not contain references to `PageConfig`
type _SpecificPagesConfig = typeof pages;

// used to convert specific pages to the general `PageConfig` type
type _AsPages<T> = {
    [I in keyof T]: PageConfig;
}

// finally you have the 'correct' type
// { home: PageConfig; rules: PageConfig; about: PageConfig; }
type PagesConfig = _AsPages<_SpecificPagesConfig>;

(Or in the Typescript Playground)
Now this has the problem, that pages itself is not properly typed check. We can statically assert, that pages conforms by altering the types a bit:
type _AsPages<T> = {
    [I in keyof T]: T[I] extends PageConfig ? PageConfig : 'error';
}

// to assert, that PagesConfig is valid
type __CheckOnlyPageConfigs<T extends { [k: string]: PageConfig }> = { }
type __check = __CheckOnlyPageConfigs<PagesConfig>

Now the last line will not compile, if a property in pages does not conform to the PageConfig type (see Typescript Playground)
You have to decide if you want these complicated types, but with a simple pages declaration or the more verbose version when declaring pages but with easier to understand types...


text:
Q: Jquery Load Message and Then Display Site I know there are tons of plugins/scripts that will pre-load the site while displaying a picture or a message but I am looking to extend the time x amount longer. In other words I want to display message, "This is the message" and while that is up I want the site to fully load and then wait x amount of seconds before fading that message out and fading in the rest of the site. Is this possible?

A: If you set the opacity of the page to 0 the browser will still render everything.
Then on .ready() fade it in.
Example:
HTML:

this is the site

this is the message

CSS:
#message{
    position:absolute;
    top:10px;
}
#content{
    opacity:0;
    filter: alpha(opacity=0);
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
}

JS:
$(function(){
    $('#content').delay(1000).fadeTo(500, 1);
    $('#message').delay(1000).fadeOut(500, function() {
        $(this).remove();
    });
});

jsFiddle:
http://jsfiddle.net/9kM7p/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hide content based on set cookie I'm setting myCookie for specific domain and when the cookie is set I want to hide content, but the show/hide IF statement is not working at all.
I would like to use the jquery .cookie plug-in, but this is what i have so far. writing the cookie does work, i just can't get the hide to function properly.
var cookieName = 'myCookie';
var cookieValue = 'myCookie';
var myDate = new Date();
myDate.setMonth(myDate.getMonth() + 12);
document.cookie = cookieName +"=" + cookieValue + ";expires=" + myDate
                  + ";domain=.example.com;path=/";

$(document).ready(function(){
    if ($.cookieName('myCookie') >= 0) {
        $('.myContent').hide();
    }
});

HTML

hide this content if the cookie is set

otherwise show this content if you don't have the required cookie

Any help in this would be much appreciated!

A: I made you an example:

hide this content if the cookie is set

This example hide the div because 25 > 0.
In other case:

hide this content if the cookie is set

Now i change the if condition and the div it's showing
myCookie = 25 and it's minor than 26 (so its working in both cases).
------------------------------EDITED----------------------------------
Javascript version:
function createCookie(name,value,days) {
if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/"; //replace this line

}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

function eraseCookie(name) {
createCookie(name,"",-1);
}

Javascript create cookie call:
createCookie('ppkcookie','testcookie',7)  //name_of_cookie,value,num_days

Reading the cookie:
var x = readCookie('ppkcookie1')

Full explanation here: http://www.quirksmode.org/js/cookies.html
In the createCookie function:
    document.cookie = name+"="+value+expires+"; path=/"; //replace this line

    //with this one adding domain
    document.cookie = name+"="+value+expires=" + ";domain=.example.com;path=/";

Saludos ;)

A: First,  download https://github.com/carhartl/jquery-cookie and reference in your page.
Then, it's as simply as changing your if statement to:
if ($.cookie("myCookie") !== undefined)
{
    $(".myContent").hide();
}

If you wanted to, you could use $.cookie to set the cookie too; the README.md has examples.


text:
Q: Slack Oauth/Authorize API Call I'm new to OAuth (and the Slack API) and have a question regarding Step 1 of Slack's OAuth Flow.
It says "Your web or mobile app should redirect users to the following url: https://slack.com/oauth/authorize".  At first I thought I should do an XHR request but then came to understand that that is not what I want.
After more research, I found that the initial oauth/authorize request should be sent as a direct request in the browser.  My problem is I can't begin to visualize how this should be done.  I've been referencing parts of this tutorial (scroll down to 'Web Server Apps' section) but it doesn't help me to be able to wrap my head around the oauth/authorize petition.
So basically, I'm looking for someone to better explain to me how that initial petition is supposed to be made.  Any and all help is greatly appreciated!
Thanks in advance

A: You should check out the Slack button docs.
There you will find an example for your slackapp, something like:

This button asks for authorization for a slackapp that includes incoming webhooks, you can add more features needed inside scope separating them by commas. scope=incoming-webhook,commands,bot,channels:read
As of your tutorial link, when it says you should link them to https://oauth2server.com/auth?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=photos
It is refering to wrap that into a button for the user:

   Auth Button

Hope this helps clarify the usage of /oauth/authorize


text:
Q: Validate pydantic fields according to value in other field I'm trying to validate some field according to other fields, example:
from pydantic import BaseModel, validator
class MyClass(BaseModel):
    type: str
    field1: Optional[str] = None
    field2: Optional[str] = None
    field3: Optional[str] = None

   @validator("type")
   def has_required_fields(cls, v, values):
       required_fields {"v1": ["field1", "field3"], "v2": ["field2"]}
       for required_field in required_fields[c]:
           if not values[required_field]:
               raise Exception

But my issue is that the values dict is empty. How should I access the other fields correctly in this situation?

A: Fields are validated in order they are initialized. Dictionary is empty because there is no validated fields as the type is the first field to be validated.
-> Reorder the field initialization
or
-> Use root validator

A: I believe you need to set "always=True" in the validator if you plan on type being empty when you initialize it. See here:
https://github.com/pydantic/pydantic/issues/691#issuecomment-785101470


text:
Q: Additional processor needed for WiFi-MCU module? I'm reading up on the design of WiFi-to-Ethernet converters, and came across the Ubiquiti U6-LR Teardown.
I noticed that both this device and its competitors have not just a WiFi-enabled MCU and PHY, but also include an additional processor with at least 512 MB of RAM.
If you were just looking to convert a WiFi signal to Ethernet, is this additional processor really necessary?
I'm Surprised you can't get away with a WiFi + MCU module linked to a PHY directly. I do not have experience in this area of electronics, so any support would be greatly appreciated.


text:
Q: Need to draw a diagram dynamically using php I have a requirement,drawing a open plot diagram using input dimensions of 4 sides.
https://www.google.com/search?client=firefox-b-d&tbm=isch&sa=1&ei=CRqfXdOSJb7gz7sPzc-w0Ag&q=real+estate+floor+plan+open+plot+images&oq=real+estate+floor+plan+open+plot+images&gs_l=img.3...40791.43818..44131...0.0..0.175.1327.0j10......0....1..gws-wiz-img.ONTZ6f8LBaE&ved=0ahUKEwiTu7SYz5HlAhU-8HMBHc0nDIoQ4dUDCAY&uact=5#imgdii=IfI5Qr1IfzbbzM:&imgrc=O-RkY4-5OUfoeM:
I want plot diagram with dimensions and angles,i will give input as individual plot dimensions.

A: You will need to use GD library to draw stuff in PHP.
Please go through:
https://www.php.net/manual/en/book.image.php


text:
Q: Sync await NULL reference exception while populating selectlistitem in Razor View I am injecting my service in view to populate dropdown in razor like this
@inject Web.Services.MyService  Options

Now I am trying to populate my dropdown like this
<select asp-for="CityID" asp-items="await Options.GetCities();" class="form-control form-control-sm">
            <option>--Select--</option>
</select>

Getcities method is below
public async Task<IEnumerable<SelectListItem>> GetCities()

        {

            var cities = await _cityrepository.ListAllAsync();

            var items = new List<SelectListItem>
            {
                new SelectListItem() { Value = null, Text = "All", Selected = true }
            };
            foreach (SetupCities city in cities)
            {
                items.Add(new SelectListItem() { Value = city.CityId.ToString(), Text = city.Name});
            }

            return items;
        }

I am getting following error
NullReferenceException: Object reference not set to an instance of an object.
EvolvedX.Web.Services.VMWHService.GetCities() in VMWHService.cs
+
            var cities = await _cityrepository.ListAllAsync();
AspNetCore.Views_Warehouse_CreateWarehouse.ExecuteAsync() in CreateWarehouse.cshtml
+
        <select asp-for="CityID" asp-items="await Options.GetCities();" class="form-control form-control-sm">

I can see as the first await hit getcities the function exit. what is the proper way to handle such scenario
M function is exiting before completing the method when it found await that is causing my selectlistitem to be null. I want to know how i modify my code so that selectlistitem get filled null exception will be solved


text:
Q: trigger.io [Error 5] Access is denied I just recently updated to the new version of forge, did not change anything on my setting and when I went to build my app I got an error that said it could not find the file..
so I made the copy of aapt file and put it in a directory where trigger said it was looking (the docs said trigger.io should have moved this file for me already but Im guessing it did not)
After I moved this file and ran the build again it looked like it found the file but now I get [Error 5] Access is denied.
I have checked the permissions on the folder as I am the admin and I have full permissions and I have launched trigger as an administrator and still nothing.
Thanks.

A: So again from what I can tell this is a problem with the python script that calls aapt.
When you look at the script it points only to aapt, this means its looking for a directory and not the aapt.exe file itself so the first thing that happens is
1) forge says it cant find the aapt directory, this is why you are getting the error message "cant find aapt tool"
2) by adding the directory you would get the access denied because then the script is trying to run all these commands on just the directory (this was the problem I ran into), by making the change below you do not need to create a directory, just leave everything how it is but add the exe and it should work
After doing some testing I found that by adding .exe to the pythong script in android_tasks.py the build was able to run successfully
if you look on line 35 of android_tasks.py and change 'appt' to 'appt.exe' it should build for you
this is what it looks like for me
path.join(sdk, 'build-tools', '*','aapt.exe')
Hope this helps


text:
Q: Why is pow(-infinity, positive non-integer) +infinity? C99 annex F (IEEE floating point support) says this:

pow(−∞, y) returns +∞ for y > 0 and not an odd integer.

But, say, (−∞)0.5 actually has the imaginary values ±∞i, not +∞. C99's own sqrt(−∞) returns a NaN and generates a domain error as expected. Why then is pow required to return +∞?
(Most other languages use the C library directly or, like Python in this case, copy the behaviour required of it by standards, so in practice this affects more than just C99.)

A: For odd integer y, it makes sense to define
pow(±0, y) = ±0

After all, raising to an odd power always preserves the sign. If we can preserve the sign of zero, we might as well do it. For positive non-integer y, we should define
pow(±0, y) = +0.

The sign is undefined. But we don't set this to NaN for -0 for the same reason we don't set sqrt(-0) equal to NaN: it just wouldn't make sense. (FWIW, this is also how it is defined in section 9.2.1 of the IEEE-754-2008 standard.)
Since 1/±0 = ±∞, and mathematically
pow(x,y) = 1/pow(1/x,y)

then setting x=±∞ in the above, leads to:
pow(±∞,y) = 1/pow(±0,y) = 1/+0 = +∞

for y a positive non-integer.


text:
Q: How to fix "AttributeError at /orders/create/ 'tuple' object has no attribute 'get' in Django I am trying to make an e-commerce website where the user submits the order and is redirected to the payment interface (Paytm ,India) .
However i get this error:
Traceback:

File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/utils/deprecation.py" in __call__
  96.             response = self.process_response(request, response)

File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/middleware/clickjacking.py" in process_response
  26.         if response.get('X-Frame-Options') is not None:

Exception Type: AttributeError at /orders/create/
Exception Value: 'tuple' object has no attribute 'get'

If I indent the "else clause" to be exactly below the if form.is_valid()
I receive this error.
Traceback:

File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/core/handlers/exception.py" in inner
  34.             response = get_response(request)

File "/Users/shyambalakrishnan/Dev/trydjango/lib/python3.7/site-packages/django/core/handlers/base.py" in _get_response
  126.                 "returned None instead." % (callback.__module__, view_name)

Exception Type: ValueError at /orders/create/
Exception Value: The view orders.views.order_create didn't return an HttpResponse object. It returned None instead.

Though in both the scenarios , the server runs without any errors.
views.py (In my orders app)
from django.shortcuts import render
from .models import OrderItem , Order
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from .forms import OrderCreateForm
from cart.cart import Cart
from payTm import Checksum
from django.http import HttpResponse
MERCHANT_KEY = 'my_merchant_key';

@csrf_exempt
def handlerequest(request):
return HttpResponse('done')
pass

@login_required
def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(
                    order=order,
                    product=item['product'],
                    price=item['price'],
                    quantity=item['quantity'],
                    total_price=item['total_price'],
                )
            cart.clear()
            param_dict = {
                'MID': 'osIFyR31215257913677',
                'ORDER_ID': str(order.id),
                'TXN_AMOUNT': str(order.total_cost),
                'CUST_ID': order.email,
                'INDUSTRY_TYPE_ID': 'Retail',
                'WEBSITE': 'WEBSTAGING',
                'CHANNEL_ID': 'WEB',
                'CALLBACK_URL': 'https://127.0.0.1:8000/handlerequest/'
            }
            param_dict['CHECKSUMHASH'] =
            Checksum.generate_checksum_by_str(param_dict, MERCHANT_KEY)
            return (request, 'paytm.html', {'order': order},
                    {'param_dict': param_dict})

    else:
        form = OrderCreateForm()
        return render(request, 'create.html', {'form': form})

paytm.html
{% extends 'base.html' %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Paytm merchant Payment Page</title>

 Redirecting you to the merchant.....

 Please don't refresh this page.....

<form action="https://securegw-stage.paytm.in/theia/processTransaction" method="POST" name="paytm">
    {% for key,value in param_dict.items %}
    <input type="hidden" name="{{ key }}" value="{{ value }}">
    {% endfor %}
</form>

I expect the output to get posted to handlerequest view and it should show me Done.
But unfortunately
that is not happening.
Also in paytm.html..form action= is getting posted to paytm's testing page which is given in https://developer.paytm.com/docs/v1/payment-gateway

A: You forgot to call render. Which, by the way, takes a single context dictionary, not two.
return render(request, 'paytm.html', {'order': order, 'param_dict': param_dict})


text:
Q: Can a client make a request with RestTemplate without a certificate to a secure SSL server? could somebody please help me with the following questions:
I have a REST server that has SSL enabled and a REST client that are on 2 different computers. Both are built with Spring boot. The server will have a .p12 or .pfx certificate.
If the REST client wants to make a request to the server, does it need to provide a certificate or can it make a request with a simple RestTemplate even if the server is secure? Does the same rules apply for Postman or can Postman send a request without a certificate as well?
I tried to create a request from the REST client, using a REST template with the certificate. But I am not sure, which certificate should I provide. Should it be the same certificate that is on the server or another one? And does the certificate from the server need to have a rule for the ip of the REST client to allow the requests?
The ssl server configuration:
ssl:
 key-store-type: PKCS12
 key-store: ${MY_DIR}/config/ssl/myCert.pfx
 key-store-password: 123456

The rest template from the client:
 RestTemplate restTemplate = null;
    try {
        SSLContext sslContext = SSLContextBuilder
            .create()
            .loadTrustMaterial(ResourceUtils.getFile("classpath:config/ssl/myCert.pfx"), password.toCharArray())
            .build();

        HttpClient client = HttpClients.custom()
            .setSSLContext(sslContext)
            .build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(client);

        restTemplate = new RestTemplate(requestFactory);
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | KeyManagementException ex) {
        LOGGER.error("Error getting the RestTemplate with ssl certificate", ex);
    }

A: If a client certificate is required or not depends fully on the server configuration. Some servers require client certificates, some do not. Please refer to the documentation of your specific REST API to find out what the requirements on the client are.

A: @Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpClient = HttpClients.custom()
                        .setSSLSocketFactory(csf)
                        .build();

        HttpComponentsClientHttpRequestFactory requestFactory =
                        new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
    return restTemplate;
}

This works for me.

A: please use this below import packages.
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


text:
Q: Android hdpi, xxhdpi, xxxhdpi. Provide drawables for only single directory? Android has the concept of several density buckets for handling screens with different resolution display. We all know that.
I am used to providing images for each bucket but there also exists practice of having some images only for a single bucket, say, xxhdpi - Android would scale it down as required.
I would like to know the practical advice for doing something like this. For example, if we were to categorize the images, we would probably have something like,

*

*App launcher icon(mipmap by default)

*Other icons

*Medium graphics with less details and/or size

*Heavy/detailed graphics, usually heavy in size as well

So, what would be the advice for icons - is it advisable to provide only xxxhdpi for them?
The same can be asked for each of the category.
As a side note, I checked out the resources with WhatsApp APK and they seem to have several of their images for only a single bracket - xxhdpi.
I am sure every developer follows some strategy for the resources. Any pointers or industry experience is appreciated.

A: If you are thinking to add png or webp type of image file then, you need to add different images based on their size in different folders such as xhdpi, mdpi, xxhdpi etc. If you do not add than the device will not automatically scale down images but use the image which you have added and near to device density. Another approach is, you can use drawable-vector images than it is okay that you only create one file which is XML, the mobile phone will automatically render this drawable type of file based on screen size. If you want to use images for icons than it is my suggestion to use vector drawable image always instead of different png files. This is my experience that, during one project execution, I have observed that for low memory devices the app gets crashed when using png and webp files, but when used vector graphics file instead of png/webp, it doesn't crash and work faster also benefits in application size. So, this is my personal opinion may be different people have different views.
Note: there are many online tools available which can convert png to svg image which can be imported to the android studio as drawable using vector assets, which is very helpful


text:
Q: How to spell numbers in TCL? I thought this might be possible in TCL with format, but I'm not seeing how. My requirement is a spell_number function, i.e. given the number 456,789, output the string four hundred and fifty six thousand, seven hundred and eighty nine.
Ideally I'd like to be able to pass this function a locale, and have the output localised, but English will do for now!
Any suggestions?


text:
Q: C# hash and sql server's hashbytel function, same implementation? I want to has on both the c# level and the sql server 2012 level.
How do I know if the SHA1 implementation will produce the same results?
In sql server I am doing:
HASHBYTES('SHA1', @data)

I haven't written my c# function yet.
I'm just worried if they don't produce the same hash value, I will get some inconsistencies in my application.
Note:  The columns I will be using to create a hash are datetime, nvarchar and int.  I have to convert these to strings correct?

A: You won't have any problems using this code:
    public static byte[] GetHash(string inputString)
    {
        HashAlgorithm algorithm = SHA1.Create();
        return algorithm.ComputeHash(Encoding.Unicode.GetBytes(inputString));
    }

It creates just the same hash as you can create on SQL Server:
HASHBYTES('SHA1', CAST(@data AS NVARCHAR(100)))


text:
Q: Facebook JavaScript SDK - getLoginStatus always returns unknown I am creating the application that will aggregate data from different social network profiles. So I have created an interface where client can choose which social network profile will he allow my application to access to. Interface has either a button that user clicks to authorize app or a button that revokes granted privileges to my application if a user changed hers/his mind about giving the right to my application.
My flow is following:

*

*On page load I ask Facebook whether the user is logged in

*

*If the user is logged in an option to disconnect is provided

*if the user is not logged in (or the status is unknown <- this is important) the option for logging in is provided.

And this works like it should. But a strange thing happens.
At the beginning
FB.getLoginStatus(loginStatusCallback, true);

function loginStatusCallback(response) {
    if(response.status == 'not_authorized') {
       ....
    } else if(response.status == 'unknown') {
       ....
    } else {
       ....
    }
}

For login I use
FB.login(loginCallback);

Login is successful and I act accordingly. But if I reload page response.status will be 'unknown' even though I am logged in to Facebook and my application is on the list of logged apps on Logged in with Facebook. As far as I understand SDK documentation 'unknown' should be the response if I am not logged in to Facebook (which is equivalent to not being connected in my application). So even if user has already logged in he will be bothered to log in again and that is not acceptable.

A: Looks that the problem was not on my side since it fixed with no code changes. The problem is that I once used FB.logout() and instead of just logging me out of the app Facebook just considered me as logged out.
Logging me back in did not change a thing. I have cleared all cookies from browser and did a re-login and problem ceased to exist.
For disconnecting user from application I do not use FB.logout() instead I revoke privileges with
FB.api("/me/permissions", "delete", logoutCallback);

Now everything works like it should... But to me this looks like an issue with SDK...


text:
Q: prove that : $a^{2}+b^{2}+c^{2}+4abc<\frac12$ Let $a,b,c$ be a sides of triangle
Such that : $a+b+c=1$ Then

prove that : $a^{2}+b^{2}+c^{2}+4abc<\frac{1}{2}$

My effort :
Since $a+b+c=1$ $\implies$ $2S=sr=bc\sin A=\frac{abc}{2R}$
Also : $S=\sqrt{s(s-a)(s-b)(s-c)}$
Also :
$a^{2}+b^{2}+c^{2}+2(ab+ac+bc)=1$
But I don't know how to complete it,any help is appreciated !

A: Homogenizing the equation, we WTS
$$\frac{(a+b+c)^3}{2} -(a+b+c)(a^2+b^2+c^2)-4abc > 0$$
Expanding and factoring, we obtain
$$(a+b-c)(a-b+c)(-a+b+c) > 0$$
This is true via the triangle inequality.

A: A standard trick to solve such problems is to use the substitution $a= y + z, b =x+z, c = x+y$, where $x, y, z>0$ (to see why this is so, draw the inscribed circle and pairs of equal tangents: $x, y, z$ are the lengths of the tangents)

So, we have $$x+y+z = \frac{1}{2}$$
and the inequality is $$ (x+y)^2 + (x+z)^2 + (y+z)^2  + 4 (x+y)(x+z)(y+z) < x+y+z$$
$$2x^2 + 2y^2 + 2z^2 + 2(xy+yz+xz) + 4 (x+y)(x+z)(y+z) < x+y+z $$
$$x^2 + y^2 +z^2 + (xy+yz+xz) + 2(x+y)(x+z)(y+z) < (x+y+z)^2 $$
$$ 2(x+y)(x+z)(y+z) < xy + xz +yz$$
$$(x+y)(x+z)(y+z) < (x+y+z) (xy+xz +yz)$$
$$ x^2y + xzy + x^2z + xz^2  + y^2x + y^2z + yxz + yz^2  < x^2y + x^2z + xyz + xy^2 +xyz +y^2z + xyz +xz^2 + yz^2 $$
$$2 xyz < 3xyz $$

A: we need to prove that
$$2(a^2+b^2+c^2)+8abc<(a+b+c)^2$$ or
$$8abc<\sum_{cyc}(2ab-a^2)$$ or
$$8abc<\sum_{cyc}a(b+c-a)$$ or
$$8abc<\sum_{cyc}a(b+c-a)(b+c+a)$$ or
$$8abc<\sum_{cyc}a(b^2+c^2+2bc-a^2)$$ or
$$2abc<\sum_{cyc}(a^2b+a^2c-a^3)$$ or
$$2abc(a+b+c)<\sum_{cyc}a\sum_{cyc}(a^2b+a^2c-a^3)$$ or
$$\sum_{cyc}2a^2bc<\sum_{cyc}(a^3b+a^3c+2a^2b^2+2a^2bc-a^4-a^3b-a^3c)$$ or
$$\sum_{cyc}(2a^2b^2-a^4)>0,$$ which is $16S^2>0$ by the Heron's formula.

A: Using homogeneization and Ravi's substitution, the problem boils down to showing that
$$2(a+b+c)(a^2+b^2+c^2)+8abc \leq (a+b+c)^3 $$
holds for any triple $(a,b,c)$ of side lengths of a triangle, i.e. that
$$4(A+B+C)((B+C)^2+(A+C)^2+(A+B)^2)+8(A+B)(A+C)(B+C) \leq 8(A+B+C)^3 $$
holds for any triple $(A,B,C)$ of positive numbers. The previous inequality simplifies into
$$ (A+B+C)(A^2+B^2+C^2+AB+AC+BC)+(A^2 B+B^2 A+A^2 C+C^2 A+B^2 C+C^2 B+2ABC) \leq (A+B+C)^3$$
which is equivalent to the trivial $-ABC\leq 0$.


text:
Q: Differential calculus vs Integral calculus I have never done integration in my life and I am in first year of university. Is it harder than taking the derivative? I've heard its just going backwards. Also, my high school taught me only differentiation, I don't know why we never touched on integration. I'm going to be starting it next week and I want to know what I'm facing. Is it generally considered harder than differentiation? Thank you in advance.

A: If you were fine with derivatives, you will be fine with integrals in 1st year calc. It never hurts to pay attention in class (which kind of implies attending class) and to do your homework.  In fact, if you have trouble with a problem, you should do more of the same kind as soon as you know the answer. As to difficulty:
Integrals start out harder than derivatives and wind up easier.  The reason derivatives are easier is that if a function has a derivative you can compute what it is.  There is an algorithm for doing so.  Sometimes the computation may be long and complicated.  But theoretically anyway, anyone can do this.
With the integral, you will be given a lot of problems to solve, but there is no algorithm.  The kind of problems you get in first year calculus will be solvable if you learn enough tricks. (They are chosen to be solvable).  There are hundreds of tricks because over the course of many years lots and lots of smart mathematicians have worked them out.  You'll probably learn 3 - 5 tricks in your first year class.
Integrals which are not subject to the tricks (that is, most of them) are evaluated with numerical or approximating methods and for practical purposes that works very well.  In fact, with the availability of computers, many of the old tricks have fallen into disuse, because it is faster to just do the numerical computation.
Integrals and derivatives are the reverse of one another in the same sense that addition and subtraction are.  As you know, taking an operation in one direction is often easier than reversing it.  Thus multiplication is easier than division,and raising things to powers is easier than the reverse: finding roots.
One expression of the connection between derivatives and integrals is the Fundamental Theorem of the Calculus, which you will probably be taught.  However, the two subjects are more intertwined than the Fundamental Theorem suggests. Indeed, I find the myriad entanglements fascinating.
Now why does the difficulty turn around later?  Derivatives are about differences and division which make a function less smooth; and the smoother a function is, the easier it is to work with.  For example, if f is differentiable, f' may only be continuous; and in fact it can be discontinuous.  You've taken a relatively smooth function and degraded it.
Integrals are about addition, that is to say averaging, which always smooths things out.  You can integrate discontinuous functions and they will come out continuous.  Integrate again and they will be differentiable, which is even smoother than continuous. We like smooth.

A: Integration is the reverse of differentiation through the Fundamental Theorem of Calculus.Integration is generally tougher because you will learn and use techniques like partial fractions, trigonometric substitutions, algebraic expression substitutions,integration by parts, etc.Certain real valued integrals can only be solved easily using techniques from Complex Analysis like Cauchy's Residual Theorem.To explain ,Integration is historically finding the limit of a sum of infinitesimals.Moerover,integrating a function smoothens it while differentiating a function makes it less smooth.Integration requires one to understand about the function's behaviour throughout the entire interval while differentiation only requires one to understand the behaviour of the function's rate of change about a point and its neighbourhood.


text:
Q: Pivot/gather multiple "crossed" values belonging to a common key I have some strangely stored time series data.  Two kinds of values, event and foo, can be observed together for different phenomena a and b.  The observations are in time t and belong to different category (those are basically different recordings).
Everything is stored as follows, in a kind of mixed wide format:
> tibble(category = c("x", "x", "y", "y"), t = c(1:2, 1:2),
  event_a = c(T, T, F, F), event_b = c(T, F, T, F),
  foo_a = c(1, 2, 3, 4), foo_b = c(10, 20, 30, 40))

# A tibble: 4 x 6
  category     t event_a event_b foo_a foo_b
  <chr>    <int> <lgl>   <lgl>   <dbl> <dbl>
1 x            1 TRUE    TRUE        1    10
2 x            2 TRUE    FALSE       2    20
3 y            1 FALSE   TRUE        3    30
4 y            2 FALSE   FALSE       4    40

Now I want convert it to long format, with the phenomena being used to index the kind of event with a value, and the foo value being matched to them via a/b:
# A tibble: 8 x 5
  category     t event value   foo
  <chr>    <dbl> <chr> <lgl> <dbl>
1 x            1 a     TRUE      1
2 x            1 b     TRUE     10
3 x            2 a     TRUE      2
4 x            2 b     FALSE    20
5 y            1 a     FALSE     3
6 y            1 b     TRUE     30
7 y            2 a     FALSE     4
8 y            2 b     FALSE    40

I'm looking for some sort of tidyr (or at least tidyverse) solution using gather/pivot_long and friends, but couldn't come up with anything useful, since there are multiple value columns in the result.  I was thinking about a join with the foo columns split of, but didn't really succeed, and I'm not really enought in to SQL to know what goes wrong there...

A: This is a complicated way of solving the problem but it works.
The idea is to solve the multiple columns issue with in two steps, a pivot_longer for each of event_* and foo_*. And bind_cols the results. Finally, remove the pattern 'event' from the new column event.
library(tidyverse)

df1 %>%
  dplyr::select(-starts_with('foo')) %>%
  pivot_longer(
    cols = starts_with('event'),
    names_to = 'event',
    values_to = 'value'
  ) %>%
  bind_cols(
    df1 %>%
    dplyr::select(-starts_with('event')) %>%
    pivot_longer(
      cols = starts_with('foo'),
      values_to = 'foo'
    ) %>%
    dplyr::select(-category, -t, -name)
  ) %>%
  mutate(event = sub('event_', '', event))
## A tibble: 8 x 5
#  category     t event value   foo
#  <chr>    <int> <chr> <lgl> <dbl>
#1 x            1 a     TRUE      1
#2 x            1 b     TRUE     10
#3 x            2 a     TRUE      2
#4 x            2 b     FALSE    20
#5 y            1 a     FALSE     3
#6 y            1 b     TRUE     30
#7 y            2 a     FALSE     4
#8 y            2 b     FALSE    40


text:
Q: Sine and Cosine functions and modulo Given some positive values $a_0,a_1,\cdots , a_{n-1}$ and an integer $n$, i want to   "build" a function $f$ such that for integer $k$ we have that :
$ f(k) = a_{k \mod n}$
for instance $a_0=\pi,a_1=e,a_2= 1.5$ and $n=3$ so $f(4) = a_{4\mod 3} = a_1 = e$
I want $f$ to be continues function over $\mathbb{R}$, so i don't want to break $f$ into "cases", but rather i would like to use $\sin , \cos$ functions.
Thanks.


text:
Q: Kivy Render Children Instructions So if I have a Layout that contains several children widget instances, how and when does the parent make sure they are all drawn to the screen? Assume our children are being animated in some simple fashion, so they constantly need to be updated.
If my ParentLayout class is roughly like so:
class ParentLayout(ScatterLayout):
    def __init__(self):
        #
        with self.canvas.before:
            #hook A
            #switchout framebuffer here?
            pass
        with self.canvas:
            #hook B
            pass
        with self.canvas.after:
            #hook C
            #recover framebuffer with just this Widget?
            pass

Q1: Are child drawables ultimately drawn to the parent.canvas?
A1: No they are not. canvas is full of instructions; its not a buffer.
It seems like children would be drawn somewhere around hook B, but I have no way to confirm or test this.
I am essentially trying to take a screenshot of certain groups of widgets after they have been freshly rendered into a buffer. I want to retrieve a texture representing the canvas of the ParentLayout and its children... no more, no less.

A: Widget already has a method that does this, Widget.export_to_png.
The canvas is ultimately an ordered list of instructions (mapping to opengl instructions). Drawing the screen involves running through this list, and is guaranteed to happen once per frame, so a simple solution in general is to Clock.schedule_once(your_function, 0) which should run the next frame after everything is rendered.


text:
Q: Find scalar interval containing maximum elements from population A and zero elements from population B Given two large sets A and B of scalar (floating point) values, what algorithm would you use to find the (scalar) range [x0,x1] containing zero elements from B and the maximum number of elements from A?
Is sorting complexity (O(n log n)) unavoidable?

A: Create a single list with all values, where each value is marked with two counts: one count that relates to set A, and another that relates to set B. Initially these counts are 1 and 0, when the value comes from set A, and 0 and 1 when the value comes from set B. So entries in this list could be tuples (value, countA, countB). This operation is O(n).
Sort these tuples. O(nlogn)
Merge tuples with duplicate values into one tuple, and accumulate the values in the corresponding counters, so that the tuple tells us how many times the value occurs in set A and how many times in set B. O(n)
Traverse this list in sorted order and maintain the largest sum of counts for countA of a series of adjacent tuples where countB is always 0, and the minimum and maximum value of that range. O(n)
The sorting is the determining factor of the time complexity: O(nlogn).

A: Sort both A and B in O(|A| log |A| + |B| log |B|). Then apply the following algorithm, which has complexity O(|A| + |B|):
i = j = k = 0
best_interval = (0, 1)

while i < len(B) - 1:
    lo = B[i]
    hi = B[i+1]

    j = k    # We can skip ahead from last iteration.
    while j < len(A) and A[j] <= lo:
        j += 1

    k = j   # We can skip ahead from the above loop.
    while k < len(A) and A[k] < hi:
        k += 1

    if k - j > best_interval[1] - best_interval[0]:
        best_interval = (j, k)

    i += 1

x0 = A[best_interval[0]]
x1 = A[best_interval[1]-1]

It may look quadratic at a first inspection but note we never decrease j and k - it really is just a linear scan with three pointers.


text:
Q: Determine if $\frac{x^2y}{x^2+y^2}$ is differentiable at $(x,y)=(0,0)$
Let $k$ be a real number. Define $f\colon\Bbb{R}^2\to\Bbb{R}$ by $$f(x,y)=\begin{cases}\dfrac{x^ky}{x^2+y^2}&\text{if $(x,y)\neq(0,0)$},\\k-2&\text{if $(x,y)=(0,0)$}.\end{cases}$$

*

*Find the value of $k$ such that $f$ is continuous at $(0,0)$.

*For the value of $k$ found in part (1), determine whether $f$ is differentiable at $(0,0)$.

  (Image that replaced text.)

So, I have solved the part (1) and found that the $k=2$.
Then both partial derivatives $f_x(0,0)$ and $f_y(0,0)$ of the function $f(x,y)$ equal $0$.
I know that if the partial derivatives exist and continuous at $(0,0)$, then the function is differentiable at $(0,0)$.
However, I also know that we can check the differentiability using this formula:

Definition. Let $f\colon X\to\Bbb{R}$ where $X\subset\Bbb{R}^2$ is open, and let $\mathbf{a}\in X$. Suppose $f_x(\mathbf{a}),f_y(\mathbf{a})$ exist. We say that $f$ is differentiable at $\mathbf{a}$ if $$\lim_{\mathbf{x}\to\mathbf{a}}\frac{f(\mathbf{x})-[f(\mathbf{a})+f_x(\mathbf{a})(x_1-a_1)+f_y(\mathbf{a})(x_2-a_2)]}{\|\mathbf{x}-\mathbf{a}\|}=0.$$
(Image that replaced text.)

And using, this formula I get that it is not continuous at $(0,0)$ (I have used $x=r\cos\alpha$ and $y = r\sin\alpha$ substitution to check it.)
Can you please tell me which approach is right, and is the function differentiable at $(0,0)$ if $k=2$?

A: We need to check whether
$$0 = \lim_{(a_1,a_2) \to (0,0)} \frac{f(a_1,a_2)}{\|(a_1, a_2)\|} = \lim_{(a_1,a_2) \to (0,0)} \frac{a_1^2a_2}{(a_1^2+a_2^2)^{3/2}}$$
If we approach $0$ along the line $y = x$ in the first quadrant, we get
$$\frac{f(t,t)}{\|(t,t)\|} = \frac{t^3}{(2t^2)^{3/2}} = \frac1{2^{3/2}}$$
which doesn't converge to $0$ as $t \to 0^+$ and therefore the above limit is not $0$.
We conclude that $f$ is not differentiable at $(0,0)$.


text: Q: Docker CLI in Freestyle Build Shell I'd like to run the postgres docker image instead of the postgres binary provided by cloudbees due to the lack of uuid and postgis support. However, the only two docker plugins I have access to are CloudBees Docker Custom Build Environment Plugin and Docker Commons Plugin. I'd like to avoid the extra complexity associated with the custom build env plugin due to the need to setup docker in docker(outer image for the slave and inner image for postgres).


text:
Q: Select rows where datetime = date and still use index I have a table with a datetime column which is indexed.  I'd like to select all the rows for a specific date.  Previously I've been using this:
SELECT *
FROM `table`
WHERE DATE(date_column) = '2016-04-12';

This works fine, however I've been noticing performance issues due to the fact that MySQL does not make use of the index once I apply the DATE() function.  I've also tried:
SELECT *
FROM `table`
WHERE SUBSTR(date_column,1,10) = '2016-04-12';

to no avail.  So far the only thing that seems to work is:
SELECT *
FROM `table`
WHERE date_column >= '2016-04-12'
    AND date_column < '2016-04-13'

This last query successfully uses the index but I'd like to know if there is a way to do this with only a single condition.

A: I like this code pattern; it is clear, precise (no confusion over midnight), and can use the index:
WHERE date_column >= '2016-04-12'
  AND date_column  < '2016-04-12' + INTERVAL 1 DAY

It even works 'correctly' for DATE, DATETIME, TIMESTAMP, DATETIME(6), etc.
'2016-04-12 00:00:00.000' is identical to '2016-04-12' when used in this context.  I prefer the latter because it is more concise.


text:
Q: Macbook Pro hanging on Boot Screen After Driver Installation After installing a USB 3.0 to VGA  driver for an external monitor, my Macbook won't start up after rebooting. I download fl2000 1.4.2 off of frescologic's site: https://support.frescologic.com/portal/en/kb/articles/fl2000-mac-driver-beta-release
When I rebooted my mac, it hung up on the boot page with the apple logo. The boot process hangs even though the loading bar is completely filled. I can't start my computer now so I'm trying to delete the driver via recovery mode. I think it is one of the kext files in Library/Extensions, but there are so many and none of them say frescologic.
My macbook pro is a 2015 model with Mac OS Mojave installed. Unfortunately I don't have a filevault backup so uninstalling the driver is my only hope of recovering my work. Is there an easy way to identify this kernel extension and am I even looking in the right place?

A: You're looking at the wrong /System/Library/Extensions. You've booted into macOS Recovery, which lives on its own volume separate from your normal boot volume. This means that all filesystem paths are relative to the root of the Recovery volume, not your boot volume.
Try first cding into /Volumes/YourBootVolumeName and continuing from there. When you find the appropriate KEXT(s), you can delete them or move them outside of the Extensions/ directory.
You will then also need to run the following command in order to update the kernel extension cache, otherwise you'll still be trying to boot as if you never deleted the Fresco Logic KEXTs: kextcache -update-volume /Volumes/YourBootVolumeName

A: The package comes with an uninstaller script, from which I was able to scavenge this list of file locations & deletion commands…
sudo rm -f /usr/local/libexec/screen_capture

sudo rm -f /Library/LaunchDaemons/com.frescologic.screen_capture.plist
sudo rm -f /Library/LaunchAgents/com.frescologic.screen_capture.plist

sudo rm -r /Library/LaunchAgents/com.frescologic.screen_capture-prelogin.plist

sudo rm -rf /Library/Extensions/FL2000.kext

sudo rm -rf /Library/Extensions/IOProxyVideoCard.kext

sudo rm -rf /Library/Extensions/IOProxyFramebuffer.kext

echo Please restart your computer for changes to take effect.

You should be able to run these from terminal


text:
Q: Particles moving in a unit circle. Two particles are moving in form of a unit circle.
One with a velocity v in the anticlockwise direction and one with velocity 3v in  clockwise direction.
They meet at P and they again meet at R.
Its very clear here that they meet (-1,0).
[Can be easily visualised by drawing the circle]
I shall generalise the problem which will make it harder which is the actual question.
Suppose we have $2n$ particles moving in a unit circle.
They are placed equidistant from each other having distance say $d$ from each other.
(Or You can say they make an equal angle of theta with each other consecutively)
Lets suppose when moving about the clockwise motion they have velocities $v,2v,3v,...,nv$.(in the first and the second quadrants).
Lets suppose when moving about the anticlockwise motion they have velocities $v,2v,3v,...,nv$.(in the fourth and the third quadrants).
Suppose at first they meet at point P.
Find the coordinates of the point P.Let them meet again at R.
What are the coordinates of the point R.
Suppose they meet for the nth time,what will be the coordinates of the point.

A: For simplicity, let's assume a pair of points start from $(1,0)$, one clockwise, and another counterclockwise.
For example, if red one goes at velocity $v$ counterclockwise, and blue one clockwise at velocity $3v$ or $2v$, they first meet at $90°$ or $120°$, respectively:

We can generalize this into one particle (red) going counterclockwise at velocity $pv$, and another (blue) clockwise at velocity $qv$.
The duration $t$ from the initial point to the first meeting point is such that when summed, the two particles have covered a full 360°, i.e.
$$p\,v\,t + q\,v\,t = 360°$$
i.e.
$$t = \frac{360°}{p\,v + q\,v}$$
This means that the first particle covers
$$p\,v \frac{360°}{p\,v + q\,v} = 360° \frac{p\,v}{p\,v + q\,v} = 360° \frac{p}{p + q}$$
and the second
$$q\,v \frac{360°}{p\,v + q\,v} = 360° \frac{q\,v}{p\,v + q\,v} = 360° \frac{q}{p + q}$$
In other words, the two particles will first meet at
$$\varphi_1 = \begin{cases}
\displaystyle 360° \frac{p}{p + q}, & p \le q \\
\displaystyle -360° \frac{q}{p + q}, & q \lt p \end{cases}$$
and since the situation repeats -- that is, we can treat the first meeting as a new initial positions --, the following meeting points will simply occur at multiples of that angle,
$$\varphi_n = n \varphi_1 , \qquad 2 \le n \in \mathbb{N}$$
Or, because the starting point $\varphi_0 = 0°$, we can simplify it as
$$\varphi_i = \begin{cases}
\displaystyle 360° \frac{i\;p}{p + q}, & p \le q \\
\displaystyle -360° \frac{i\;q}{p + q}, & p \gt q \end{cases}\tag{1a}\label{NA1a}$$
or in Cartesian coordinates,
$$\begin{cases}
\displaystyle x_i = \cos\left(\frac{2 \pi \, i \, p}{p + q}\right) \\
y_i = \begin{cases}
\displaystyle \sin\left(\frac{2 \pi \, i \, q}{p + q}\right), & p \le q \\
\displaystyle -\sin\left(\frac{2 \pi \, i \, q}{p + q}\right), & p \gt q \end{cases}
\end{cases}\tag{1b}\label{NA1b}$$

In OP's case, we have $2n$ particles, with $p_i = i$, $q_i = i$, $i = 1..n$. As angles a function of time, we have
$$\begin{aligned}
\varphi_{i}(t) &= \alpha i t \qquad & \text{for p particles} \\
\theta_{i}(t) &= -\alpha i t \qquad & \text{for q particles} \end{aligned}$$
where $\alpha$ is some angular velocity constant, that depends on $v$ and the choice of time units.
Essentially, we are looking at the other half of the full period of the system, compared to the question OP posed.
Note that after the slowest particles have done a full turn, the next slowest particles have done two full turns, and the fastest particles have done $n$ full turns; but all particles are back at their initial positions.
Numerically, I found out that because there is no particle with zero speed, starting at the same point with angular velocities $\pm \alpha$, $\pm 2 \alpha$, ..., $\pm n\,\alpha$, the particles are never uniformly distributed along the circle:
$$\begin{array}{l|ccc|c}
n & \varphi_1 & \delta_{max} & \delta_{min} & \delta \\
\hline
2 & 154.28° & 102.85° & 51.42° & 51.43° \\
3 & 108.00° & 72.00° & 36.00° & 36.00° \\
4 & 83.08° & 55.38° & 27.69° & 27.69° \\
5 & 67.50° & 45.00° & 22.50° & 22.50° \\
6 & 56.84° & 37.89° & 18.95° & 18.95° \\
7 & 49.09° & 32.73° & 16.36° & 16.36° \\
8 & 43.20° & 28.80° & 14.40° & 14.40° \\
9 & 38.57° & 25.72° & 12.86° & 12.86° \\
10 & 34.8° & 23.2° & 11.6° & 11.6° \\
20 & 17.7° & 11.8° & 5.9° & 5.9° \\
\end{array}$$
where $\varphi_1$ denotes the angle of the slowest particle, $\delta_{max}$ the largest angular separation between neighboring particles (without any other particles in between), and $\delta_{min}$ the smallest angular separation between neighboring particles, at minimum possible $\delta = \delta_{max} - \delta_{min}$.
(The numerical test considered angles modulo 360°, and ignored the "velocity order" of the particles, i.e. considered only particle pairs angular differences, where there were no other particles in between, and took special care to handle the pair that crossed 360° correctly. I did this, because I thought there might be a case where the particles were uniformly distributed, but their angular positions in different order than their velocities.)
Note that $n=1$ is an exception, since there is just one pair of particles, having the same velocity. When they have travelled one quarter of the unit circle, they are opposite each other, 90° separated from the starting point. After they travel another quarter circle, they are at the same point, 180° from their starting point. This repeats ad infinitum.
Thus, it looks like the answer to OP's question for $2 \le n \in \mathbb{N}$ is never. If the particles start uniformly distributed along the unit circle, with angular velocities $\pm \alpha$, $\pm 2 \alpha$, ..., $\pm n \alpha$, they will never meet in a single point.


text:
Q: Multiple android api calls using RxJava I have list of object which are sent as body for post request in each api call. All post request should be run in parallel. For each request it should notify  that either it is success or failure and once all post request completes it should notify. How to achieve this using rxjava
Please go through this code. Is this is the implementation?
    FlashSaleRetrofitService retrofitService = flashSaleProvider.createRetrofitService();
    FlashSale runningFlashSale = JumkeyApplication.getRunningFlashSale();

    List<Observable<Response<ClaimWrapper>>> wrapperResponseList = new ArrayList<>();

    for (final CartProduct cartProduct : cartProducts) {

        final Claim claim = new Claim();

        Customer customer = customerDataProvider.getCustomer();
        claim.setCustomerId(String.valueOf(customer.getId()));
        claim.setEmail(customer.getEmail());
        claim.setMobileNumber(customer.getDefaultAddress().getPhone());
        claim.setProductId(Long.parseLong(cartProduct.getProductId()));
        claim.setVariantId(Long.parseLong(cartProduct.getVariantId()));
        claim.setQuantity(cartProduct.getQuantity());
        claim.setSaleId(runningFlashSale.getSaleId());

        wrapperResponseList.add(retrofitService.claimProduct(claim));
    }

    Observable.zip(wrapperResponseList, new FuncN<List<Claim>>() {
        @Override
        public List<Claim> call(Object... args) {
            return null;
        }
    }).subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .doOnNext(new Action1<List<Claim>>() {
                @Override
                public void call(List<Claim> claims) {

                }
            })
            .compose(new Observable.Transformer<List<Claim>, Claim>() {
                @Override
                public Observable<Claim> call(Observable<List<Claim>> listObservable) {
                    return null;
                }
            })
            .subscribe(new Observer<Claim>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(Claim claim) {

                }
            });

If this is not the right way, please suggest me how to solve the above problem.

A: You are looking for the Zip method.
See the RxJava documentation.

A: If you want process results when all done.
Observable
        .zip(observables, new FuncN<List<Response<ClaimWrapper>>>() {
            @Override
            public List<String> call(Object... args) {
                List<Response<ClaimWrapper>> result = new ArrayList<>(args.length);

                for (Object arg : args) {
                    result.add((Response<ClaimWrapper>) arg);
                }
                return result;
            }
        })
        .subscribe(new Subscriber<List<Response<ClaimWrapper>>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(List<Response<ClaimWrapper>> results) {

            }
        });

If you want process one by one when each it
Observable
        .merge(observables)
        .subscribe(new Subscriber<Response<ClaimWrapper>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Response<ClaimWrapper> result) {

            }
        });


text:
Q: Unbinding in jQuery If an element is removed from the page, does it automatically unbind? Or is this a scenario in which one ought to unbind using jquery's unbind?
I assume it's done automatically...

A: If you remove elements using remove or empty, event handlers will automatically be removed in order to prevent memory leaks. Otherwise they will remain, unless they are explicitly unbinded prior to removing those elements.
EDIT: Turns out .html will remove event handlers too, by calling an internal .cleanData method (declared on line 5177). You can check this in the source:
html: function( value ) {
   ...

    for ( var i = 0, l = this.length; i < l; i++ ) {
                    // Remove element nodes and prevent memory leaks
                   if ( this[i].nodeType === 1 ) {
                       jQuery.cleanData( this[i].getElementsByTagName("*") );
                       this[i].innerHTML = value;
                    }
                }
   ...

So, to avoid memory leaks, don't directly use innerHTML to replace DOM elements which have attached jQuery event handlers.


text:
Q: Approximate number of unique items by stopping at first repeat I was just reading a blog post about determining how many purchases are needed to complete a set of N unique items, given that you know in advance how many items are in the set.
I was thinking as a modification of this problem, let's say you do not know how many unique items N are in the set (but we can assume each item appears with the same frequency). You're only way to estimate N is by repeatedly sampling ("buying") a box and opening it up to reveal inside which item is present. At some point, you will buy a repeat, but this will be at random, for example, let N = 26 and each letter a-z represent an item type (| represents an end of trial as a repeat is encountered):
a, f, i, l, o, f |

c, q, i, e, s, t, l, r, c |

As soon as a repeated purchase was made, the trial ends. I think this could be done easily in a computer simulation, but I'm wondering how difficult an analytical solution is, or whether it even exists. My guess is this a "classic" problem that has been worked out, but my google search prowess failed to turn up any results.
Specifically, is there a way to estimate N(n) with some confidence level X% after n=1, 2, 3, etc trials?

A: The probability, if there are $k$ distinct items, that the $n$th purchase is the first duplicate is $\dfrac{k!\,(n-1)}{(k-n+1)!\,k^n}$ for $2 \le n \le k+1$.
If a duplicate first turns up on the $n$th purchase, it seems empirically that an estimate of about $\hat{k}\approx \dfrac{n^2}{2}-\dfrac{5n}{6}$ distinct items in the population is reasonable.
But the uncertainty would be huge.  If there really had been $k=26$ distinct items, then the probability of the first duplicate turning up in any of the $3$rd through to $14$th purchases would be slightly less than $95\%$ and in those cases your estimate of $k$ might have been from $2$ distinct items though to $86$ distinct items.


text:
Q: MongoDB: conditional updates considering arrays as unordered I need each document in a collection to be updated only if its content is different, regardless of the order of the elements in nested lists.
Fundamentally, two versions should be the same if the elements are identical regardless of their order. MongoDB does not do that, by default.
def upsert(query, update):
    # collection is a pymongo.collection.Collection object
    result = collection.update_one(query, update, upsert=True)
    print("\tFound match: ", result.matched_count > 0)
    print("\tCreated: ", result.upserted_id is not None)
    print("\tModified existing: ", result.modified_count > 0)

query = {"name": "Some name"}

update = {"$set": {
    "products": [
        {"product_name": "a"},
        {"product_name": "b"},
        {"product_name": "c"}]
}}
print("First update")
upsert(query, update)

print("Same update")
upsert(query, update)

update = {"$set": {
    "products": [
        {"product_name": "c"},
        {"product_name": "b"},
        {"product_name": "a"}]
}}
print("Update with different order of products")
upsert(query, update)

Output:
First update
Found match:  False
Created:  True
Modified existing:  False

Same update
Found match:  True
Created:  False
Modified existing:  False

Update with different order of products
Found match:  True
Created:  False
Modified existing:  True

The last update does modify the document because the order of products are indeed different.
I did find a working solution which is to compare a sorting of the queried document's content and a sorting of the new one.
Thanks to Zero Piraeus's response for the short and convenient way to sort for comparison.
def ordered(obj):
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    else:
        return obj

I apply it to compare the current and the new versions of the document. If their sorting are different, I apply the update.
new_update = {
    "products": [
        {"product_name": "b"},
        {"product_name": "c"},
        {"product_name": "a"}]
}

returned_doc = collection.find_one(query)
# Merging remote document with local dictionary
merged_doc = {**returned_doc, **new_update}
if ordered(returned_doc) != ordered(merged_doc):
    upsert(query, {"$set": new_update})
    print("Updated")
else:
    print("Not Updated")

Output:
Not Updated

That works, but that relies on python to do the comparison, introducing a delay between the read and the write.
Is there a way to do it atomically ? Or, even better, a way to set a MongoDB Collection to adopt some kind of "order inside arrays doesn't matter" mode ?
This is part of a generic implementation. Documents can have any kind of nesting in their structure.

A: EDIT:
According to your comment (and the resemblance to other question) I suggest:
db.collection.updateMany(
  {"name": "Some name"},
  [{
    $set: {products: {
        $cond: [
          {$setEquals: [["a", "c", "b"], "$products.product_name"]},
          "$products",
          [{"product_name": "a"}, {"product_name": "c"}, {"product_name": "b"}]
        ]
    }}
  }]
)

See how it works on the playground example
Original answer:
One option is to use the query part of the update to work only on documents that are matching your condition:
db.collection.update(
  {"name": "Some name",
   "products.product_name": {
    $not: {$all: ["a", "b", "c"]}}
  },
  {"$set": {
    "products": [
      {"product_name": "b"},
      {"product_name": "c"},
      {"product_name": "a"}
    ]
  }}
)

See how it works on the playground example

A: @nimrodserok correctly pointed out a flaw in my first answer.  Here's my updated answer that's a slight variation of his answer.
This should also preserve the upsert option.
new_new_update = [
  {
    "$set": {
      "products": {
        "$let": {
          "vars": {
            "new_products": [
              {"product_name": "b"},
              {"product_name": "c"},
              {"product_name": "a"}
            ],
            "current_products": {
              # need this for upsert
              "$ifNull": ["$products", []]
            }
          },
          "in": {
            "$cond": [
              {"$setEquals": ["$$current_products", "$$new_products"]},
              "$$current_products",
              "$$new_products"
            ]
          }
        }
      }
    }
  }
]

Here's a mongoplayground.net example to demonstrate the concept.  You can change the "name" value to verify the upsert option.
I'm curious what the result values are for this update_one.


text:
Q: search nearby location with country name not working with geocoder I'm trying to get nearby users from a given location. I have users latitude and longitude(I'm taking out from their address).
Now when I'm searching a term like 'NC' its showing some of its results, But when I'm searching with the country name 'Unites States', it must show all the results but instead it doesn't show any result.
I'm using Geocoder gem for this.
Here's what I'm doing:
controller :
@user = User.near(params[:search], 20, :order => :distance)

Model:
geocoded_by :address1

View :
 Displaying all the results returned from @user

Any Idea what I should do so that it will return all results even if I search with a country name.

A: When Geocoder receive something like 'US', it will pick a single central coordinates pair and then search from it. So in your case, it will search for users within 20 miles from the center of US.
What you want to do, is to geocode the search and then find out which kind of input it was (country etc.)
So, for example, in your controller:
def search
  search = Geocoder.search(params[:search]).first

  if search.types.includes?('country')
    @users = User.where(country: search.address)
  else
    @users = User.near(search.coordinates, 20) # Will be ordered by distance by default
  end
end

You have to store the address components in you database.
The best way to have consistent data is to run a custom geocode callback:
class User < ActiveRecord::Base
  geocoded_by :address do |obj, results|
    if result = results.first
      obj.street = result.street_address
      obj.zip = result.postal_code
      obj.city = result.city
      obj.country = result.country
      obj.latitude = result.latitude
      obj.longitude = result.longitude
    end
  end

  after_validation :geocode, if: :address_changed?

  def address
    "#{street}, #{zip} #{city}, #{country}"
  end

  def address_changed?
    street_changed? || city_changed? || zip_changed? || country_changed?
  end
end

A: The accepted answer by @delba is great there is only one little typo and that is, Ruby doesn't have :includes? predicate for arrays , but :include?.
So it should be search.types.include?('country').


text:
Q: Quebra de texto dentro do Options do select html Eu estou tentando quebrar o texto dentro do option ou simplesmente diminuir o tamanha do modal (dropdown) do select, mas não consigo. Alguem já conseguiu? como proceder nisto, estou preso com sistema nisto, pois ele precisa esta em responsivo e quero tudo organizado.

A: Para diminuir o dropdown, você pode usar a propriedade width, no elemento select.

.select1 {
  width: 50px;
}

.select2 {
  width: 100px;
}
<select class="select1">
  <option value="volvo">Lorem ipsum dolor asit met</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<select class="select2">
  <option value="volvo">Lorem ipsum dolor asit met</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

Já quebrar o texto no option, eu não sei. No entanto, posso recomendar que você diminua a fonte do select.

.select1 {
  font-size: 5px;
}
.select2 {
  font-size: 12px;
}
<select class="select1">
  <option value="volvo">VolvoVolvoVolvoVolvoVolvoVolvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<select class="select2">
  <option value="volvo">VolvoVolvoVolvoVolvoVolvoVolvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>


text:
Q: Can XSL-FO be use to created MANY documents? I am looking into various technologies associated with formatting data into document form.  There are many software platforms to do so, but most are quite expensive.
I stumbled upon XSL-FO and have been looking deeper into it to see if it may fit my needs.  But so far I have not been able to answer this question.  Can it be used to create multiple documents into a single stream?
FOP can create AFP (the print language my company uses for mass printings) and it works pretty well (I would need to do more font configuration to make it truly worthwhile).  But I have not yet seen any evidence that XSL-FO can create hundreds, thousands, or in my case hundreds of thousands of documents (statements) in a single print stream.
One more question for anyone who knows FOP... can it index (TLEs, NOPs, etc.) documents in an AFP stream?
ADDITIONAL INFORMATION:
I do not have any code to show/share because this little project is in the research phase.  I would dearly love to know if XSL-FO will meet my needs BEFORE I spend the next 4-6 months buried in books, tutorials, and manuals, coding something together, only to find it can't do what I need.
What I am looking for is a way to create multiple documents in a single print stream (AFP) for spooling to commercial printers.  I found fop as an open-source Java-based converter for turning XSL-FO to AFP (or PDF, or a host of other outputs).
For these purposes, a document may be defined as follows: a group of pages/impressions that begin with page 1.
So far, I have not seen how XSL-FO can produce anything other than a single document at a time.  Granted, my foray into XSL is in its infancy, which is why I've sought answers here.
Some potential answers to this question that would not surprise me might be:
"Yes, XSL-FO can do this... look into the fo:new-document tag."
"No, XSL-FO is intended to create a single document.  To produce multiple documents, you need to either use a third-party piece of software or post-process the XSL-FO to "fake" multiple documents."
If the answer is yes, then I will pursue this further.  If the answer is yes, but it costs money, then I will pursue other avenues that also cost money but that are far easier to develop with.  If the answer is no, then I will again pursue other avenues.
I hope this clarifies my query.  Anyone have some good insight for me?
MORE INFO:
This looks promising: http://xmlgraphics.apache.org/fop/trunk/output.html#afp

A: Certainly XSL FO can be used to do such a thing: (1) producing many individual documents from a single large (repetitive document), (2) producing a large document from a single large document or (3) even combinations of this ... simultaneously. Refer to the concepts posted within this whitepaper:
http://www.renderx.com/solutions/large_report_formatting.html
with details here:
PDF Report
These apply to RenderX and how it functions. In such a solution, a single XML input could represent many thousands of repeating invoices. You can split in chunks, send to multiple simultaneous threads of composition engines running in separate threads, JVMs, even on different machines and assemble or whatever desired to create the desired output. Because you can parallelize the composition step, you can scale with threads, cores, CPUs and machines even to get the performance you need. Such methods are in production in major organizations throughout the world.
We do not evaluate or test FOP, the concepts presented would require a completely thread safe renderer as is XEP and a rendering thread controller as is EnMasse. XEP is an FO renderer and does supports AFP with TLEs, etc. as one output format (also PDF, PDF Forms, Postscript, XPS, PPML, SVG, XHTML ...).


text:
Q: Timer App closing out after second onClick of the START button I am pretty new to android and am making a timer app (The code is not complete, as you can see, but I am testing on thing at a time).  hitting the start button a second time results in the app closing out. I edited my code so that the timer is being recreated each call to onClick, but the app still closes out after the second click. Thank you for the help.
package com.example.ryan.timerapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    secondsView = (TextView) findViewById(R.id.seconds);
    tenSecondsView = (TextView) findViewById(R.id.tensSeconds);
    hoursView = (TextView) findViewById(R.id.hours);
    tenHoursView = (TextView) findViewById(R.id.tensHours);
    minutesView = (TextView) findViewById(R.id.minutes);
    tenMinutesView = (TextView) findViewById(R.id.tensMinutes);

       timer = new Timer();

}

 TextView secondsView;
 TextView tenSecondsView;
 TextView hoursView;
 TextView tenHoursView;
 TextView minutesView;
 TextView tenMinutesView;

    Timer timer;
    TimerTask timerTask;

    public void start(View view){

        if(timer != null) {
            timerTask.cancel();
            timer.cancel();
        }
        timer = new Timer();
         timerTask = new TimerTask() {
            @Override
            public void run() {

                runOnUiThread(new Thread(new Runnable() {
                    @Override
                    public void run() {

                        int secondsInt = Integer.parseInt(secondsView.getText().toString());

                        int tenSecondsInt = Integer.parseInt(tenSecondsView.getText().toString());

                        int hoursInt = Integer.parseInt(hoursView.getText().toString());

                        int tenHoursInt = Integer.parseInt(tenHoursView.getText().toString());

                        int minutesInt = Integer.parseInt(minutesView.getText().toString());

                        int tenMinutesInt = Integer.parseInt(tenMinutesView.getText().toString());
                        if (secondsInt < 9) {
                            secondsInt++;
                            secondsView.setText(secondsInt + "");
                        } else {
                            secondsInt = 0;
                            secondsView.setText(secondsInt + "");
                            if (tenSecondsInt < 6) {
                                tenSecondsInt++;
                                tenSecondsView.setText(tenSecondsInt + "");
                            } else {
                                tenSecondsInt = 0;
                                tenSecondsView.setText(tenSecondsInt + "");
                                if (minutesInt < 9) {
                                    minutesInt++;
                                    minutesView.setText(minutesInt + "");
                                } else {
                                    minutesInt = 0;
                                    minutesView.setText(minutesInt + "");
                                }
                            }
                        }
                    }
                }));

            }
        };
        timer.scheduleAtFixedRate(timerTask,0, 1000);

    }

public void stop(View view){
    timer.cancel();
}

public void reset(View view){

    secondsView.setText("0");
    tenSecondsView.setText("0");

    minutesView.setText("0");

    tenMinutesView.setText("0");

    hoursView.setText("0");

    tenHoursView.setText("0");

}

}

XML:
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.ryan.timerapp.MainActivity"
    android:layout_margin="5dp"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="35sp"
        android:text="Timer"
        android:gravity="center"
        />
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center"
        android:layout_weight="2"
        >
        <TextView
            android:id="@+id/tensHours"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text="0"
            />
        <TextView
            android:id="@+id/hours"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text="0"
            />
        <TextView
            android:id="@+id/firstColon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text=":"
            />
        <TextView
            android:id="@+id/tensMinutes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text="0"
            />
        <TextView
            android:id="@+id/minutes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text="0"
            />
        <TextView
            android:id="@+id/secondColon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30sp"
            android:text=":"
            />
        <TextView
            android:id="@+id/tensSeconds"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text="0"
            />
        <TextView
            android:id="@+id/seconds"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="35sp"
            android:text="0"
            />
    </LinearLayout>

    <Button
        android:id="@+id/startButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="START"
        android:textSize="30sp"
        android:onClick="start"
        />
    <Button
        android:id="@+id/stopButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="STOP"
        android:textSize="30sp"
        android:onClick="stop"
        />
    <Button
        android:id="@+id/resetButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_weight="2"
        android:text="RESET"
        android:textSize="30sp"
        android:onClick="reset"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        />

    </LinearLayout>

A:
the first being the Seconds counter not updating past 1 second

TimerTask is used to run a particular task at a specified time.
timer.schedule() is not meant to run continuously.
Check this documentation.
So this block of code-
 int secondsInt = Integer.parseInt(txt.getText().toString());
                    secondsInt++;

                    if(secondsInt<=6) {
                        txt.setText(secondsInt + "");
                    }

will run only once . Hence

Seconds counter not updating past 1 second

is the apparent behavior.

hitting the start button a second time results in the app closing out

You are trying to run an already scheduled TimerTask.
You need to create a new Timer instance to start your TimerTask again.
Change your start() method -
public void start(View view){

        if(timer != null) {
                    timerTask.cancel();
                    timer.cancel();
                }
                timer = new Timer();
                timerTask = new TimerTask() {
                    @Override
                    public void run() {

                        runOnUiThread(new Thread(new Runnable() {
                            @Override
                            public void run() {
                                int secondsInt = Integer.parseInt(txt.getText().toString());
                                secondsInt++;

                                if(secondsInt<=6) {
                                    seconds.setText(secondsInt + "");
                                }
                            }
                        }));

                    }
                };
                timer.scheduleAtFixedRate(timerTask,0, 1000);

    }

Also, no need to initialize your TextView again and again . Do it once only in onCreate() -
private TextView seconds;
  private Timer timer;
  private TimerTask timerTask;

In onCreate()
seconds = (TextView) findViewById(R.id.seconds);


text:
Q: JavaScript in DOM popup SilverStripe 2.4.7
Hi
I have been reading this tutorial and have tried to implement it but I am confused.  It doesn't seem to work but I'm not getting errors or anything.
My question is am I missing something like a module, etc?  I have implemented the code like so...
   JQ = jQuery.noConflict();
   JQ(document).ready(function() {
   // Find the select box, named differently on the update and add forms
   var sel = JQ('select[id="DataObjectManager_Popup_DetailForm_Status"]');
   if (sel.attr('id') == undefined) {
       sel = JQ('#DataObjectManager_Popup_DetailForm_Status');
   }

   // hide either the internal or external link editing box
   if (sel.val() == 'rejected' || 'Rejected') {
       JQ('#DataObjectManager_Popup_DetailForm_Reason').show();
   }  else {
       JQ('#DataObjectManager_Popup_DetailForm_Reason').hide();
   };

   // toggle boxes on drop down change
   sel.change(function(e) {
   if (sel.val() == 'rejected' || 'Rejected') {
     JQ('#DataObjectManager_Popup_DetailForm_Reason').show();
   }  else {
     JQ('#DataObjectManager_Popup_DetailForm_Reason').hide();
   };
 });
});

Nothing happens when I use the dropdown so do I need to install a module too or is there something else I'm missing?
Thanks in advance.


text:
Q: React Could not find a declaration file for module 'react-vis' I installed react-vis library for my react code.
I used this command, like in the tutorial: npm install react-vis --save
But when I include the library with this code: import {XYPlot, XAxis, YAxis, HorizontalGridLines, LineSeries} from 'react-vis';
It gives me the following error:
Could not find a declaration file for module 'react-vis'. 'C:/react-vis/dist/index.js' implicitly has an 'any' type.Try npm install @types/react-vis if it exists or add a new declaration (.d.ts) file containing declare module 'react-vis';
And even that doesn't work.
Anyone know how to do this?
I'm just a beginner in react.

A: A declaration file was created by evgsil; you can get the declaration file he created in his repo at https://github.com/evgsil/react-vis-typings.  It is the react-vis.d.ts file.  To use it, you can copy the file to a local folder and then reference it from the file that imports react-vis.  To reference it, you may add
/// <reference path="./react-vis.d.ts"/>

to the top of the file that imports it.  The value assigned to the reference path should be the relative path to wherever you saved the d.ts file.
So a file with react-vis imported may look like this:
/// <reference path="../../../dts/react-vis.d.ts"/>
import React from 'react';
import "react-vis/dist/style.css";
import {XYPlot, XAxis, YAxis, HorizontalGridLines, LineSeries} from 'react-vis';

export function FirstPlot() {
    return(
        <XYPlot
            width={300}
            height={300}>
            <HorizontalGridLines />
            <LineSeries
                data={[
                {x: 1, y: 10},
                {x: 2, y: 5},
                {x: 3, y: 15}
                ]}/>
        <XAxis />
            <YAxis />
        </XYPlot>
    )
}

Hopefully an @types solution will be forthcoming soon, but until then this has worked for me.
P.S.  If you are wondering what that /// <reference path /> is all about, you can read the specific documentation about it here.  In typescript, it is called a "triple-slash directive."

A: I created a demo in this sandbox here:
https://codesandbox.io/s/64k21qmq43
make sure you have the latest version of react-vis (1.11.2)
Package.json
"dependencies": {
    "react-vis": "1.11.2"
  },

Maybe remove all your node modules and run npm install again with your new updated package.json.
Usually the error you describe come with your modules acting weird... So thats why i suggest to re-install them ;)
then your component will work fine like this:
import React from "react";
import ReactDOM from "react-dom";

import {
  XYPlot,
  XAxis,
  YAxis,
  HorizontalGridLines,
  LineSeries
} from "react-vis";

import "./styles.css";

function App() {
  return (

      <XYPlot width={300} height={300}>
        <HorizontalGridLines />
        <LineSeries data={[{ x: 1, y: 10 }, { x: 2, y: 5 }, { x: 3, y: 15 }]} />
        <XAxis />
        <YAxis />
      </XYPlot>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

If you follow my sandbox example you should be fine!, good Luck!

A: I believe you are using typescript for compiling your code.
First try
npm install @types/react-vis.
If it does not work then you have to take longer route:
- Create a folder name : typings in the root of your project,
- inside typings create a new folder with name: "react-vis" and in that folder create a react-vis.d.ts file
- write declare module 'react-vis' in react-vis.d.ts file.
// react-vis.d.ts
 declare module 'react-vis';

- go to your tsconfig.json file and add "typeRoots": [ "../../typings", "../../node_modules/@types"] in the compilerOptions (with the proper relative path to your folders) to let TypeScript know where it can find the types definitions of your libraries and modules and add a new property
- add exclude": ["../../node_modules", "../../typings"] " to the tsconfig.json file.
Here is an example of how your tsconfig.json file should look like:
{
"compilerOptions": {
    "module": "commonjs",
    "noImplicitAny": true,
    "sourceMap": true,
    "outDir": "../dst/",
    "target": "ESNEXT",
    "typeRoots": [
        "../../typings",
        "../../node_modules/@types"
    ]
},
"lib": [
        "es2016"
],
"exclude": [
    "../../node_modules",
    "../../typings"
]

}
For more information, do refer to : https://stackoverflow.com/a/51320328/4998546


text:
Q: CosmosDB Update c#: Could not determine JSON object type for type System.String[] I want to update a field in CosmosDB to array like below:
"Aliases": [
"John",
"Johnny"
],
Below is my code:
           dynamic GuideDoc= new
           {
               id = "00B2845F-F394-5E93-9A26-E70000452562",
               type = "Guide",
               GuideGuid= "00B2845F-F394-5E93-9A26-E70000452562"
           };

           ItemResponse<dynamic> clientGuideResponse1 = await this.container.ReadItemAsync<dynamic>(GuideGuid, new PartitionKey(PartitionKey));
           dynamic itemBody1 = clientGuideResponse1.Resource;

           String[] AliasesConverted= JSONDecoders.DecodeJSONArray(AliasesValues);
           itemBody1.Aliases= AliasesConverted;

           GuideDoc= itemBody1;

           GuideResponse = await this.container.ReplaceItemAsync<dynamic>(GuideDoc, GuideGuid, new PartitionKey(PartitionKey));

The part that stores the data to itemBody1.Aliases is returning an error "Could not determine JSON object type for type System.String[]"
How do I make it save the value to Aliases as an array?

A: The easiest way to add new properties while keeping everything else intact is deserializing it into a Dictionary. As example:
var response = await container.ReadItemAsync<Dictionary<string, object>>(id, partitionKey);
var item = response.Resource;
item["Aliases"] = new[] { "John", "Johnny" };
await container.ReplaceItemAsync(item, id, partitionKey);

The reason it doesn't work is because the deserializer will return the result as JObject when you use dynamic as type. You can't navigate the JObject through the properties as if it were deserialized into a class with properties. The error you describe is a bit different than I would have thought though.


text:
Q: React app not rendering inside react-native-webview I am planning to show my react app inside react-native-webview. I implement the code for WebView. When I put URL https://www.w3schools.com , It works perfectly. But when I used my react app URL https://jshossen.com/ it not rendering anything. It only shows a white screen. Anyone help me with whats I have to do to run React App inside WebView?

This is my code sample:
import React from 'react';
import { StyleSheet, StatusBar, Platform, View } from 'react-native';
import { WebView } from 'react-native-webview';

const App: () => React$Node = () => {
  return (
    <View style={styles.topContainer}>
      <View style={styles.container}>
        <WebView
          // source={{ uri: 'https://www.w3schools.com/' }}
          source={{ uri: 'https://jshossen.com' }}
          scalesPageToFit={true}
          javaScriptEnabled={true}
          startInLoadingState={true}
        />
      </View>
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    overflow: 'hidden',
    height: '100%',
    width: '100%',
  },
  topContainer: {
    flex: 1,
    paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0
  }
});

export default App;

A: <WebView source={{ uri: url }}
          style={{ resizeMode: 'cover', flex: 1 }}
          injectedJavaScript={`const meta = document.createElement('meta'); meta.setAttribute('content', 'width=width, initial-scale=1, maximum-scale=1, user-scalable=2.0'); meta.setAttribute('name', 'viewport'); document.getElementsByTagName('head')[0].appendChild(meta); `}
          scalesPageToFit={false}
        />

This should work, please have a test


text:
Q: Using a regex to extract prefixed values from a string I have a string of the form
s = "something prefix1 value1 prefix2 value2 prefix1 value3 prefix2 value4"

I want to extract the values (value1, value2 etc.) using a regular expression.  There can be any number of value/prefix pairs.  There are only two prefixes.  The values may have spaces.
I've tried things like
/((prefix1|prefix2)(.*))+/

This doesn't work as the first .* match matches the rest of the string.
I'm working in ruby.
Thanks in advance.

A: It sounds to me like you want to use a split function:
tokens = s.split(/\s+/)
This will give you a list of tokens that were separated by white space.
Check out this section in the ruby cookbook.
UPDATED: If you absolutely must match them using a single regex expression, this should work for you:
/((\w+)\s+(.*?))+/

A: Try /((prefix1|prefix2)(.*?))+/
The question mark makes it non-greedy.

A: what's he expected result?
if you simply want to extract values without prefixes try this:
str = "something prefix1 value1 prefix2 value2 prefix1 value3 prefix2 value4"

p str.split.reject { |s| s =~ /prefix/ }

#=> ["something", "value1", "value2", "value3", "value4"]

A: String#split can split on a regex:
s = "something prefix1 value1 prefix2 value2 prefix1 value3 prefix2 value4"
p s.split(/ prefix1 | prefix2 /) # ["something", "value1", "value2", "value3", "value4"]


text:
Q: Windows alternative CLI with no filename character limit Trying to run mvn clean install -Dfull on a project returns back with a filename or extension too long error. I've been told you can install alternative CLI's on Windows that do not have the limit.
Can anyone lead me to where I can install this or am I not correct in my understanding ?
Thank you.
Update: I'm using Windows 7 64 bit

A: If you happen to be running the just released Windows 10 v1607, you can enable paths up to (about) 32 KB long either globally via registry or policies, or per-application via manifests.
From the just updated reference for Naming Files, Paths, and Namespaces:

Tip    Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must opt-in to the new behavior.
A registry key allows you to enable or disable the new long path behavior. To enable long path behavior set the registry key at HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD). The key's value will be cached by the system (per process) after the first call to an affected Win32 file or directory function (list follows). The registry key will not be reloaded during the lifetime of the process. In order for all apps on the system to recognize the value of the key, a reboot might be required because some processes may have started before the key was set.
The registry key can also be controlled via Group Policy at Computer Configuration > Administrative Templates > System > Filesystem > Enable NTFS long paths.
You can also enable the new long path behavior per app via the manifest [...]

Of course, this enables support for paths >260 characters long at the system (API) level. If an application has its own assumptions hardcoded about the max path length (for example wchar_t mypath[_MAX_PATH];) then no amount of system-level support can magically make that particular application work with longer paths.

A: There's a program called Cygwin that let you use many of Linux bash terminal inside windows, I hope it will help you.