text:
Q: typescript: how to correctly type key and value parameters in Object.entries().forEach([key,value]) => I got an object with specific key/value parameters and I want to iterate over it with entries() method of Object followed by a forEach() method of Array. However I do not understand how I have to type this configuration to avoiding a typescript error:
type objType = {
  prop1: number | undefined;
  prop2: number | undefined;
  prop3: number | undefined;
};

const obj: objType = {
  prop1: 2,
  prop2: 0,
  prop3: undefined,
};

//1st attempt
Object.entries(obj).forEach(([key, value]) => {
  if (value === undefined || value < 5) obj[key] = 5;
});

//2nd attempt
Object.entries(obj).forEach(
  ([key, value]: [keyof objType, number | undefined]) => {
    if (value === undefined || value < 5) obj[key] = 5;
  }
);

In first attempt, I let typescript infer the type of key (→ string) and value (→ number|undefined). But in this case I got an error when doing obj[key] :

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'objType'. No index signature with a parameter of type 'string' was found on type 'objType'.

In second attempt I forced the type of key to correspond to the key of obj using keyof operator, but this type definition is not allowed and I got the following message :

Argument of type '([key, value]: [keyof objType, number | undefined]) => void' is not assignable to parameter of type '(value: [string, number | undefined], index: number, array: [string, number | undefined][]) => void'. Types of parameters '__0' and 'value' are incompatible.
Type '[string, number | undefined]' is not assignable to type '[keyof objType, number | undefined]'.
Type at position 0 in source is not compatible with type at position 0 in target.
Type 'string' is not assignable to type 'keyof objType'.

I understand the failure for first attempt but not for the second. Why TS believes that I want to assign string to the string enumeration, I'm guessing to do the opposite...?
How is the correct way to type this configuration ?

A: Why
First of all we need to understand why this happening:
Let's check the simplest example:
const obj = {a: 1};
Object.keys(obj).forEach((key:keyof typeof obj)=> ''); // fails because Type 'string' is not assignable to type '"a"'

This happens, because TS can't guarantee that there is no other keys in the object. Thus, it can't guarantee that key will be ONLY 'a'.
In  your case, this means that TS can't ensure that value of obj[key] will be number. It might be anything, thus TS throws an error.
Example
Option #1
One way to handle this is to force TS to use your types:
//1st attempt
Object.entries(obj).forEach(([key, value]) => {
  if (value === undefined || value < 5) obj[key as keyof typeof obj] = 5;
});

//2nd attempt
Object.entries(obj).forEach(
  ([key, value]) => {
    if (value === undefined || value < 5) obj[key as keyof typeof obj] = 5;
  }
);

This is OK in case you are absolute sure that no extra keys will be present.
Option #2
Another way is to redesign your types into something a bit more generic:
type objType = {
    prop1: number | undefined;
    prop2: number | undefined;
    prop3: number | undefined;
}

const obj: Record<string, number | undefined> = {
    prop1: 2,
    prop2: 0,
    prop3: undefined,
};

//1st attempt
Object.entries(obj).forEach(([key, value]) => {
    if (value === undefined || value < 5) obj[key] = 5;
});

//2nd attempt
Object.entries(obj).forEach(
    ([key, value]) => {
        if (value === undefined || value < 5) obj[key] = 5;
    }
);

At the code above we are clearly states that we allows any string keys.
Please check for some extra details

A: Option 3: Use a key signature
On your type objType add a key signature like so:
  [key: string]: number | undefined;

Here is the full code example:
type objType = {
  [key: string]: number | undefined;
  prop1: number | undefined;
  prop2: number | undefined;
  prop3: number | undefined;
};

const obj: objType = {
  prop1: 2,
  prop2: 0,
  prop3: undefined,
};

//1st attempt
Object.entries(obj).forEach(([key, value]) => {
  if (value === undefined || value < 5) obj[key] = 5;
});

//2nd attempt
Object.entries(obj).forEach(
  ([key, value]: [keyof objType, number | undefined]) => {
    if (value === undefined || value < 5) obj[key] = 5;
  }
);

Here is a screenshot showing VSCode is recognizing the typing:


text:
Q: Android. How change default locale fo string.xml in values I have an application with only russian locale. If I am not mistaken, the string.xml in the res/values is the  english locale by default. But english and russian have different plurals. For example:
In russian:

*

*1,21,31..x1 книга

*2-4, 2(2-4), 3(2-4), .., x(2-4) книги

*in other cases - книг

In english:

*

*1 book

*n books

Problems begin when the user changes system language from russian to other language.
How can I change default language for my application? Or maybe it is possible to force the application to use the russian plurals?

A: I finally found the answer:
https://developer.android.com/studio/write/tool-attributes#toolslocale
<resources xmlns:tools="http://schemas.android.com/tools"
tools:locale="es">

From the doc:

This tells the tools what the default language/locale is for the resources in the given  element (because the tools otherwise assume English) in order to avoid warnings from the spell checker. The value must be a valid locale qualifier.

A: you can create different String.xml files
like this
values/
           strings.xml
       values-es/
           strings.xml
       values-fr/
           strings.xml

Check google official document https://developer.android.com/training/basics/supporting-devices/languages.html
& https://developer.android.com/guide/topics/resources/localization.html

A: create new value folder values-ru and place string.xml in that.
in java change your app language programatically with this code. for change to rushion call method with ru parameter like this changeLanguage("ru").
public void changeLanguage(String languageToLoad) {
        //for language change
        Locale locale = new Locale(languageToLoad);
        Locale.setDefault(locale);
        Configuration config = new Configuration();
        config.locale = locale;
        getResources().updateConfiguration(config, getResources().getDisplayMetrics());
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: return matching word in python I wrote a script that is checking if values in 'Product content' sheet (column 'TITLE') match with values from 'Keyword list' sheet, column 'KEYWORD' (the same workbook) . Compare_title function returns true or false which is ok but I also need to know which keywords are matching so not only true/false output but also the word that is considered as 'True match'.
The Python script is below.
import pandas as pd
import re

file_path ='C:/Users/User/Desktop/data.xlsx'

def get_keyword(file_path):
    """
    Get keywords that are active (based on value in column 'ACTIVE?') from 'KEYWORD' column
    from 'Hidden search' terms sheet and convert it into the list
    """
    df = pd.read_excel(file_path, sheet_name='Keyword list')
    keywords = df['KEYWORD'].to_list()

    return keywords

keyword_list = get_keyword(file_path)

def words(phrase: str) -> [str]:
    """
    Splits string to words by all characters that are not letters or digits (spaces, commas etc.)
    """

    return list(map(lambda x: x.lower(), filter(len, re.split(r'\W', phrase))))

def compare_title(file_path):
    """
    Get title from 'Product content' sheet and compare the values with keyword_list values
    """

    df = pd.read_excel(file_path, sheet_name='Product content')
    df = df.fillna('-')
    title = df['TITLE'].apply(lambda find_kw: any([keyword in words(find_kw) for keyword in keyword_list]))

    return title

Thanks in advance for your help.

A: I think this is what you're looking for:
title = df['TITLE'].apply(lambda find_kw: [keyword for keyword in keyword_list if keyword in words(find_kw)]))

This means compare_title will return list[str] instead of bool. If you do if compare_title(...) it still works as before because an empty list is falsy and a non-empty list is truthy.


text:
Q: structuring data in numpy for ltsm (examples) I am having problem with understanding how data should be prepared for different models:

*

*One to many

*Many to one

*Many to many(A)

*Many to many(B)

Is the right way to think o it this way. Shape numbers are no relevant and do not match the one on picture. I am just trying to understand logic behind.:
import numpy as np

#1. one to many
# X for input y for output

X = np.ones([10,1,5])
y = np.zeros([10,3]) #3 represnts size of output vector

#2. many to one

X = np.ones([10,5,5])
y = np.zeros([10,1])

#3. many to many

X = np.ones([10,5,5])
y = np.zeros([10,5])

# in this case cell should be different than y. It must be bigger to shift some data

#4. many to many

X = np.ones([10,5,5])
y = np.zeros([10,5])

# in this case cell is the same shape as y


text:
Q: How to stay on a loop while scraping a site with linked lists in python I am scraping a site where by there are links, these links have got children and their children spawn their own children. And the children also spawn their own children. I would want my code to stay on a loop. Scrape and then find the links in a, then store them on a list, follow up on the children, scrape the detailed information and then continue to the end. Then start on b and follow on the generations of children with their children. Then proceed to c doing the same thing. My question is how do I do something like that in python, whilst staying in a loop. If there is someone who has come accross a problem like this please may you help suggest how would you go about it ad what would be the best strategy. Below is a tree to draw a picture on these relations.
parents = [a, b, c]
a_children = [e, f, g]

    e_children =  [h, j, k]

        f_children = [l, m, n]

            g_children = [o, p, q]
                h_children = [r, s, t]

I would like to have this function to run on a loop to the end
def scrape_save_and_continue(driver, nodes):
    print('Scraping Saving & Continuing..')
    time.sleep(2)
    print('Continuing ...')

Thank you in advance

A: In python this is all about indentation.
If you take a for loop it will complete everything in this indentation before continuing to the next element in the list/range.
example_list = [a, b, c]
for letter in example_list:
    for _ in range(0, 2):
        print(letter)

because of indentation this will print:
a
a
b
b
c
c


text:
Q: gio - resolve path with symlinks I have a gfile which points to a path containing symlinks.
E.g. there are:
/home/test/link --> /home/original
/home/original/myfile.txt

The gfile points to  /home/test/link/myfile.txt. Does gio provide some method to resolve all links in this path, so that I can obtain /home/original/myfile.txt ?
Or do I need to implement that myself ?

A: Still not sure if gio possibly provides some shortcut ... meanwhile I implemented it myself using gio:
/**
 * g_file_get_resolved_path:
 * @file : #GFile for which the path will be resolved
 *
 * Gets the local pathname with resolved symlinks for GFile, if one exists.
 * If non-NULL, this is guaranteed to be an absolute, canonical path.
 *
 * This only will work if all components of the #GFile path actually do exist
 *
 * Return value: (nullable) (transfer full): A #gchar on success and %NULL on failure.
 * The returned string should be freed with g_free() when no longer needed.
 **/
char* g_file_get_resolved_path (GFile *file)
{
  gchar     *path;
  gchar    **tokenized_path;
  GFileInfo *info;
  gchar     *real_path = NULL;
  gchar     *folder_name;
  gchar     *temp_path;
  GFile     *link_test;
  gchar     *link_target = NULL;

  _thunar_return_val_if_fail (G_IS_FILE (file), NULL);

  path = g_file_get_path (file);

  /* No local path for file found */
  if (path == NULL)
    return NULL;

  tokenized_path = g_strsplit (path ,"/", -1);
  for (gsize i = 0; tokenized_path != NULL && tokenized_path[i] != NULL; ++i)
  {
    folder_name = tokenized_path[i];
    temp_path = g_strjoin ("/", real_path, folder_name, NULL);
    link_test = g_file_new_for_path (temp_path);
    g_free (temp_path);

    info = g_file_query_info (link_test, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET, G_FILE_QUERY_INFO_NOFOLLOW_SYMLINKS, NULL, NULL);
    if (info != NULL)
    {
      link_target = g_file_info_get_attribute_as_string (info, G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET);
      g_object_unref (info);
      if (link_target != NULL)
      {
        temp_path = real_path;
        if (link_target[0] == '/')
        {
          /* It's an absolute link */
          real_path = g_strdup (link_target);
        }
        else
        {
          /* It's a relative link */
          real_path = g_strjoin ("/", real_path, link_target, NULL);
        }
        g_free (temp_path);
      }
    }
    g_object_unref (link_test);

    /* no symlink found ? --> just append the folder name */
    if (link_target == NULL)
    {
      temp_path = real_path;
      real_path = g_strjoin ("/", real_path, folder_name, NULL);
      g_free (temp_path);
    }
    link_target = NULL;
  }
  g_strfreev (tokenized_path);

  g_free (path);
  return real_path;
}

Tested for some absolute and relative links.

A: Here a version which uses realpath, which might not be available on all systems:
g_file_get_resolved_path (GFile *file)
{
  gchar *path;
  gchar *real_path;

  _thunar_return_val_if_fail (G_IS_FILE (file), NULL);

  path = g_file_get_path (file);

  /* No local path for file found */
  if (path == NULL)
    return NULL;

  real_path = realpath (path, NULL);

  if (real_path == NULL)
    g_warning ("Failed to resolve path: '%s' Error: %s\n", path, strerror (errno));

  g_free (path);
  return real_path;
}


text:
Q: Firewall failure path ignored on second attempt With a firewall failure_path set, a user's first failed attempt at login follows the failure path. When the user clicks again on login, a Bad Credentials exception is thrown rather than allowing the user to try again.
firewall:
firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            failure_path:    /message/inactive

login menu link (using KnpMenuBundle)
if ('anon.' === $user) {
    $menu->addChild('Sign in', array(
        'route' => 'fos_user_security_login'
    ));
} else {
    $menu->addChild("Sign out", array(
        'route' => 'fos_user_security_logout',
    ));
}

Where else should I look?

A: This appears to be the answer: modify security.yml as below:
firewalls:
    main:
        pattern: ^/
        form_login:
            provider: fos_userbundle
            failure_path:    /message/inactive
            failure_forward: true


text:
Q: Strongly typed View: Model class not listed I am trying to create strongly typed view from model class N1Process. I did compile the solution, before attempting to add View. But can't locate this N1Process model in the add View wizard.

namespace GetPathOfRunningProcess.Models
{
    public class N1Process
    {
        public string Name { get; set; }
        public string Path { get; set; }
    }
}

Does it has to do anything with the namespace GetPathOfRunningProcess.Models where N1Process has been defined ?
Thanks !

A: You can type in the path in the wizard or just add
@model N1Process

to the top of your view file.
(You'll probably need the fully qualified name in the @model statement).

A: Build your Application and it show the models


text:
Q: How can convert data that I have stored as a string into a map I have one String stored in my DDBB, for example in my column data I have this String: "name=James castle&age=20" and I want, in my Services, converted to a map
I'm trying something like:
List <NameValuePair> parameters = myDomainInstance.data
if (org.externalDeliveryParameters){
    parameters = URLEncodedUtils.parse(org.externalDeliveryParameters,
                                       StandardCharsets.UTF_8)
}

I get this error:
Cannot cast object 'name=James castle&age=20' with class 'java.lang.String' to class 'java.util.List'

Somebody know how can i do it with List<NameValuePair> or another form?

A: I suspect you really wanted to write something like this
List <NameValuePair> parameters
if (myDomainInstance.data) {
   parameters = URLEncodedUtils.parse(myDomainInstance.data, StandardCharsets.UTF_8)
}

That's based on input and output params.

A: You can do that:
s = "name=James castle&age=20"

def map = s.split('&').inject([:]) {result, kv-> def (key, value) = kv.split('=').toList(); result[key] = value != null ? value : null; result }

If you're storing URLs in your database then you need to use the decordeURL() method provided by Grails, check below:
def map = s.split('&').inject([:]) {result, kv-> def (key, value) = kv.split('=').toList(); result[key] = value != null ? value.decodeURL() : null; result }

A: use simple regexp
def m = [:]
'name=James castle&age=20'.eachMatch( /([^&=]+)=([^&=]+)/ ){ m[ it[ 1 ] ] = it[ 2 ] }
assert m == [name:'James castle', age:'20']


text:
Q: Is Microsoft.AspNetCore no longer available? I was testing the Asp.NET Core authentication features. The project.json is copied from the GitHub exmaple. here

NU1001 The dependency Microsoft.AspNetCore.Server.Kestrel >= 1.0.0-* could not be resolved.

Other dependencies can be successfully resolved. And I also double checked my dnvm version.
The IntelliSense in Visual Studio also shows there is no Microsoft.AspNetCore... package in dependencies.
So if I want to add
app.UseOAuthAuthentication("Google-AccessToken", options =>...);

in Startup.cs, what is the correct dependency to use?

A: If you want to use the nightly builds, you need to add the nightly package repositories to do so.

*

*First you will need to use the latest rc2 nightly runtime dnvm upgrade -u latest. Beware, it will fail to restore packages really often!!

*You need to add the proper nuget feeds. The official nuget feed (https://www.nuget.org/api/v2) do not contain this packages, as they are nightly builds and pretty unstable. Official nuget feed only has rc1-final packages
From my experience these feeds worked well for rc2 for me

*

*Old (now deprecated) DNX runtime: https://www.myget.org/F/aspnetvnext/api/v3/index.json

*New dotnet-cli tooling: https://dotnet.myget.org/F/cli-deps/api/v3/index.json

*If you want to try out dotnet-cli you need to install it and follow the instructions in my previous answer on how to run ASP.NET MVC on dotnet-cli found here.
That being said, Microsoft.AspNetCore.Server.Kestrel uses the new naming scheme, which means it's RC2 since Microsoft.AspNet.* packages where renamed to Microsoft.AspNetCore.* some time during RC2 cycle.
If you need a stable base to play around, use rc1-final and it's versions, as they won't be updates at any time and your package restore won't fail multiple times a week due to upgrade to the runtime or packages.
The samples in the dev branch always target the nightly builds, that's some RC2 nightly build at the time of the writing. You either have use the sample in rc1-final branch or switch to rc2 nightly (runtime and packages) and wait for rc2 to be released (hopefully soon).
You can find the rc1-final version of project.json in the rc1-final tag or directly here.


text:
Q: Can I subclass UIMenuController so that it can take icons instead of just text? How would one go about doing this?  I'm looking for a dense, purely graphical menu on tap-hold.

A: In 3.2 you can add menu items using the menuItems property. But I think subclassing won't be useful, since it's a singleton that does not returns the views of each menu item. You could access menuFrame when setMenuVisible:animated: is called, so you can add you're own view that looks like a menu items with icons. But for adding icons to the system menu items... I think you should stick to what's Apple is giving you ;)

A: My low reputation don't let me post links, therefore I am answering again here:
Check Emoji & Symbols, perhaps it will fit to your purpose.
Go to your Xcode Menu -> Edit -> Emoji & Symbols.
Ex.:
let menuItemYes = UIMenuItem(title: "✅", action: "doSomething")

Good luck!

A: I wrote a category to support image for UIMenuItem. It's based on method swizzling, but should be safe in most cases.
https://github.com/cxa/CXAImageMenuItem
Note: duplicate answer to https://stackoverflow.com/a/14140904/395213
EDIT: the above link is 404'ed, this link works
https://github.com/cxa/UIMenuItem-CXAImageSupport


text:
Q: Calculate the value of the improper Riemann integral $H(s)=\int_0^{\infty} \frac{t^s}{1+t^2}dt$ for $0Given $0<s<1$ calculate the value of the improper Riemann integral $H(s)=\int_0^{\infty} \frac{t^s}{1+t^2}dt$.
I thought about using having a semi-circle contour, then use Residue's theorem.
But the problem is that $\frac{t^s}{1+t^2}$ may not be an even function. So we can't just divide it by 2 in the end.
I also know that $\int_0^{\infty}\frac{1}{1+t^2}dt = \frac{\pi}{2}$. I guess the problem here is to deal with $t^s$.
Any help will be appreciated!

A: Let $t^2=x$
$$H(s)=\frac{1}{2}\int_0^\infty \frac{x^{(s-1)/2}}{1+x}dx=\frac{1}{2}B\left(\frac{s+1}{2},\frac{1-s}2\right)=\frac{\pi}{2\sin(\frac{s+1}2\pi)}=\frac{\pi}{2\cos(\frac{s}2\pi)}$$


text:
Q: Problem related to background image in css django My background image is not shown on the website. The image is in static folder under /projectname/static/img and CSS is under /projectname/static/css/style.css. This is the css:
#showcase {
    background: url("../img/showcase.jpg") no-repeat top center fixed/cover;
}

In template under /projectname/template/pagesapp/index.html there is id of element (id= showcase) where i want to apply image. But the image isn't shown. I have checked every thing, collected static and collected static under projectanme/rentalrooms/static,settings.py where.  and static root on base (projectname/static)

#showcase {
  background: url("../img/showcase.jpg") no-repeat top center fixed/cover;
  position: relative;
  min-height: 650px;
  color: #fff;
  padding-top: 6rem; }
  #showcase .home-search {
    min-height: 400px;
    position: relative;
    border-radius: 5px; }
  #showcase .overlay {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    min-height: 400px;
    width: 100%;
    background: rgba(51, 51, 51, 0.8); }
{% extends 'base.html' %}

{% block title %} | Welcome {% endblock%}
{% load humanize %}

{% block content %}

                Rooms Searching Just Got So Easy

Stop Finding Rooms Manually Its Our Duty To Find Rooms According To Your Preference

                <form action="{% url 'search' %}">

                      Keywords
                      <input type="text" name="keywords" class="form-control" placeholder="Keyword (Search By Facility You Want)">

                      City
                      <input type="text" name="city" class="form-control" placeholder="City">

                      State
                      <select name="state" class="form-control">
                        <option selected="true" disabled="disabled">State (All)</option>
                        {% for key,value in state_choices.items %}
                          <option value="{{ key }}">{{ value }}</option>
                        {% endfor %}
                      </select>

                      Bedrooms
                      <select name="bedrooms" class="form-control">
                        <option selected="true" disabled="disabled">Bedrooms (All)</option>
                        {% for key,value in bedroom_choices.items %}
                          <option value="{{ key }}">{{ value }}</option>
                        {% endfor %}
                      </select>

                      <select name="price" class="form-control" id="type">
                        <option selected="true" disabled="disabled">Max Price (Any)</option>
                        {% for key,value in price_choices.items %}
                          <option value="{{ key }}">{{ value }}</option>
                        {% endfor %}
                      </select>

                  <button class="btn btn-secondary btn-block mt-4" type="submit">Submit form</button>
                </form>

      {% include 'partials/_alerts.html' %}

Latest Listings

            {% if listings %}
              {% for listing in listings %}

                          Rs.{{ listing.price | intcomma }}

{{ listing.title }}

                             {{ listing.city }}, {{ listing.state }},
                            {{ listing.zipcode }}

                             Security: {{ listing.security_fee }}

                             For: {% if  listing.parking %} Boys{% else %} Girls{% endif %}

                             Bedrooms: {{ listing.bedrooms }}

                             Bathrooms: {{ listing.bathrooms }}

                             {{listing.owner }}

                             {{listing.list_date | timesince }}

                        More Info

              {% endfor %}
            {% else %}

 No Listings Available

            {% endif %}

Consulting Services

Coming Soon

Blog

Coming Soon

Disclaimer

Coming Soon

{% endblock %}

{% load static %}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <link rel="stylesheet" href="{% static 'css/all.css'%}">

    <link rel="stylesheet" href="{% static 'css/bootstrap.css'%}">

    <link rel="stylesheet" href="{% static 'css/style.css'%}">

    <link rel="stylesheet" href="{% static 'css/lightbox.min.css'%}">

    <title>RentalRooms {% block title%}{% endblock%}</title>

    {% include 'partials/_topbar.html' %}

    {% include 'partials/_navbar.html' %}

    {% block content %} {% endblock %}

    {% include 'partials/_footer.html' %}


text:
Q: Regex for line without runs of non-alphanumeric characters I want to regex to match e.g. the below string:

Discover - CashBack Bonus & Citi TYP®

All of the non-alphanumeric characters like - , & and ® , cannot appear one after another.
Tried this: ^[A-Za-z0-9 ]+[-]*[A-Za-z0-9 ]+[&]*[A-Za-z0-9 ]+[®]*[A-Za-z0-9 ]+$

A:
Tried this: ^[A-Za-z0-9 ]+[-]*[A-Za-z0-9 ]+[&]*[A-Za-z0-9 ]+[®]*[A-Za-z0-9 ]+$

This didn't match because the trailing [A-Za-z0-9 ]+$ requires 1 character of [A-Za-z0-9 ] at the end of the line, while your string ends with ®.
To match a line without runs of non-alphanumeric characters except space, you can use the regex:
^.?([A-Za-z0-9 ]++.?)*$

This is essentially

*

*[A-Za-z0-9 ]++ - a run of alphanumeric characters or space, followed by

*.? - at most one extra character,

*(…)* - the above occuring any number of times.

The leading ^.? is there to allow for one extra character at the start of the string. And it's important to use the possessive quantifier ++ in order to avoid catastrophic backtracking.


text:
Q: Resource image files for VBA? I have a word doc that I have been writing some VBA for, and in it I use this a lot:
LoadPicture(ThisDocument.Path & "image_name")

However, for this to work I've needed users to have an "Images" folder in the same directory, which is very inconvenient.
Is there a better way to include resources in a VBA project?
Thanks!

A: I use the QuickParts in Word to store them.  Create a new document template, paste the image onto the page and select it.  Then go to QuickParts and Add it to the Library and save your template.  Repeat for each item to add.  Then use VBA code to apply the template to the document and your QuickPart will pull in from the template.  Then use a second macro to pull your image from the QuickPart.

A: Why not check if the folder exists on document open and create the folder if it does not?
Private Sub Document_Open()
    Dim imagesFolder As String

    imagesFolder = ThisDocument.Path & "\images\"
    If Len(Dir(imagesFolder, vbDirectory)) = 0 Then MkDir imagesFolder

End Sub


text: Q: Modifying the existing "project properties" window in Eclipse I am writing an Eclipse plugin for which I require need to take as input several parameters from the user. I am planning to add these parameter in already existing "Project Properties" window of Eclipse. Is there any way we can do this?


text:
Q: Xcode CoreFoundation/CFUserNotification.h' file not found I don't know why I get this, when I build a iPad project in xcode4.6.
iOS sdk 6.1, simulator 6.1.

/Applications/Xcode4.6.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:92:10: 'CoreFoundation/CFUserNotification.h' file not found
In file included from /Applications/Xcode4.6.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator6.1.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:5:10


text:
Q: ng-model display duplicate value Following are my code please take a look

var app = angular.module('myApp', []);

app.controller('displayData', function($scope){
     $scope.selected = {};

     $scope.formData = {};
        $scope.customproductoption = [
            {
                "id" : "1",
                "producttype" : "Shoe",
                "sizetype" : [
                    { "size" : "15" },
                    { "size" : "16" },
                    { "size" : "17" }
       ]
            },{
                "id" : "2",
                "producttype" : "Dress",
                "sizetype" : [
                 { "size" : "XS" },
                    { "size" : "S" },
                    { "size" : "L" }
                ]
            }
        ];
});

 <title></title>

<select ng-model="selected.producttype" ng-options="s.producttype for s in customproductoption">
       <option value="">-- Custom Product Option --</option>
    </select>

          Index
          Size
          Price
          Qty

         {{$index+1}}
          <input type="text" ng-model="formData.customsize" ng-init="formData.customsize=s.size" id="productsize" disabled>
           <input type="text" ng-model="formData.customproductprice" id="customprice" name="productprice">
          <input type="text" ng-model="formData.customproductqty" id="customqty" name="productqty">

In this code based on selected option, i show related result in related result users can fill product price and quantity, in ng-model used formData i can bind all filled value in one array but ng-model value display all duplicate value

A:

var app = angular.module('myApp', []);

app.controller('displayData', function($scope){
     $scope.selected = {};

     $scope.formData = {};
        $scope.customproductoption = [
            {
                "id" : "1",
                "producttype" : "Shoe",
                "sizetype" : [
                    { "size" : "15" },
                    { "size" : "16" },
                    { "size" : "17" }
       ]
            },{
                "id" : "2",
                "producttype" : "Dress",
                "sizetype" : [
                 { "size" : "XS" },
                    { "size" : "S" },
                    { "size" : "L" }
                ]
            }
        ];
});

 <title></title>

<select ng-model="selected.producttype" ng-options="s.producttype for s in customproductoption">
       <option value="">-- Custom Product Option --</option>
    </select>

          Index
          Size
          Price
          Qty

         {{$index+1}}
          <input type="text" ng-model="formData.customsize[$index]" ng-init="formData.customsize[$index]=s.size" id="productsize" disabled>
           <input type="text" ng-model="formData.customproductprice" id="customprice" name="productprice">
          <input type="text" ng-model="formData.customproductqty" id="customqty" name="productqty">

you'r replacing the formData.customsize value when repeating. so you have to assign different models


text:
Q: "No package pv available." on CentOS 6.2 Minimal I'm trying to install Pipe Viewer on a CentOS 6.2 minimal system.
When I run:
yum install pv

I get:
* base: mirror.thelinuxfix.com
* extras: mirror.atlanticmetro.net
* updates: ftp.usf.edu

No package pv available.
Error: Nothing to do

Do I need to add another repo? If so, which one and how do I add it?

A: The pv package is available from the RPMForge repository. Follow the instructions at that link to install it.
You could also download and install the package a la carte - See the RPM search engine, rpm.pbone.net:
Here's the pv package page.

A: You have to yum search epel, install it, then yum install pv.

A: Here is a working url (previous ones are no more):
http://mirror.airenetworks.es/epel/6/x86_64/Packages/p/pv-1.1.4-3.el6.x86_64.rpm
or
http://mirror.airenetworks.es/epel/7/x86_64/Packages/p/pv-1.4.6-1.el7.x86_64.rpm


text:
Q: Complex numbered function differentiation Let us think formally of $z$ and $z^*$ as independent variables for the plane, like $x$ and $y$. Then we have that
$$ \frac{\partial f}{\partial z*}= \frac{\partial f}{\partial(x-iy)}= \frac{\partial f}{\partial x}+i \frac{\partial f}{\partial y}. $$
Can you explain how to derive the above equation for complex numbered functions?

A: We have
$$ x = \frac{1}{2}(z+z^*), \quad y = \frac{1}{2i}(z-z^*), $$
so
$$ \frac{\partial f}{\partial z^*} = \frac{\partial x}{\partial z^*} \frac{\partial f}{\partial x} + \frac{\partial y}{\partial z^*} \frac{\partial f}{\partial y} = \frac{1}{2} \frac{\partial f}{\partial x} - \frac{1}{2i}\frac{\partial f}{\partial y} = \frac{1}{2} \left( \frac{\partial f}{\partial x} + i\frac{\partial f}{\partial y} \right) $$
(and in particular, the formula in the question is missing a factor of $1/2$).

A: (note: the formula in the OP is wrong)
Differentials tend to be better behaved, especially when multiple related variables are involved. The crucial equations are
$$ z = x + \mathbf{i} y\qquad \qquad  z^* = x - \mathbf{i} y$$
which differentiates to
$$ \mathrm{d}z = \mathrm{d} x + \mathbf{i} \mathrm{d} y
\qquad \qquad
\mathrm{d}z^* = \mathrm{d} x - \mathbf{i} \mathrm{d} y $$
which we can solve to get
$$ \mathrm{d}x = \frac{\mathrm{d}z + \mathrm{d}z^*}{2}
\qquad \qquad
\mathrm{d}y = \frac{\mathrm{d}z - \mathrm{d}z^*}{2 \mathbf{i}}
$$
which we can apply if we need to switch from the $\mathrm{d}x, \mathrm{d}y$ basis to the $\mathrm{d} z, \mathrm{d} z^*$ basis.

For partial derivatives, $\frac{\partial}{\partial z}$ and $\frac{\partial}{\partial z^*}$ is meant to be the dual basis to $\mathrm{d}z$ and $\mathrm{d}z^*$. That is, we specifically want to have
$$ \frac{\partial z}{\partial z} = 1
\qquad \qquad
\frac{\partial z}{\partial z^*} = 0
\\
\frac{\partial z^*}{\partial z} = 0
\qquad \qquad
\frac{\partial z^*}{\partial z^*} = 1
$$
Similarly, $\frac{\partial}{\partial x}$ and $\frac{\partial}{\partial y}$ are the dual basis to $\mathrm{d}x$ and $\mathrm{d}y$, so that we have
$$ \frac{\partial x}{\partial x} = 1
\qquad \qquad
\frac{\partial x}{\partial y} = 0
\\
\frac{\partial y}{\partial x} = 0
\qquad \qquad
\frac{\partial y}{\partial y} = 1
$$
By whatever method you like, we arrive at the equations
$$ \frac{\partial x}{\partial z} = \frac{1}{2}
\qquad  \frac{\partial x}{\partial z^*} = \frac{1}{2}
\\
 \frac{\partial y}{\partial z} = \frac{1}{2\mathbf{i}}
\qquad  \frac{\partial y}{\partial z^*} = -\frac{1}{2\mathbf{i}}
$$
or alternatively,
$$ \frac{\partial z}{\partial x} = 1
\qquad  \frac{\partial z}{\partial y} = \mathbf{i}
\\
 \frac{\partial z^*}{\partial x} = 1
\qquad  \frac{\partial z^*}{\partial y} = -\mathbf{i}
$$
And we can do linear algebra to express $\frac{\partial}{\partial z}$ and $\frac{\partial}{\partial z^*}$ in terms of $\frac{\partial}{\partial x}$ and $\frac{\partial}{\partial y}$ and vice versa. The end result will be
$$ \frac{\partial}{\partial z} = \frac{1}{2} \frac{\partial}{\partial x} + \frac{1}{2 \mathbf{i}} \frac{\partial}{\partial y}
\qquad \qquad \frac{\partial}{\partial z^*} = \frac{1}{2} \frac{\partial}{\partial x} - \frac{1}{2 \mathbf{i}} \frac{\partial}{\partial y}
\\
\frac{\partial}{\partial x} = \frac{\partial}{\partial z} +  \frac{\partial}{\partial z^*}
\qquad \qquad
\frac{\partial}{\partial x} = \mathbf{i} \frac{\partial}{\partial z} - \mathbf{i} \frac{\partial}{\partial z^*}
$$
we can verify, for example, the formula for $\frac{\partial}{\partial z}$ by applying both sides to, for example, both $z$ and to $z^*$:
$$  \frac{\partial z}{\partial z} = 1
\qquad \qquad \frac{1}{2} \frac{\partial z}{\partial x} + \frac{1}{2 \mathbf{i}} \frac{\partial z}{\partial y}
= \frac{1}{2} + \frac{1}{2} = 1$$
$$ \frac{\partial z^*}{\partial z} =0
\qquad \qquad \frac{1}{2} \frac{\partial z^*}{\partial x} + \frac{1}{2 \mathbf{i}} \frac{\partial z^*}{\partial y}
= \frac{1}{2} - \frac{1}{2} = 0$$


text:
Q: How to create attribute in magento How can we create an attribute for product programatically in magento CE 1.9? I have been trying out multiple ways for creating an attribute for product that has a boolean value by default set to false and assigned to Default attribute set, but not visible/editable by any admin panel user.
my Model/Resource/Eav/Mysql4/Setup.php
    <?php

class Mofosys_Quickbuy_Model_Resource_Eav_Mysql4_Setup extends Mage_Eav_Model_Entity_Setup {
protected function _prepareValues($attr) {
    $data = parent::_prepareValues($attr);
    $data = array_merge($data, array(

        'apply_to'                      => $this->_getValue($attr, 'apply_to'),
        'frontend_input_renderer'       => $this->_getValue($attr, 'input_renderer'),
        'is_comparable'                 => $this->_getValue($attr, 'comparable', 0),
        'is_configurable'               => $this->_getValue($attr, 'is_configurable', 0),
        'is_filterable'                 => $this->_getValue($attr, 'filterable', 0),
        'is_filterable_in_search'       => $this->_getValue($attr, 'filterable_in_search', 0),
        'is_global'                     => $this->_getValue(
            $attr,
            'global',
            Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL
            ),
        'is_html_allowed_on_front'      => $this->_getValue($attr, 'is_html_allowed_on_front', 0),
        'is_searchable'                 => $this->_getValue($attr, 'searchable', 0),
        'is_used_for_promo_rules'       => $this->_getValue($attr, 'used_for_promo_rules', 0),
        'is_visible'                    => $this->_getValue($attr, 'visible', 0),
        'is_visible_on_front'           => $this->_getValue($attr, 'visible_on_front', 0),
        'is_wysiwyg_enabled'            => $this->_getValue($attr, 'wysiwyg_enabled', 0),
        'is_visible_in_advanced_search' => $this->_getValue($attr, 'visible_in_advanced_search', 0),
        'position'                      => $this->_getValue($attr, 'position', 0),
        'used_for_sort_by'              => $this->_getValue($attr, 'used_for_sort_by', 0),
        'used_in_product_listing'       => $this->_getValue($attr, 'used_in_product_listing', 0),
        ));
    return $data;
}
}

?>

my etc/config.xml
    <global>
        <resources>
            <mofosys_quickbuy_setup>
                <setup>
                    <module>Mofosys_Quickbuy</module>
                <class>Mofosys_Quickbuy_Model_Resource_Eav_Mysql4_Setup</class>
                </setup>
            </mofosys_quickbuy_setup>
        </resources>
    </global>

my sql/mofosys_quickbuy_setup/install-0.0.1.php
    <?php
// Installer file to create an attribute name "approved" inside Default attribute set
$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

// the attribute added will be displayed under the group/tab Special Attributes in product edit page
$setup->addAttribute('catalog_product', 'approved', array(
    'group'                         =>          'Default',
    'input'                         =>          'select',
    'type'                          =>          'int',
    'default'                       =>          '0',
    'label'                         =>          'Testing',
    'backend'                       =>          '',
    'visible'                       =>          0,
    'required'                      =>          0,
    'user_defined'                  =>          0,
    'searchable'                    =>          0,
    'filterable'                    =>          0,
    'comparable'                    =>          0,
    'visible_on_front'              =>          0,
    'visible_in_advanced_search'    =>          0,
    'is_html_allowed_on_front'      =>          0,
    'global'                        =>          Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
));

$installer->endSetup();

?>

A: Try this, it should work, it just worked fine for me, just put this code in your install.php
$installer = $this;
$installer->startSetup();
// Set data:
$attributeName  = 'Approve'; // Name of the attribute
$attributeCode  = 'approve'; // Code of the attribute
$attributeGroup = 'General';          // Group to add the attribute to
$attributeSetIds = array(4);          // Array with attribute set ID's to add this attribute to. (ID:4 is the Default Attribute Set)

// Configuration:
$data = array(
    'type'      => 'select',       // Attribute type
    'input'     => 'boolean',          // Input type
    'global'    =>  Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,    // Attribute scope
    'required'  => false,           // Is this attribute required?
    'user_defined' => false,
    'searchable' => false,
    'filterable' => false,
    'comparable' => false,
    'visible_on_front' => false,
    'unique' => false,
    'used_in_product_listing' => true,
    'default_value_yesno' => '0',
    // Filled from above:
    'label' => $attributeName
);

// Create attribute:
// We create a new installer class here so we can also use this snippet in a non-EAV setup script.
$installer = Mage::getResourceModel('catalog/setup', 'catalog_setup');

$installer->addAttribute('catalog_product', $attributeCode, $data);

// Add the attribute to the proper sets/groups:
foreach($attributeSetIds as $attributeSetId)
{
    $installer->addAttributeToGroup('catalog_product', $attributeSetId, $attributeGroup, $attributeCode);
}

$installer->endSetup();


text:
Q: Locally finite - equivalent (?) definition A collection $(U_i)_i$ of open subsets of a topological space $X$ is called locally finite if every point $x \in X$ has a neighborhood $V_x$ that intersects only finitely many of the $U_i$'s. Clearly this implies that $x$ itself only lies in finitely many $U_i$'s, but the converse is not true in general, I think. Is there a good counterexample? And are there assumptions on $X$ under which the converse holds, i.e., local finiteness can be checked on points themselves, instead of on neighborhoods of points?

A: Let our collection consist of open intervals $(-1,1)$ and $\left(\dfrac1{n+1},\dfrac1n\right)$ for all $n\in\mathbb N$. Then clearly any point belongs to finitely many $U_i$, but good luck finding an open neighborhood of $0$ that intersects finitely many of them.

A: To answer the second part of your question: And are there assumptions on X under which the converse holds, i.e., local finiteness can be checked on points themselves, instead of on neighborhoods of points?
Well, there is at least one such assumption, though it is trivial and therefore not much interesting. But if $X$ has the discrete topology, i.e. every point (more precisely every singleton) is open, then every point-finite collection is locally-finite.
Here is an example of a point-finite collection of intervals in the real line that is not locally-finite at $0$. Consider $\{(0,\frac1n):n=1,2,3,...\}$.
If $X$ is Hausdorff and $x$ is a non-isolated point, then one could find non-empty open sets $U_n$ and $V_n$ such that $x\in(U_{n+1}\cup V_{n+1})\subset U_n$ and $U_n\cap V_n=\varnothing$. Then $\{V_n:n=1,2,...\}$ is a disjoint open family, and $x\notin\cup\{V_n:n=1,2,...\}$. If necessary, we may add more open sets (continue transfinitely), none containing $x$, to obtain an infinite disjoint family $\mathcal V$ such that $x\in\overline{\cup\mathcal V}$, yet $x\notin\overline{V}$ for any $V\in\mathcal V$. Then $\mathcal V$ is point-finite, but it is not locally-finite at $x$.


text:
Q: Multiple row in one row table Does anyone know how can I have two rows on one column but only a single cell
---------------------
      | x    |      |
    Z |------| A    |
      | y    |      |
------------- -------

My table in PHP looks like this
Trans Table
Transaction ID - 1
Transactiion date - Feb 7
Transdetails Table
Details ID - 1
Transaction ID - 1
Medicine - 1
Details ID - 2
Transaction ID - 1
Medicine - 2
I need to show both medicine on one Transaction ID in one row

A: With  you can achive that layout with a HTML Table.

    z
    x
    a

    y


text:
Q: Listpicker Selected Item change on generate page (c#) I have a page with generate many element like textblock, listpicker, etc. base on JSON response with C#, not in XAML. so, it is very dynamic page. example (just for Listpicker):
public partial class MainPage : PhoneApplicationPage
{
     public MainPage()
     {
         InitializeComponent();
     }

     protected override void OnNavigatedTo(NavigationEventArgs e)
     {
          Generate();
     }

     void Generate()
     {
          stack.Children.Clear(); // in XAML, I just put stackpanel

          //in example I have array of string
           string[] test = {"a","b","c","d","e","f"};

           ListPicker list = new ListPicker();

           for (int i = 0; i < test.Count(); i++)
           {
                list.Items.Add(test[i]);
           }
           //I want to keep in fullmode
           list.ExpansionMode = ExpansionMode.FullScreenOnly;
           sp.Children.Add(list);
     }

the problem is, when I select the List item in full mode, the Listpicker selected item not change.
In case ListPicker SelectedIndex Not Shown Correctly in WP7
I realized my problem is on OnNavigatedTo, but I cannot find solution for Listpicker which  created on cs, not XAML first.
Can someone help me?


text:
Q: How to interpret NA in GARCH std. errors and $t$-statistics in R? I'm trying to apply GARCH model to the RedHat market data using R.
When I use the garchFit function from the fGarch library I get the following results:
> garchFit(~garch(10,0),data=RedHatLogRet,trace=F)

Title:
 GARCH Modelling

Call:
 garchFit(formula = ~garch(10, 0), data = RedHatLogRet, trace = F)

Mean and Variance Equation:
 data ~ garch(10, 0)

Conditional Distribution:
 norm

Coefficient(s):
        mu       omega      alpha1      alpha2      alpha3      alpha4      alpha5
0.00098990  0.00024533  0.10983739  0.14223797  0.05749616  0.00155498  0.00000001
    alpha6      alpha7      alpha8      alpha9     alpha10
0.08477199  0.00060140  0.04391016  0.05989966  0.03876993

Std. Errors:
 based on Hessian

Error Analysis:
         Estimate  Std. Error  t value Pr(>|t|)
mu      9.899e-04   3.860e-04    2.565 0.010329 *
omega   2.453e-04   1.455e-05   16.864  < 2e-16 ***
alpha1  1.098e-01   2.881e-02    3.813 0.000137 ***
alpha2  1.422e-01   4.356e-02    3.266 0.001093 **
alpha3  5.750e-02   3.269e-02    1.759 0.078587 .
alpha4  1.555e-03   2.386e-02    0.065 0.948045
alpha5  1.000e-08          NA       NA       NA
alpha6  8.477e-02   3.121e-02    2.717 0.006596 **
alpha7  6.014e-04   7.643e-03    0.079 0.937281
alpha8  4.391e-02   3.107e-02    1.413 0.157608
alpha9  5.990e-02   2.438e-02    2.457 0.014010 *
alpha10 3.877e-02   2.697e-02    1.437 0.150598
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Log Likelihood:
 6613.981    normalized:  2.438784

As you can see model seems to be appropriate but I'm confused with alpha5's NA stats. How to interpret these results?
For more information, here are the squared residuals' ACF and PACF plots based on an ARMA model: ACF plot of squared residuals, PACF plot of squared residuals.


text:
Q: Q: Passwordless auth on Rails Is there a way to setup auth without password where user receives one-time password on every login.
Only auth option for Rails that I know of is Devise but it doesn't seem to support "passwordless" auth.
Are there any other options and am I missing something about devise not supporting it?

A: You could consider requiring your user to have a Fido U2F compliant device.
They need to plug it in on register. and on login. It is more commonly used as 2nd factor authentication. but I can imagine people who might want to use it as a single authentication method. The protocol is web_authn and there is a gem for it in ruby.
https://github.com/cedarcode/webauthn-ruby
you can test at https://webauthn.io/
you could also consider the more common OTP Authenticator app.
Have people scan your QR Core on signup, and that would become the only auth required.
is this what you are asking? Single method of authentication, without a saved password.
sent everything by email or SMS seems annoying
but that is also possible.


text:
Q: SQL Server 2008 R2 restore error When I restore database backup in SQL Server 2008 R2 , I get this error message .

How can I solve it ?

A: Your backup comes from a SQL Server 2008 R2 (v10.50.1600) installation, and you're trying to restore to SQL Server 2008 (v10.00.1600).
This is NOT SUPPORTED and cannot be done. If you have a backup from SQL Server 2008 R2, you need to restore to 2008 R2 (or newer) - you cannot go back in time.

A: Versions between production and your destination are different. I think you can't solve this easy, maybe to try to make scripts for creating database and objects, and to use SQL Import/Export tool to transfer data from source to destination.
Also, you can go to production database, right click on it, and choose Generate scripts option to create whole database with entire structure. Even, you can use this tool for export data and, later, import them, but for large amount of data, this step work unpredictable.


text:
Q: What is a simple algorithm / approach to store key-value (number-number) pairs *in disk* for quick access by key? I need to store many Long-Long pairs in disk, not in memory, for example:
(123, 2)
(1253, 3)
(12345, 6)
...

So later I can easily do:
long value = get(123); // => 2

Is there a simple approach to do that? I am hoping it does not need to be as complicated as a hashtable in disk.
To make it clear, the pairs will NOT be stored in memory, they will be written straight to a file or set of files in disk.

A: There are multiple key/value stores available. A quite comprehensive list can be found here.
One good alternative is to use MapDB which is a fast and easy-to-use NoSQL database which supports disk storage and transactions.
To use it, simply follow the instructions in the cheat sheet:
File file = new File("dbFileName");
DB db = DBMaker.newFileDB(file).make();

//use map
Map map = db.getHashMap("mapName");
map.put("aa","bb");

//commit and close database
db.commit();
db.close();

Plus, it obviously works for Long values as well!

A: You can still use a hashtable (best way to store key/value pairs), you just have to serialize it.
You can access your serialized files and read those in. For example, after reserialization (assuming hashmap style): Long x = Long.parseLong(y.get("123"));

A: Unless this is a CS homework, I would simply use a Redis persistent instance.
http://www.redis.io


text:
Q: Deformation of Gamma function integral contour Terence Tao has described the gamma function as the inner product of a multiplicative and an additive character with respect to the Haar measure on $\Bbb R^+$. The gamma function is defined as follows:
$\Gamma(\omega) = \int_0^\infty \frac{x^{\omega}}{e^x} \frac{\text{d}x}{x}$
The functions $x^\omega$ and $e^x$ map from $\Bbb R^+$ to $\Bbb R^+$, hence they can be thought of as non-unitary characters.
More interesting to me is to replace them with the unitary characters $x^{i \omega}$ and $e^{ix}$, which map from $\Bbb R^+$ to $\Bbb C^\times$. That would yield the integral
$\int_0^\infty \frac{x^{i \omega}}{e^{ix}} \frac{\text{d}x}{x}$
I don't think the integral converges, but it seems likely to me that there is some method that can make something of it.
I am wondering if this integral is related to the ordinary Gamma function interval, or if it can be expressed in terms of the Gamma function, if contour deformation can be used to relate the two in some sense, etc.


text:
Q: How can I generate (suitably random) symplectic matrices? I would like to write a computer script to generate a lot of symplectic matrices.  How can I do this?  Is there a parameterization of all symplectic matrices?

A: This article is about generating random matrices it includes symplectic matrices
http://www-stat.stanford.edu/~cgates/PERSI/papers/what-is.pdf

A: Also check out http://www.ams.org/notices/200705/fea-mezzadri-web.pdf

A: Choose a subgroup that is easy to generate, say $Sp(2)$, and pick a random pair of coordinates $i < j$ and a random element in $Sp(2)$ spanning the subspace spanned by those two coordinates. This gives a markov chain analogous to the Kac random walk. It is known that this procedure converges. In fact if it measures the convergence rate in the transportation distance, then the rate is $n^2 \log n$.

A: Pick a random element of the Lie algebra of the symplectic group (this you can find explicitly described in Fulton and Harris), and exponentiate it.


text:
Q: Plugin Location Accuracy Ionic 2 Estou utilizando uma API Location Accurancy Ionic v2 segue o código:
cordova.plugins.locationAccuracy.canRequest(function(canRequest){
    if(canRequest){
        cordova.plugins.locationAccuracy.request(function (success){
            console.log("Successfully requested accuracy: "+success.message);
        }, function (error){
           console.error("Accuracy request failed: error code="+error.code+"; error message="+error.message);
           if(error.code !== cordova.plugins.locationAccuracy.ERROR_USER_DISAGREED){
               if(window.confirm("Failed to automatically set Location Mode to 'High Accuracy'. Would you like to switch to the Location Settings page and do this manually?")){
                   cordova.plugins.diagnostic.switchToLocationSettings();
               }
           }
        }, cordova.plugins.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY);
    }
});

A função "canRequest" sempre retorna false e não faz a solicitação para poder ativar.

A: Segundo a documentação do plugin , sobre o método canRequest:

On Android, this will return true if the app has authorization to use
  location.

Então podemos supor que o método sempre vai retornar false se o seu app não tiver permissão pra localizar o usuário. Verifique se você está pedindo essa permissão, geralmente isso é feito em algum arquivo de configuração.


text:
Q: How to change other items in a Android ListView when one item is show How to change other items in a Android ListView when one item is show?
I want to change something, if the item appears on the screen in the listview


text:
Q: How to nest dependent Jenkins Pipelines to execute on a single machine? We are implementing Continuous Integration of several repositories using Jenkins.
For this example, let's assume libA is a dependency of libB which is a dependency of clientC.
libA pipeline
libA has external dependencies, so we can write the pipeline build-A-pipe to build it : one of the stages being responsible for gathering such dependencies, and a subsequent stage actually invoking the build command.
libB pipeline
libB would ideally be built within a separate pipeline, called build-B-pipe. In the stage to gather libB dependencies, we have to build libA. It seems to us that the best way to achieve such thing is to call build job: 'build-A-pipe' within the pipeline that builds libB (this way it allows to reuse the build-A-pipe, which already describes all steps required to successfully build libA).
clientC pipeline
Now, if we wanted to build clientC, we would follow a similar procedure. Thus, there would be a call like build job: 'build-B-pipe' in the dependencies gathering stage of the pipeline building clientC. The issue is that it results in nested calls to the build command, which deadlocks the single machine :

*

*at the top level calling build job: 'build-B-pipe' schedules build-B-pipe, and starts it on the master machine (our only "execution node").

*build-B-pipe then calls build job: 'build-A-pipe', which is then scheduled but cannot start, as the only "execution node" is already taken.

How should we approach this problem to make this inherently sequential build work within Jenkins ?

A:
The issue is that it results in nested calls to the build command, which deadlocks the single machine

By deadlock, do you mean that the slave agent which is responsible for executing the nested pipeline is running out of resources? Or is the node which is responsible for running these nested pipelines running out of executors?
If the machine responsible for running pipelines is exhausting all resources (assuming that this is the only responsibility of this machine), then your pipeline is too complex and should delegate more to other nodes/agents.
If the node is running out of executors, you can increase those in the node config.


text:
Q: Swift 5 Ubuntu 16.04 Crash with dateComponents Here's my code:
import Foundation

if let utc = TimeZone(abbreviation: "UTC") {
    let calendar = Calendar.current
    print("\(calendar.description)")
    print("Before dateComponents")
    let componentsDate1 = calendar.dateComponents(in: utc, from: Date())
    print("\(componentsDate1)")
}
else {
    print("Could not create timezone")
}

I'm running on Ubuntu 16.04 under Docker. The result is:
gregorian (current)
Before dateComponents
Segmentation fault

It appears the dateComponents call is crashing.
My Docker container is based off
https://github.com/apple/swift-docker/blob/0aafffef619fb3b1824c968cbbe2fba4ba41bd26/5.0/ubuntu/16.04/Dockerfile
Suggestions?

UPDATES
1) I just replicated this on a Ubuntu 16.04 system running under Virtual box with an install of the Swift 5.0.1 release for Ubuntu 16.04: https://swift.org/builds/swift-5.0.1-release/ubuntu1604/swift-5.0.1-RELEASE/swift-5.0.1-RELEASE-ubuntu16.04.tar.gz

A: I was just informed this is indeed a known bug with a known current fix:
https://forums.swift.org/t/possible-bug-in-datecomponents-method-running-on-ubuntu-16-04/25702


text:
Q: Flexbox column align items same width but centered without wrapper (css-only)
This is for a mobile menu, which of course needs to be responsive.
The longest child should set the width for all the other children
.index needs to be full width and height with a background-color.
CSS only, please
I want to solve this issue without an extra wrapper.

My code:

.index {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column; /* main-axis vertical */
  justify-content: center; /* main-axis alignment */
  align-items: center; /* neither center nor stretch produce desired result */
}
.index a {
  /* nothing important here */
}

  Some item
  Some other item
  This one long item
  Overview
  Contact

What I tried so far:

*

*percentaged padding on either the parent (.index) or the children (a) never got the whole package centered perfectly

*played around with max-width on the items, but ...

I want to solve this issue without an extra wrapper.
There are so many things I found out about native flexbox behaviour in the last months that I wonder and wish so much it can handle this use case as well.

A: Why not just remove the flex option:

body,
html {
  height: 100%;
  padding: 0;
  margin: 0;
}
.index {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: inline-block;
}
.index > a {
  display: block;
}
.index:after {
  left:50%;
  top:50%;
  content: '';
  display: block;
  position: fixed;
  width:100vw;
  height:100vh;
  transform: translate(-50%, -50%);
  z-index: -1;
  background: #525252;
}

  Some item
  Some other item
  This one long item
  Overview
  Contact

A: Try below HTML or CSS code:

.index {
    background-color: #525252;
    position: fixed; top: 0; left: 0;
    width: 100%; height: 100%;

    display: flex; flex-direction: column; // main-axis vertical
    justify-content: center; // main-axis alignment
    align-items: center; // neither center nor stretch produce desired result

    a {
        ... // nothing important here
    }
}
.index ul {
  background-color: #5c7343;
  color: #b0c696;
  float: none;
  list-style-type: square;
  margin: auto;
  padding: 0 5px 0 15px;
}
.index ul li {
  padding: 3px 0;
}
.index ul li a {
  color: #b0c696;
  text-decoration: none;
  width: 100%;
}

Some item

Some other item

This one long item

Overview

Contact


text:
Q: Adding various number of dots in excel I have a lot of excel files looking like that:
Example:

My goal is to make it look like that:

To do that, I used very simple excel's function:
=F7&" "&G7&".........cat."&" "&H7&" times "&I7&CHAR(10)&F8&" "&G8&".........cat."&" "&H8&" times "&I8&CHAR(10)
The thing is, the number of dots placed before "cat" is not constant. It depends where the previous sentence ends and my formula doesn't take it into account - it always adds 9 dots, which means I have to add the rest of the dots manually.
Any ideas how to make it work? :D

A: The REPT function can do this. Use LEN to calculate the length of what you're adding the dots to, then subtract that from the desired width of the result. That will repeat the dot enough times to fill the column. For example, if you want the text with dots to be 40 characters, right padded with .:
=F1&" "&G1&REPT(".",40-LEN(G1))&"cat."&" "&H1&" times "&I1&CHAR(10)&F2&""

A: =LEFT(A1 & REPT(".",22-LEN(A1))&"cat",25)

22 = fixed width - len("cat"), 25 - fixed width.
edit - i revised because my original answer was not correct but I see Comintern has posted a similar response since.


text:
Q: PHP static Property Misbehaving in child classes I am trying to learn Object Oriented PHP and for this I tried to make login/logout system. The problem I am stuck in, is as given below:
Scenario: DB_CONNECT is Parent class and has static property array also Parent class has two child classes i.e. crud.php and user.php. crud.php adds data to parent's static array (see function login() in crud.php for more clarification) while user.php accesses/retrieves the data from that static array.
Issue: Child_2 gets empty array (since it is static array).
Note1: I have verified that data is being added by child_1. When accessed the static property via child_1 it shows data but empty via chiild_2!
Note2:parent class is DB_CONNECT child_1 class is crud.php and child_2 class is user.php
DB_CONNECT.php    (parent class)
class DB_CONNECT
{
    /**
    * Stores a database object
    *
    * @var object A database object
    */
    protected $dbc;
    public static $user_name  ;
    public static $fname  ;
    public static $lname  ;
    public static $email  ;
    public static $psword ;
    public static $user_details = array();
    /**
    * Checks for a DB object or creates one if one isn't found
    *
    * @param object $db A database object
    */
    protected function __construct($db=NULL)
    {

        if ( is_object($db) )
        {
            $this->dbc = $db;
            echo 'Connected to DB by child constructor object';
        }
        else
        {
        // Constants are defined in /sys/config/db-cred.inc.php
            $dsn = "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME;
            try
            {
                $this->dbc = new PDO($dsn, DB_USER, DB_PASS);
                // echo 'Connected to DB via parent';

            }
            catch ( Exception $e )
            {
            // If the DB connection fails, output the error
                // die ( $e->getMessage() );
                printf("Connection Failed: %s", $e->getMessage());
            }
        }
    }

    public function getParentDetails()
    {
        echo DB_CONNECT::$user_details[0];
    }

}

crud.php  (child class)
class CRUD extends DB_CONNECT
{
    // inherits protected $dbc;
    function __construct($dbo=null)
    {
        parent::__construct($dbo);
    }

    public function login()
    {
        $result = '';
        self::$user_details[] = $_POST['fname'];
        self::$user_details[] = $_POST['pwd'];

        if (!empty($_SERVER)) {

            $select = "SELECT first_name, password FROM member_credentials
                    WHERE first_name = '$_POST[fname]' AND
                    password = '$_POST[pwd]'";
            $stmt = $this->dbc->prepare($select);
            $stmt->execute();

            $result = $stmt->fetch(PDO::FETCH_NUM);
           // var_dump($result);
            if (!is_array($result)) {
                Redirect::to(404);
            } else {
                DB_CONNECT::$user_name = $result[0];

                // session_start();
                Session::set('admin', DB_CONNECT::$user_name);
                Redirect::to('../admin.php');
            }

        }

    }

}

user.php  (child class)
class User extends DB_CONNECT
{

    // inherits protected $dbc;
    function __construct($dbo=null)
    {
        parent::__construct($dbo);
    }

    public function getUserName($name=null)
    {
        return DB_CONNECT::$user_name;
    }

    public function getUserDetails()
    {
        echo DB_CONNECT::$user_details[0];
    }

}

index.php (instantiating class objects)
$user = new User();

$user->getUserDetails();


text:
Q: Wrapping a C function call taking char** [in/out], to return a python list in cython How do you wrap a C function call that expects a pre-allocated char** as an argument to store the result? I am trying to return a python list result.
I have found examples of the other way around, and also this ctypes example, but I am not entirely sure ctypes is the appropriate approach in cython.
For reference, I am practicing wrapping the openni library:
http://openni.org/Documentation/Reference/classxn_1_1_pose_detection_capability.html
The original C signature I am wrapping is (its actually a C++ method that just wraps around a C function internally):
/**
 * @brief Gets the names of all poses supported by this capability.

 * @param [out]     pstrPoses   Pre-allocated memory for the names of the supported poses.
 * @param [in,out]  nPoses      In input - size of the preallocated memory, in output
 *                              - the number of pose names.
 */

XnStatus GetAvailablePoses(XnChar** pstrPoses, XnUInt32& nPoses) const

(XnChar is just a typedef for char)
Here is my attempt so far, which crashes:
from libc.stdlib cimport malloc, free

def get_available_poses(self):
    cdef:
        int i
        bytes name
        XnStatus stat
        XnUInt32 size = self.handle.GetNumberOfPoses()
        XnChar **buf = <XnChar**>malloc(size * sizeof(XnChar*))

    if not buf:
        raise MemoryError()

    try:
        # this crashes: Segmentation fault
        stat = self.handle.GetAvailablePoses(buf, size)

        # if I could get to here, I would want to
        # build a list to return (not saying this is
            # even correct either)
        for i in range(size):
            name = <char*>(buf[i])
            ...

    finally:
        free(buf)

That version of the C function is technically deprecated, but the newer one looks even scarier to me:
/**
 * Gets the names of all poses supported by this capability.

 * @param [out]     pstrPoses       Pre-allocated memory for the names of the supported poses.
 * @param [in]      nNameLength     Memory size for each pose name.
 * @param [in,out]  nPoses          In input - size of the preallocated memory, in output
 *                                  - the number of pose names.
 */

 XnStatus GetAllAvailablePoses(XnChar** pstrPoses, XnUInt32 nNameLength,
                                XnUInt32& nPoses) const;

Ideally if I could figure out how to pass in a proper char** and produce a list, I would use the newer one that also requires me to specify the length of the names that was allocated.
Update:
I simplified this problem down to just the basics to make sure I am doing this right in the first place:
src:
//chars.h

void setChars(char** str_array, int size);

//chars.cc

#include "chars.h"

void setChars(char** str_array, int size) {
    for (int i = 0; i < size; i++) {
        char *s = "FOO";
        str_array[i] = s;
    }
}

cython:
#chars.pxd

cdef extern from "chars.h":
    void setChars(char**, int)

#chars.pyx

from libc.stdlib cimport malloc, free

def py_setChars():
    cdef:
        bytes s
        int i
        int size = 6
        char** buf = <char**>malloc(size * sizeof(char*))

    if not buf:
        raise MemoryError()

    out = []

    try:
        setChars(buf, size)

        for i in range(size):
            s = buf[i]
            out.append(s)

    finally:
        free(buf)

    return out

And it works as expected:
In [1]: import chars
In [2]: chars.py_setChars()
Out[2]: ['FOO', 'FOO', 'FOO', 'FOO', 'FOO', 'FOO']

I am guessing the GetAllAvailablePoses() call I want to use is expecting some kind of pre-allocated memory that I am not doing right, hence the param asking for the size of each char.

A: I finally figured this out with enough playing. GetAllAvailablePoses really does expect you to preallocate the space of each char* and tell it how big that space is for it to populate:
# foo.pxd

XnStatus GetAllAvailablePoses(XnChar **, XnUInt32, XnUInt32&)

# foo.pyx

def get_available_poses(self):
    cdef:
        int i
        bytes name
        XnStatus stat
        XnUInt32 nameLength = 256
        XnUInt32 size = self.handle.GetNumberOfPoses()

    cdef XnChar **buf = <XnChar**>malloc(size * sizeof(XnChar*))

    if not buf:
        raise MemoryError()

    for i in range(size):
        buf[i] = <XnChar*>malloc(nameLength)

    out = [None]*size

    try:
        stat = self.handle.GetAllAvailablePoses(buf, nameLength, size)

        for i in range(size):
            name = <char*>buf[i]
            out[i] = name

    finally:
        free(buf)

    return out

# Out: ['Psi', 'CrossHandsPose', 'Wave', 'Click', 'RaiseHand', 'MovingHand']


text:
Q: Casting class into a struct I have this :
class masterStruct {

public:

int counter;
bool synchronized;
std::string slaveIDs[3];

void test() { counter = 0; }

}

It's defined in my class like this:
class MasterInterface {

public:
  struct masterStruct masStruct;

}

And I use masStruct in C-style callback functions.
My question is : What happens to the test() function? I know struct and class are essentially the same with class default member variable set to private. Why does c++ allow casting class to struct in this case, where the test() function seems to be no longer valid?

A: The only difference between class and struct is that, in the definition of the type, the default access level is private or public respectively. Otherwise, and in other contexts (such as this one), they are identical.
class masterStruct and struct masterStruct are two names for the same type. There's no casting because there's only one type. C++ allows the keywords to be used interchangeably because the default access level is no more than a minor implementation detail within the definition.
C++ class types (declared with class or struct) can be accessed from C functions as long as certain C++ features can't be used. virtual functions, mixed access protection for members, etc. can affect the layout of the members in memory, so the C compiler won't be able to find them. "POD" (plain old data) classes are a slight superset of what C will understand, because certain kinds of single inheritance are also permitted.
Nonstatic member functions don't add anything to a class in memory, so they don't affect its layout. They're just ordinary functions with special rules for passing an additional argument which implements this. C doesn't need to know about them, so you can safely #ifndef __cplusplus them out.
However, it doesn't sound like you're using masterStruct from C code at all, but you're only passing a void* through a C library and back to yourself. In this case, POD-ness doesn't make a difference either. The void* value is just a scalar value, and it will be the same when you pass it and when you get it back. It could point to anything, or to nothing; it doesn't matter.

A: Why does c++ allow casting class to struct in this case, where the test() function
seems to be no longer valid?

In C++, struct can also have functions. So you can cast a class object to an object of the according struct, and access the member functions via that struct object. Note that the access specifiers(public, private, or protected) in the original class definition determines how the member functions are accessed. Casting to struct doesn't redefine those functions as public, which you may wonder.
I guess your real question is why a C++ struct(or class as in your original question) can be passed to a C API where there is no member function concept in the language?
This is doable due to Plain Old Data(POD) types support in C++. POD objects in C++ are interchangable with C. That's why you can pass it to C API. In short, A POD type is a struct or class without user-defined constructors, destructors and virtual member functions, which is exactly your case. For a detailed discussion, refer to this thread.


text:
Q: JSON response is null, but the URL is echoing correctly I have a form being AJAX'd in by jQuery on a page with multiple forms.  I'm performing the following function, which is a wrapper for the $.ajax function:
function do_json_get(uri){
    var ret = '';
    var url = AJAX_URL + uri;

    $.ajax({
        type: 'GET',
        url: url,
        async: false,
        success: function(data) {
            ret = data.html;
        },
        dataType: 'json'
    });

    return ret;
}

When I go to the AJAX server directly (which is rendering the form in PHP), I get the raw JSON response - so I know the server is outputting to the browser, and the AJAX server is doing other things like setting the proper cookies, so I know that the connection is good (I get a 200 response code).  Yet the data object is coming back null.

A: Here's a guess. If you're serving the page from the file system, Firefox (and I think Chrome) will see it as originating from a different domain. You'll get the 200 response, but no data.
Try Safari, or maybe give jsonp a shot in place of json.
EDIT:
Since you're getting the data from a different domain, it won't work. I think it is not allowed by the XMLHTTPRequest.

A: Oh boy.  This question again.
AJAX: Asynchronous JavaScript And XML*. Asynchronous. Asynchronous. Asynchronous.
Your function, do_json_get() returns ret before the success handler function in the AJAX call executes.  The order of operation is not proceeding, here, from top to bottom. In other words, you just can't do it that way.
Because of its asynchronous nature, AJAX operates on callbacks, not return values. You need to change your paradigm.  The success handler function needs to do whatever is required with data.html itself, or pass it off to another function.
* Yes, I know the XML part of the original acronym is largely vestigial these days


text:
Q: How to add Cache-Control on create-react app so I was reading this article how to add control-cache
and I think the best way to do it is via .htaccess file, but will it work on create-react-app if I add it? I've read that that file is only working on Apache (and I think we are not using Apache) - I am not a devops guy or someone that knows how deployment or server works so It's quite hard for me to understand (I have no idea how we deploy, another team is handling it :( ).
So, how do I properly add it on create-react-app so I can cache my static images?
I saw a couple of the same questions here but they don't have an answer.


text:
Q: String replacement with array index for (int i = 0; i < NumberOfRFIDTransponders; i++)
{
  if (ReadDataFromReader == "ReaderLeft")
  {
    for (int j = 0; j < NodeIDList.Count; j++)
    {
       NodeIDList[j] = NodeIDList[j].Replace("LeftReader.DATABASE_UPDATE[0]",
       "RightReader.DATABASE_UPDATE[" + Convert.ToString(i) + "]");
    }
  }
}

The following is happening: I'm replacing the index of my DATABASE_UPDATE array with the index i of my first for loop. I also replace the name of my reader. The output of every loop within the loop with index j is that the name of the reader is replaced correctly but every index is set as [0]. So, the Convert.ToString(i) isnt working.


text:
Q: highcharts-ng - adding popover to legend items I'm trying to add a popover to the legend items for one of my charts. I'm using twitter bootstrap and have tried the javascript method as well as the template method with no luck. When I try to use the javascript method on the chart's load event the chart.legend.allItems array is always empty, which is odd, because if I print the chart.legend property to the console I see the allItems property with a length of 4. If I print the chart.legend.allItems property to the console it shows the length as 0. In any case, the allItems array is not loaded when the chart's load event fires. The javascript method for the popover results in a $(...).popover is not a function error because the ".highcharts-legend-item" is undefined when load fires. It seems like all the chart properties and elements aren not, in fact, loaded when this event fires.
load event
  events: {
      load: function(e) {
         $(".highcharts-legend").popover({trigger:'hover', placement:'bottom', title:'Title!', content:'Content'}).hover(function() {
         $('.popover').appendTo($(document.body));
      });

      }

template
legend: {
    align: 'left',
    verticalAlign: 'bottom',
    layout: 'vertical',
    x: 0,
    y: 2,
    labelFormatter: function () {
      return '' + this.name + '';
    },
    useHTML:true

Edit
I forgot to load popover.js from bootstrap but that didn't completely fix the issue. The only time I'm able to get the popover to display is passing the ".highcharts-legend" selector to jquery. Trying to use ".highcharts-legend-item" or any child element of ".highcharts-legend" doesn't display the popover. Any ideas?


text:
Q: How to convert custom digits to date in excel Assuming 421 stands for April 2021 and 1299 for December 1999, what would be the correct formula to convert the digits in to the corresponding date format in excel?

A: Adjust the 30 as you see fit:
=IFERROR(DATE(IF(VALUE(RIGHT(A1,2))<30,2000+RIGHT(A1,2),RIGHT(A1,2)),LEFT(A1,LEN(A1)-2),1),"")

A: Actually, here is a one-liner (note, to get the correct century the formula is posted lower in the answer and is more complicated):
=DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1)

DATE requires 1) Year 2) Month and 3) Day

*

*So, it's easy to get the year (just take the two most digits)

*However, it's trickier to get the month, since it can be 3 or 4 digits, so you need some if logic to add a 0 in front if only 3 digits and THEN take the left two digits to extract the month.

*Finally, you have to have a day for the formula, so just put a 1. Then format the cells as desired to whatever date format. See screenshot.

In order to get the correct century, then the formula gets complicated :) Basically, it says if the date is greater than now, subtract a century. If it is less than now, then go with that date.
=IF(DATE(YEAR(DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1))+100,MONTH(DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1)),DAY(DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1)))>NOW(),DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1),DATE(YEAR(DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1))+100,MONTH(DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1)),DAY(DATE(RIGHT(A1,2),LEFT(IF(LEN(A1)=3,0&A1,A1),2),1))))


text:
Q: How to find that all pixels in an image are grey scale or has R,G,B equal value for each individual pixel Please dont quote this How can I check the color depth of a Bitmap? or How to check if a picture is in grayScale
Because an image can be 24/32 bit per pixel even if all unique colors are grey scale or less than 256 and each pixel can be 24 or 32 bit.
How do I find that the pixel in an image Bitmap.GetPixel(x, y) has equal R,G,B vales so that I can find out if all pixels in an image lie in grey scale range. Because the R,G,B value of a grey scale pixel is same. Or is there any better way to find if the image is in grey scale?
I am writing a code to compress the size of a 16/24/32 bit image such that if the image has 256 unique colors then change it to 8 bit image and save it.
First I count unique colors in an image that has higher than 8 its per pixel.
If the unique colors in the image are less than or equal to 256 then

*

*If all the unique colors are in greyscale range then convert it to greyscale

*Otherwise if any color is not greyscale then convert image to 8 BPP

uint UniqueColors(Bitmap Bitmap)
{
    try
    {
        List<int> lstColors = new List<int>();

        if (null == Bitmap)
            return 0;

        for (int iCount = 0; iCount < Bitmap.Height; iCount++)
            for (int iCounter = 0; iCounter < Bitmap.Width; iCounter++)
                if (!lstColors.Contains(Bitmap.GetPixel(iCounter, iCount).ToArgb()))
                    lstColors.Add(Bitmap.GetPixel(iCounter, iCount).ToArgb());

        Bitmap.Dispose();

        return Convert.ToUInt32(lstColors.Count);
    }
    catch (Exception)
    {
        Bitmap.Dispose();
        return 0;
    }
}

And then:
if (256 >= UniqueColors(new Bitmap(string ImagePath)))
{
    if (Is_Greyscale(new Bitmap(ImagePath))
        Convert_To_Greyscale(ImagePath);
    else
        Convert_To_8Bits(ImagePath);
}

now I am stuck how do I find if each unique color in the image lies in the greyscae rage. By which I mean that each unique color has equal (R, G, B) values. Like R=G=B. How can I find it in my code line
Bitmap.GetPixel(iCounter, iCount).ToArgb()

A: Bitmap.GetPixel() returns a Color structure which has fields R, G and B so you can just compare them however you want.
Do note that using GetPixel() is very slow, but if you don't need speed it will do.


text:
Q: How do I control the access of multiple threads to a collection of objects? I'm writing an application that displays a list of objects which the user can select and then view and edit the properties of through a PropertyGrid control. The object's properties are populated by time consuming process of extracting information from files through the use of a secondary thread. But I'd also like to allow the user to continue viewing other objects as the extraction process is proceeding.
After reading the responses to my previous questions on SO. It sounds like because the properties that are being written by the extraction process do not intersect the properties that are editable by the user through the property grid I shouldn't have an issue with the two threads editing the objects at the same time. Although it's possible for the user to see an incorrect value if they are incredibly unlucky and the property grid end up reading the object in the middle of a non-atomic write.
However, I'd still like to know how I might set this up to prevent the user from editing or viewing an object which is in the middle of being extracted. I'm very very new to multithreading, but most examples that I've read so for show a separate token Object being created to use to lock access to to the actual Object of interest. The answers to my other previous question confirmed that it is typical to create a separate object like this specifically for locking.
So now what I'd like to know is how is this handled in my case where I have a large collection of objects? I'd like to create locks that prevents the property grid from displaying the object a user selects if it is currently being extracted to.
Do I need to create a separate collection of lock Objects that is kept in sync with my real collection? So if an object is added or removed from my main collection I have to add or remove lock objects from my lock collection?
Do I lock to the actual objects rather then creating separate token lock objects?
What about adding a "IsBeingExtracted" Boolean property to the objects that the property grid can check to see if the object is in the middle of being written to? This would then be set at the very beginning and very end of the extraction process.
Or how about a static field somewhere that references the current (if any) object that is current being extracted to. The property grid could then check that the latest object it was ask to display was not the object referenced by this static field? This of course wouldn't work if there were multiple extraction threads.
What's the best/correct way to do this? Personally I like the boolean property option the best, but would like to know what others who actually know what they are doing think.

A: Couldn't you just make the collection that holds the objects a SynchronizedCollection<T>? It will make sure that only one thread can add or access objects at a time. Then, rather than worry about how to synchronize access to each object's properties, don't add the object to the collection until it has been populated.
Something like this:
private readonly ICollection<Item> Items = new SynchronizedCollection<Item>();

// Run this on the background thread.
public void PopulateItems()
{
    using (var file = File.OpenRead("BigFile.txt"))
    using (var reader = new StreamReader(file))
    {
        while (!reader.EndOfStream)
        {
            var item = new Item();
            PopulateItem(item);
            Items.Add(item);
        }
    }
}

public void PopulateItem(Item item)
{
    // Do time-consuming work.
}

The property grid can happily do whatever it wants with the object because by the time it shows up in the list, the extraction thread is finished with it. No explicit locking required.

A: Make your collection of objects a Dictionary and then lock on the keys.

A: In general, using one or several locks depends on the degree of concurrency that you want to achieve.
The less locks you have (say, one global lock), the less concurrency there'll be because many operations can compete for the lock and prevent each other from running.
The more locks you have, the more concurrency you can achieve, but the more overhead there is in managing locks.
Using a lock that is the object being modified makes sense if what you are protecting with the lock is only this object. You'll see many examples using a separate object because you then don't need to thing about the scope of the protection.
In your specific case, I do not really understand what is being protected. Are you trying to prevent the concurrent modification of a property of an object, i.e. by the background process or the user ?
As a user cannot do more than one thing at a time, there is no need for lots of concurrency, thus there is no need to have many locks.
What you could do is have a single lock that is taken when the property grid enters editing mode and when a background process is about to set the same property being edited (otherwise, there is no need for locks).

A: I think the best way would be to use the ManualResetEvent object with a timeout. That way you can tell the user that it is being extracted and to try again in a few seconds.
public class Item : IDisposable // I know it is a horrible class name...
{
    private readonly ManualResetEvent accessibleEvent = new ManualResetEvent(false);

    public void Extract()
    {
        try
        {
            // .....
        }
        finally
        {
            accessibleEvent.Set(); // unlock
        }
    }

    public void Edit()
    {
        if (!accessibleEvent.WaitOne(1000)) // wait 1 second
        {
            // notify user?
        }

        // ....
    }

    public void Dispose()
    {
        ((IDisposable)accessibleEvent).Dispose();
    }
}


text:
Q: Creating new VM nodes, is this vagrant or puppet? I have an 8-cpu server and I installed Centos 7 on it.  I would like to dynamically and programmatically spin up and down VM nodes to do work, ex. Hadoop nodes.
Is the technology I use for this Vagrant or Puppet, or something else?  I have played around with Vagrant, but it appears that every new node requires a new directory in the file system, I can't just spin up a new VM as far as I can tell with an API call, I think.  And it doesn't look like there's even a real API for Vagrant, just machine-readable output.  And if I understand it properly, Puppet deals with configuration management for pre-existing nodes.
Is either of these the correct technology to use or is there something else that is more fitting to what I want to do?

A: Yes, you can use vagrant to spin up a new vm. Configuration of that particular vm can be done using puppet. Take a look at: https://www.vagrantup.com/docs/provisioning/puppet_apply.html
And if you're problem is having separate directories for each vm, you're looking for a multimachine setup: https://www.vagrantup.com/docs/multi-machine/
For an example using the multiserver setup take a look at https://github.com/mlambrichs/graphite-vagrant/blob/master/Vagrantfile
In the config directory you'll find a yaml file which defines an array that you can use to loop over different vm's.


text:
Q: Remote ssh commad with variables, quotes and single quotes I need to execute a command on a remote MongoDB server, using variables declared on the shell script.
Command:
ssh root@10.1.1.1 "mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval 'db.mycollection.update({}, {$push: {'"$ENTITY"': NumberInt('"$CODE"')}})' --quiet"

Note that if I use the command outside the shell script, substituting the variables, a bash -c syntax error comes up. Example:
ssh root@10.1.1.1 "mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval 'db.mycollection.update({}, {$push: {foo: NumberInt(123)}})' --quiet"

bash: -c: line 0: syntax error near unexpected token `('

It's working now! Solution:
DBUPDATE="db.mycollection.update({}, {\$push: {${ENTITY}: NumberInt(${CODE})}})"

ssh root@10.1.1.1 mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval "'$DBUPDATE'" --quiet

A: ssh root@10.1.1.1 'mongo mydb --host 10.1.1.1 --port 27017 -u user -p password --authenticationDatabase admin --eval "db.mycollection.update({}, {$push: {'"$ENTITY"': NumberInt('"$CODE"')}})" --quiet'

I switched the double quotes with single quotes at the beginning and end and put your --eval input in double quotes.


text:
Q: Angular 12 string interpolation App receive some data from server via rest calls. Based on this response we can build some context object and string. Example:
const contextObject = {name: 'World'};
const expression : string = 'Hello {{name}}';

So finally I would like to have 'Hello World' string which I can bind in HTML template.
Can somebody help and explain how to evaluate this expression in Angular 12?

@update Maybe somebody with better angular background can explain how i18n works with such scenarious? As task looks quite similar to replace all plaseholders with an object from context...
I as well was looking in some angular src and start with something like
    const context = {name: "World"};
    const expressionParser = new Parser(new Lexer());
    let parseInterpolation = expressionParser.parseInterpolation("Hello {{name}}", "", 0);
...

but that's it. Have no ide what to do next...

A: Angular supports template evaluation during runtime with JIT. The new Ivy renderer uses an AOT compiler, and is only suitable for build time usage. It is also the default pipeline.
I highly recommend to avoid going down including the run-time version of the compiler and creating templates in the browser as it's extremely slow. And will increase your bundle sizes significantly.
Rather creating templates and evaluating them run-time. I'd recommend to create the various components that you can dynamically render when needed.
So you'd essentially end up with something like:
Hello <Text [value]="contextObject.name"></Text>

If you're creating the RestAPI as well, you can easily create a tree of components with various data to pass along.
If your expression that you receive from your API is
Hello {{name}}

You'd have to parse it yourself, to generate the component tree you need to render a view in angular.
Your other solution is run-time compiling which is very slow and discouraged.
Ideally you should have your API provide some sort of structure that can be represented as your view.
{
   "children": [
      {
         "type": "Heading1",
         "children": [
            {
               "type": "Text",
               "value": "Hello",
            },
            {
               "type": "Text",
               "value": "World",
            },
         ]
      }
   ]
}

Which then could be easily translated to
<Heading1>
   <Text [vale]="Hello"></Text>
   <Text [vale]="World"></Text>
</Heading1>

For run-time compilation you should consult with google, as there are  resources available very sparsely.
However this demonstrates the basic flow of how to compile a component runtime.
Note This won't work out of the box, as you need to include several other modules in your application.
// Must clear cache.
this.compiler.clearCache();

// Define the component using Component decorator.
const component = Component({
    template: '
This is the dynamic template. Test value: {{test}}
',
    styles: [':host {color: red}']
})(class
{
    test = 'some value';
});

// Define the module using NgModule decorator.
const module = NgModule({
    declarations: [component]
})(class
{
});

// Asynchronously (recommended) compile the module and the component.
this.compiler.compileModuleAndAllComponentsAsync(module)
    .then(factories =>
    {
        // Get the component factory.
        const componentFactory = factories.componentFactories[0];
        // Create the component and add to the view.
        const componentRef = this.container.createComponent(componentFactory);
        // Modifying the property and triggering change detection.
        setTimeout(() => componentRef.instance.test = 'some other value', 2000);
    });

Dima Slivin provides a great article on this on his blog:
https://www.linkedin.com/pulse/compiling-angular-templates-runtime-dima-slivin/

A: This is not something angular will perform for you. It's something you'd have to code yourself like so:
let expression = "Hello {{name}}";
for(let key in contextObject )
{
    expression = expression.replace(`{{${key}}}`, contextObject[key]);
}

Simply replace all keys in the contextObject with their values.
You can utilize angular libraries & services to sanitize the string.


text:
Q: PDF Viewer works on VS Code Live Code Server but not on my local computer, pdf.js I am trying to make a PDF viewer, and it runs perfectly when I run it through live server on vscode, but for some reason, when I go to my files, right click on the index.html and click open with chrome, firefox, or internet explorer it comes up with 2 errors:
1)GET file://mozilla.github.io/pdf.js/build/pdf.js net::ERR_FILE_NOT_FOUND
main.js:18
2)Uncaught TypeError: Cannot read property 'GlobalWorkerOptions' of undefined
    at main.js:18
Here is my index.html code and my main.js code:
Index.html
<!DOCTYPE html>

    <title>PDF Viewer Attempt 2</title>
    <link rel="stylesheet" href="css/style.css">

PDF Name

    <button id="prev">Previous</button>
    <button id="next">Next</button>

    Page:  /

    <canvas id="the-pdf"></canvas>

main.js:
    //Code adapted from https://jsfiddle.net/pdfjs/wagvs9Lf/
// If absolute URL from the remote server is provided, configure the CORS
// header on that server.
var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf'; //works with this internet pdf
//url = 'pdf.pdf'; // Works with local pdf

// Loaded via


text:
Q: Json Error In Laravel Ajax I'm Use Laravel 5.2 And Ajax For Crud
Insert to Database is Correct But When Laravel Response The Browser Show Below Error In Console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Laravel Code:
return response()->json('ok');

Jquery Code:
    $.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
....
error: function(data){// Error...
var errors = $.parseJSON(data.responseText);                 console.log(errors);
$.each(errors, function(index, value) {                     $.gritter.add({
title: 'Error',
text: value
});
});
}

RedyState=4
Staus = 200

A: Can you paste your all controller code related to this error? Make sure you're not echoing anything before returning json response.
For example,
Route::get('/', function () {
    echo "hi";
    return response()->json('ok');
});

It would cause parse error.

A: With the Json response, what if you try something like.
return response()->json(['status'=>'ok']);

A: You javascript code should be
$.ajax({
    type: type,
    url: my_url,
    data: formData,
    dataType: 'json',
    success:function (xhr){
        var data = xhr.data;
    },
    error: function (error){

    }
});

And why are you using var errors = $.parseJSON(data.responseText); ? Your response will be always json, no?


text:
Q: r - ggplot paired seq I am having trouble plotting paired data with ggplot2.
So, I have a database with paired (idpair) individuals (id) and their respective sequences, such as
   idpair id 1 2 3 4 5 6 7 8 9 10
1       1  1 d b d a c a d d a  b
2       1  2 e d a c c d a b a  c
3       2  3 e a a a a c d b c  e
4       2  4 d d b c d e a a a  b
...

What I would like is to plot all the sequences but that somewhat we can visually distinguish the pair.
I thought of using the grid such as: facet_grid(idpair~.). My issue looks like this:

How could I plot the two sequences side by side removing the "vacuum" in between caused by the other idpair ?
Any suggestions of alternative plotting of paired data are very welcome.
My code
library(ggplot2)
library(dplyr)
library(reshape2)

dtmelt = dt %>% melt(id.vars = c('idpair', 'id')) %>% arrange(idpair, id, variable)

dtmelt %>% ggplot(aes(y = id, x = variable, fill = value)) +
  geom_tile() + scale_fill_brewer(palette = 'Set3') +
  facet_grid(idpair~.) + theme(legend.position = "none")

generate the data
dt = as.data.frame( cbind( sort( rep(1:10, 2) ) , 1:20, replicate(10, sample(letters[1:5], 20, replace = T)) ) )
colnames(dt) = c('idpair', 'id', 1:10)

A: You can remove the unused levels in the facet by setting scales = "free_y". This will vary the y-axis limits for each facet.
dtmelt %>% ggplot(aes(y = id, x = variable, fill = value)) +
    geom_tile() + scale_fill_brewer(palette = 'Set3') +
    facet_grid(idpair~., scales = "free_y") + theme(legend.position = "none")