text:
Q: Creating shortcuts in Android via Intent
Possible Duplicate:
Android create shortcuts on the home screen

I am having one TextView and Button in my Activity (HomeActivity.class).
Goal: When I click on the Button it should create a shortcut with the default android image as icon and text as entered in the TextView.
So far I've found out that we can create shortcuts using ACTION_CREATE_SHORTCUT
This is the code I have so far:
Intent result = new Intent(android.content.Intent.ACTION_CREATE_SHORTCUT);
result.putExtra(Intent.EXTRA_SHORTCUT_INTENT,
                new Intent(getApplicationContext(), Editor.class));
result.putExtra(TodoDbAdapter.KEY_ROWID,rowid);
result.putExtra(Intent.EXTRA_SHORTCUT_NAME,textView.getText());
result.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
                Intent.ShortcutIconResource.fromContext(HomeActivity.this,
                                                        R.drawable.icon));
setResult(RESULT_OK, result);

My Manifest File :
<activity android:name=".HomeActivity" android:label="@string/app_name">

        <intent-filter>
                <action android:name="android.intent.action.CREATE_SHORTCUT" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

But this code does not create any shortcut.
How can I create shortcuts?

A: Try this:
Intent shortcutIntent;
shortcutIntent = new Intent();
shortcutIntent.setComponent(new ComponentName(activity.getPackageName(), ".classname"));

shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

final Intent putShortCutIntent = new Intent();
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);

// Sets the custom shortcut's title
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"Title");
putShortCutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(PersonProfile.this, R.drawable.icon));
putShortCutIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(putShortCutIntent);

and add this permission in manifest:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />


text:
Q: Группировка и агрегация числовых и строковых значений в DataFrame У меня есть pd.DataFrame. Вывод data.head():
    userID  browser         slot    n_clicks    n_queries   n_nonclk_queries
0   1       Browser #2      exp         23          32      19
1   3       Browser #4      exp         3           4       2
2   5       Browser #4      exp         29          35      16
3   6       Browser #4      control     12          6       0
4   7       Browser #4      exp         54          68      30

Значение в userID может повторяться. Уникальным считается комбинация userID и browser. Мне необходимо преобразовать данные таким образом, чтобы userID был в табличке уникальным, со значением равным сумме по всем браузерам для конкретного userID.
Как это сделать эффективно?
Дополнение
После преобразования данных, я планирую разделить данные по группам (slot)
exp_clicks     = data[data["slot"] == 'exp'].n_clicks
cntrl_clicks   = data[data["slot"] == 'control'].n_clicks

И проверить гипотезу о равенстве средних с помощью критерия Манна-Уитни
stats.mannwhitneyu(exp_clicks, cntrl_clicks)

Slot — это обозначение группы (экспериментальная/тестовая), люди (userId) из одной группы не встречаются в другой.

A: Исходный DataFrame (я специально добавил запись для UserID==1 с Browser #33):
In [221]: df
Out[221]:
   userID      browser     slot  n_clicks  n_queries  n_nonclk_queries
0       1   Browser #2      exp        23         32                19
1       1  Browser #33      exp       100        100               100
2       3   Browser #4      exp         3          4                 2
3       5   Browser #4      exp        29         35                16
4       6   Browser #4  control        12          6                 0

Решение:
In [222]: df.groupby('userID', as_index=False).sum()
Out[222]:
   userID  n_clicks  n_queries  n_nonclk_queries
0       1       123        132               119
1       3         3          4                 2
2       5        29         35                16
3       6        12          6                 0

UPDATE: несколько вариантов для агрегирования текстовых данных:
Исходный DF:
In [2]: df
Out[2]:
   userID      browser     slot  n_clicks  n_queries  n_nonclk_queries
0       1   Browser #2      exp        23         32                19
1       1  Browser #22      exp       100        100               100
2       1  Browser #33  control       200        200               200
3       3   Browser #4      exp         3          4                 2
4       5   Browser #4      exp        29         35                16
5       6   Browser #4  control        12          6                 0

группировка по UserID и slot:
In [5]: df.groupby(['userID','slot'], as_index=False).sum()
Out[5]:
   userID     slot  n_clicks  n_queries  n_nonclk_queries
0       1  control       200        200               200
1       1      exp       123        132               119
2       3      exp         3          4                 2
3       5      exp        29         35                16
4       6  control        12          6                 0

преобразование значений из столбца slot в CSV:
In [24]: funcs = {c:'sum' for c in df.select_dtypes(include='number').drop('userID',1).columns}

In [25]: funcs
Out[25]: {'n_clicks': 'sum', 'n_queries': 'sum', 'n_nonclk_queries': 'sum'}

In [26]: funcs['slot'] = lambda x: x.values.tolist()

In [27]: df.groupby('userID', as_index=False).agg(funcs)
Out[27]:
   userID  n_clicks  n_queries  n_nonclk_queries                 slot
0       1       323        332               319  [exp, exp, control]
1       3         3          4                 2                [exp]
2       5        29         35                16                [exp]
3       6        12          6                 0            [control]

оставляем первое значение slot из группы:
In [28]: funcs['slot'] = 'first'

In [29]: funcs
Out[29]:
{'n_clicks': 'sum',
 'n_queries': 'sum',
 'n_nonclk_queries': 'sum',
 'slot': 'first'}

In [30]: df.groupby('userID', as_index=False).agg(funcs)
Out[30]:
   userID  n_clicks  n_queries  n_nonclk_queries     slot
0       1       323        332               319      exp
1       3         3          4                 2      exp
2       5        29         35                16      exp
3       6        12          6                 0  control

redpajama_set_name: RedPajamaStackExchange


text:
Q: A question on automorphisms of finite abelian groups Which are the finite groups $(G,\cdot)$ with the following property: for every $f \in Aut(G)$, there are $g,h\in Aut(G)$ such that $f(x)=g(x)\cdot h(x), \forall x\in G?$
I already have verified that:
 (i) such a group is abelian;
 (ii) all finite abelian groups of odd order have this property;
 (iii) a finite abelian 2-group satisfying this property must be of type $$(*)\hspace{2mm} \mathbb{Z}_{2^{\alpha_1}}\times \mathbb{Z}_{2^{\alpha_2}}\times \cdots\times \times \mathbb{Z}_{2^{\alpha_k}}$$where each $\alpha_i$ occurs at least twice.
In my opinion, the above class consists of all direct products $G_1\times G_2$, where $G_1$ is an abelian 2-group of type $(*)$ and $G_2$ is an abelian group of odd order, but I failed to prove it.

A: Here is an outline for odd order abelian $p$-groups:
The main point is that every non-zero element in a field with at least three elements is a sum of two non-zero elements. Using this, you can show that irreducible matrix in $GL_n(\mathbf Z/p\mathbf Z)$ can be written as a sum of two non-singular matrices, for such an irreducible matrix corresponds to multiplication by a primitive element of the field of order $p^n$.
Now, using the Jordan canonical form matrices over a finite field (see Theorem A.22 in my notes) you can show that every non-singular matrix over $\mathbf Z/p\mathbf Z$ is a sum of two non-singular matrices.
Finally, the endomorphism algebra of a finite abelian $p$-group modulo is radical is a product of matrix groups over $\mathbf Z/p\mathbf Z$ (see section 6 of this paper). So any invertible element of the endomorphism algebra can be written as a sum of two invertible elements modulo the radical of this ring. But adding something in the radical does not affect invertibility.


text:
Q: Xcode7 - equal heights multiplier constraint causing conflicting constraints I am attempting pretty much the same thing as the OP of this question in Xcode7.
My end goal is to have a vertical StackView with two child views: one that occupies 70% of the parent's height, and one that occupies the remaining 30%.
I followed the instructions in the post I linked. I selected the child view (which is a GMSMapView) and the parent StackView and checked the equal heights box in the Pin constraints menu. That worked just fine and dandy. However, when I edited that constraint from the GMSMapView's size inspector and changed the multiplier to .7, suddenly I get a conflicting constraints error!
Here is a picture of the scene I am working on right now:

And here is a picture of the error:

Does anyone know how to resolve these conflicts? I tried turning off Autoresize Subviews but I am not sure that worked since I can't delete some of the constraints displayed in the error message.

A: The height of a UIStackView is based off of the size of its subviews (Unless your using UIStackViewDistributionFillEqually).
The first two conflicting constraints evaluate to this
Stack View.height = View.height
Map View.height = 0.7 x Stack View.height

But since the UIStackView bases its height on its subviews, there is essentially a third constraint.
Stack View.height = Map View.height

All of these constraints can not exist together since they conflict.

There are two options I can think of.
Remove the UIStackView. Since it only contains one view, you aren't getting any benefit from using it and it's only complicating things.
If that's not an option, you will need to remove some constraints so that you aren't constraining the UIStackView to a specific height.


text:
Q: Search in one GWT ComboBox affects on other ComboBox with the same store I'm using com.extjs.gxt.ui.client.widget.form.ComboBox GWT version 2.8.2 and gxt 2.3.1a .
I have 2 comboboxes that have the same storage with many values. When I do search in one combobox I see in debug ComboBox lastquery value same as in search string and only single found value in the CombobBox store. But same value I see in other CombobBox which use same storage. So when I'm trying to work with other comboboxes connected (by listener) to second combobox I get an error because I can't load the required values.

com.google.gwt.core.client.JavaScriptException: (TypeError) : Cannot read properties of null (reading 'getValue__Ljava_lang_Object_2')
at Unknown.TypeError: Cannot read properties of null(Unknown@-1)

Maybe some option exists to allow to use of the same storage in several ComboBoxes without affecting each other, i.e. not limit storage with filtered by search string values? Using 2 storages by creating 2 copies is not preferable. Thanks in advance.
UPD: combobox2.getValue() gives null when search was performed earlier. How I can reload storage in this case?
UPD: I created 2 comboboxes with the same storage:
private final ListStore<ComboBoxItemModel<String>> countryStore;

public ComboBox<ComboBoxItemModel<String>> createCountryCombobox() {
    ComboBox<ComboBoxItemModel<String>> countriesComboBox = new ComboBox<>();
    countriesComboBox.setFieldLabel("Country");
    countriesComboBox.setStore(countryStore);
    countriesComboBox.setAllowBlank(false);
    countriesComboBox.setTriggerAction(ComboBox.TriggerAction.ALL);
    countriesComboBox.setDisplayField(ComboBoxItemModel.COMBO_BOX_ITEM_NAME);
    countriesComboBox.setValue(countriesComboBox.getStore().getAt(0));
    countriesComboBox.setForceSelection(true);
    countriesComboBox.setEditable(true);

    return countriesComboBox;
}

setEditable(true) option allows to search countries in the list, but it delete values in the storage as result. So I can't load values for other fields connected to second combobox without manual selection in combobox2.

A: Seems using two storage is quite a simple solution. Other solutions that I tried look like a workaround. I just create copies and it works fine:
ListStore<ComboBoxItemModel<String>> store = new ListStore<>();
store.add(countryStore.getModels());
countriesComboBox.setStore(store);


text:
Q: Storing table elements from webpage in dictionary I'm trying to extract a table from a webpage that I'm working on to store the headers as keys and the body as values but separately to denote which page they're from. Here's what I have tried:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
s=Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.maximize_window()
driver.get('https://www.google.com')

all_data = []
for i in range(1,6):
    url = "https://www.transfermarkt.co.uk/silvio-adzic/profil/spieler/{}".format(i)
    driver.get(url)
    time.sleep(3)
    data = {}
    soup = BeautifulSoup(driver.page_source, 'html5lib')
    print(f"In Page {i}")
    for th in soup.select("#yw2 tr"):
        data[th.get_text(strip = True)] = th.find_next('td').get_text(strip=True)
    all_data.append(data)

However this produces a jumbled dictionary:
[{'competitionwettbewerb': 'Total :',
  'Total :25169524616.948': 'Total :',
  'Regionalliga Süd': 'Regionalliga Süd',
  'Regionalliga Süd7922-2876.318': '',
  '2. Bundesliga': '2. Bundesliga',
  '2. Bundesliga60933873.487': '',
  'RL West-Südwest': 'RL West-Südwest',
  'RL West-Südwest5818-1943.493': '',
  'Oberliga Südwest': 'Oberliga Südwest',
  'Oberliga Südwest2015-1101.649': '',
  'Bundesliga': 'Bundesliga',
  'Bundesliga1212355355': '',
..
..
..

(Expected outcome) is there a way to separate these for each page that's extracted so something like this?
[{'p1':{'competition': ["Regionalliga Süd", "2. Bundesliga", ...],
'Appearances': [79, 60,...],
'Goals':[22, 9,...],
'Assists':[-, 3, ...]
...},
'p2':{'competition': ["Bundesliga", "2. Bundesliga", ...],
'Appearances': [262, 98,...],
'Goals':[62, 18,...],
'Assists':[79, -, ...]
...}}]

A: This needs more complex code to work with every row and every cell separatelly.
First I create place for all data
data = {'competition': [], 'Appearances': [], 'Goals':[], 'Assists':[]}

Next I use for-loop to get rows in table.
But there are two problems:

*

*some tr are empty but they don't have class so it is easy to skip them. I use also tbody to skip row in header.

*on some pages it uses ID yw2 and on other yw1 but both are in div with data-viewport=Leistungsdaten_Saison so it is easy to get correct tables.

for tr in soup.select("div[data-viewport=Leistungsdaten_Saison] tbody tr[class]"):

Next I get all cells in row and put values in correct lists.
        cells = tr.find_all('td')
        #print(cells)
        data['competition'].append(cells[1].get_text(strip=True))
        data['Appearances'].append(cells[2].get_text(strip=True))
        data['Goals']      .append(cells[3].get_text(strip=True))
        data['Assists']    .append(cells[4].get_text(strip=True))

And finally I put data in all_data with key p1, p2, etc.
        all_data.append({'p{}'.format(i): data})

Full working code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
from bs4 import BeautifulSoup

s = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.maximize_window()

all_data = []

for i in range(1, 6):
    print('--- page', i, '---')

    url = "https://www.transfermarkt.co.uk/silvio-adzic/profil/spieler/{}".format(i)
    driver.get(url)
    time.sleep(5)

    soup = BeautifulSoup(driver.page_source, 'html5lib')

    data = {'competition': [], 'Appearances': [], 'Goals':[], 'Assists':[]}

    for tr in soup.select("div[data-viewport=Leistungsdaten_Saison] tbody tr[class]"):
        cells = tr.find_all('td')
        #print(cells)
        data['competition'].append(cells[1].get_text(strip=True))
        data['Appearances'].append(cells[2].get_text(strip=True))
        data['Goals']      .append(cells[3].get_text(strip=True))
        data['Assists']    .append(cells[4].get_text(strip=True))

    all_data.append({'p{}'.format(i): data})

# --- display ---

for player in all_data:
    name, data = list(player.items())[0]
    print('---', name, '---')
    for key, value in data.items():
        print(key, value)

Result:
--- p1 ---
competition ['Regionalliga Süd', '2. Bundesliga', 'RL West-Südwest', 'Oberliga Südwest', 'Bundesliga', 'NOFV-Oberliga Süd', 'Oberliga Bayern', 'DFB-Pokal', 'UEFA Cup']
Appearances ['79', '60', '58', '20', '12', '9', '6', '6', '1']
Goals ['22', '9', '18', '15', '1', '-', '2', '2', '-']
Assists ['-', '3', '-', '-', '2', '-', '-', '-', '-']
--- p2 ---
competition ['Bundesliga', '2. Bundesliga', 'DFB-Pokal', 'Champions League', '2. BL North', 'UEFA Cup', 'VL Südwest', '2. BL Nord Aufstiegsr.', 'Ligapokal', "Cup Winners' Cup", 'DFB-SuperCup', 'UI Cup', 'Champions League Qu.', 'Südwestpokal', 'Intertoto-Cup (until 94/95)']
Appearances ['262', '98', '38', '23', '21', '15', '11', '9', '6', '4', '2', '2', '1', '1', '0']
Goals ['62', '18', '9', '7', '3', '4', '1', '2', '2', '2', '-', '2', '-', '1', '-']
Assists ['79', '-', '5', '3', '-', '5', '-', '-', '-', '1', '2', '-', '-', '-', '-']
# ...


text:
Q: Oracle proceduce create or replace procedure tt
is
begin
  select leasestation,returnstation
  from system.t_123
       leasedate>='2014-02-23';
end tt;

alter procedure tt compile;

exec tt

It doesn't work, SQL server and Oracle have so much differences,how should i do to make sure it can work on Oracle

A: It won't work without an INTO e.g. SELECT INTO some variable(s).  PL/SQL doesn't allow you to just return data without something like a CURSOR.
If you want to return the data from the SELECT statement as a Dataset, you'll need to use a REF CURSOR to store the result set and then have that REF CURSOR be an OUT parameter.
Some light reading:

*

*Example: Returning a REF CURSOR from a procedure (PL/SQL). You'll want to use the first example in that article.

*Using PL/SQL Stored Procedures and REF CURSORs


text:
Q: Можно ли по правилам ООП создавать ссылку на поле объекта? Java У меня была такая ситуация:
Class A = new Class();
int[][] B = A.getField();

В процессе выполнения программы поле field редактируется с помощью метода класса Class. Затем ссылке-переменной A присваивается новый объект.
A.editField();
A = new Class();

Однако последствии выясняется, что ссылка B все так же ссылается на поле field первого объекта. Как так получается, что объекта уже не существует, но его поле еще осталось? Можно ли вообще по правилам ООП создавать ссылку на поле объекта?

A: Объект в этом случае был просто держателем ссылки на field. По правилам сборки мусора, объект уничтожается только тогда, когда на объект не будет ссылок.
В вашем случае, при уничтожении объекта все его поля были уничтожены, в том числе ссылка на field. Но вы создали другую ссылку из другого места, поэтому field не был уничтожен, так как на него все еще есть ссылки.
То есть на самом деле поля объекта не осталось, оно действительно было уничтожено. Просто была создана вторая ссылка, которая сохранила field от сборщика мусора не смотря на то, что первая ссылка (ссылка внутри объекта) была удалена вместе с объектом.


text:
Q: I need the input to be a number. If nor, display "please enter number" and ask for input again This is what I want, but for an integer. I am not allowed to use break or continue to exit loops.
# basically I need this, but with an int(input('please enter a number'))

ask = input('Would you like to play Steal or Deal [y|n]? ')

while ask not in ('y', 'n'):

    print ("Please enter either 'y' or 'n'")
    print('')
    ask = input('Would you like to play Steal or Deal [y|n]? ')

A: You could try to convert the string to an int and catch the exception:
def is_number(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

ask = input('please enter a number: ')

while not is_number(ask):

    print ("no, a number!")
    print('')
    ask = input('please enter a number: ')


text:
Q: Where should properties like "SERVER_URL" live in a gradle-based Android project? Where should I define constants like SERVER_URL or some static passwords in a Gradle Android project? Obviously, I will use it in code.

*

*In build.gradle file as a build config field

*In gradle.properties file (I don't know how get these properties by code)

*In another props file located in res folder

How secure is it in each case?
Thanks.

A: There are two approaches in your question.

1> To store static URL in your application

The fact someone can see the URL doesn't matter (they could get this by sniffing the network anyway). You probably want to ensure the request has come from a trusted client. You can also maintain some key in request also.

2> To store password in your application

I found a good solution to store it in SharedPreferences with encryption. Copy/Paste below code to create encrypted SharedPreferences.
Simply wrap your own SharedPreferences object in this one, and any data you read/write will be automatically encrypted and decrypted. eg.
final SharedPreferences prefs = new ObscuredSharedPreferences(
this, this.getSharedPreferences(YOUR_PREFS_FILE_NAME, Context.MODE_PRIVATE) );

// eg.
prefs.edit().putString("test","test").commit();
prefs.getString("test", null);

Class code,
/**
 * Warning, this gives a false sense of security.  If an attacker has enough access to
 * acquire your password store, then he almost certainly has enough access to acquire your
 * source binary and figure out your encryption key.  However, it will prevent casual
 * investigators from acquiring passwords, and thereby may prevent undesired negative
 * publicity.
 */
public class ObscuredSharedPreferences implements SharedPreferences {
    protected static final String UTF8 = "utf-8";
    private static final char[] SEKRIT = ... ; // INSERT A RANDOM PASSWORD HERE.
                                               // Don't use anything you wouldn't want to
                                               // get out there if someone decompiled
                                               // your app.

    protected SharedPreferences delegate;
    protected Context context;

    public ObscuredSharedPreferences(Context context, SharedPreferences delegate) {
        this.delegate = delegate;
        this.context = context;
    }

    public class Editor implements SharedPreferences.Editor {
        protected SharedPreferences.Editor delegate;

        public Editor() {
            this.delegate = ObscuredSharedPreferences.this.delegate.edit();
        }

        @Override
        public Editor putBoolean(String key, boolean value) {
            delegate.putString(key, encrypt(Boolean.toString(value)));
            return this;
        }

        @Override
        public Editor putFloat(String key, float value) {
            delegate.putString(key, encrypt(Float.toString(value)));
            return this;
        }

        @Override
        public Editor putInt(String key, int value) {
            delegate.putString(key, encrypt(Integer.toString(value)));
            return this;
        }

        @Override
        public Editor putLong(String key, long value) {
            delegate.putString(key, encrypt(Long.toString(value)));
            return this;
        }

        @Override
        public Editor putString(String key, String value) {
            delegate.putString(key, encrypt(value));
            return this;
        }

        @Override
        public void apply() {
            delegate.apply();
        }

        @Override
        public Editor clear() {
            delegate.clear();
            return this;
        }

        @Override
        public boolean commit() {
            return delegate.commit();
        }

        @Override
        public Editor remove(String s) {
            delegate.remove(s);
            return this;
        }
    }

    public Editor edit() {
        return new Editor();
    }

    @Override
    public Map<String, ?> getAll() {
        throw new UnsupportedOperationException(); // left as an exercise to the reader
    }

    @Override
    public boolean getBoolean(String key, boolean defValue) {
        final String v = delegate.getString(key, null);
        return v!=null ? Boolean.parseBoolean(decrypt(v)) : defValue;
    }

    @Override
    public float getFloat(String key, float defValue) {
        final String v = delegate.getString(key, null);
        return v!=null ? Float.parseFloat(decrypt(v)) : defValue;
    }

    @Override
    public int getInt(String key, int defValue) {
        final String v = delegate.getString(key, null);
        return v!=null ? Integer.parseInt(decrypt(v)) : defValue;
    }

    @Override
    public long getLong(String key, long defValue) {
        final String v = delegate.getString(key, null);
        return v!=null ? Long.parseLong(decrypt(v)) : defValue;
    }

    @Override
    public String getString(String key, String defValue) {
        final String v = delegate.getString(key, null);
        return v != null ? decrypt(v) : defValue;
    }

    @Override
    public boolean contains(String s) {
        return delegate.contains(s);
    }

    @Override
    public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
        delegate.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
    }

    @Override
    public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener onSharedPreferenceChangeListener) {
        delegate.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
    }

    protected String encrypt( String value ) {

        try {
            final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0];
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.System.ANDROID_ID).getBytes(UTF8), 20));
            return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),UTF8);

        } catch( Exception e ) {
            throw new RuntimeException(e);
        }

    }

    protected String decrypt(String value){
        try {
            final byte[] bytes = value!=null ? Base64.decode(value,Base64.DEFAULT) : new byte[0];
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(Settings.Secure.getString(context.getContentResolver(),Settings.System.ANDROID_ID).getBytes(UTF8), 20));
            return new String(pbeCipher.doFinal(bytes),UTF8);

        } catch( Exception e) {
            throw new RuntimeException(e);
        }
    }

}

Edit
You can use NDK to store password constant. To store and retrieve your key, you need to write the following code in our application.
static {
    System.loadLibrary("library-name");
}

public native String getSecretKey();

And save in a file using NDK the following function
Java_com_example_exampleApp_ExampleClass_getSecretKey( JNIEnv* env,
                                              jobject thiz )
{
    return (*env)->NewStringUTF(env, "giveMeSecretKey".");
}

Now you can easily retrieve our key and use it to encrypt our data.
byte[] keyPassword = getSecretKey().getBytes();

A: One approach would be to define every sensitive value in gradle.properties, and ensure that this file is excluded from VCS. You can then get Gradle to add string resources into your build, which are accessible in the normal way. This has the added advantage that you can use different values for different product flavors.
// gradle.properties

MY_SECRET_PASSWORD=password

// build.gradle

buildTypes {
    debug {
        resValue "string", "my_secret_password", MY_SECRET_PASSWORD
    }
}

// MainActivity.java
String password = getString(R.string.my_secret_password);


text:
Q: What's the easiest way to check nuget package platforms? I know name of nuget package in official nuget gallery. How can I check on which platforms it's avaibale, e.g full .net, silverlight, windows store apps, universal platform, etc..?

A: On Windows I normally use the NuGet Package Explorer which will download the NuGet package and show you its contents. The frameworks it supports are shown in the lib directory inside the NuGet package.
You can also just download the NuGet package from NuGet and unzip it.


text:
Q: Randomly putting $N$ balls to $M$ baskets Suppose I have $N\in \mathbb{N}$ identical balls and $M\in \mathbb{N}$ identical baskets.
I throw the balls one by one into the baskets. Each basket has equal probability to catch the ball (no missing). Then my question is what's the distribution of the number of balls a basket finally contains?
Is it related to Poisson distribution?

A: It is not related to Poisson, it is in fact modelled by the Binomial distribution.
You have probability $1/M$ of a ball going into a specific basket which can be modelled as a "success" and the ball going into any other basket being a "failure".
Therefore with N throws the expected value of balls in any basket will be $N/M$ and the probability of $k$ balls being in a specific basket is:
$p(k) = {N \choose k} (1/M)^k ((N-1)/M)^{\rm\it{n-k}}$


text:
Q: Simulating an Active Directory Login in Dev/Test Environment Currently building a WPF app that will run in an environment where the user logs into Windows PC which is on a domain (DC).  The app will ask the user to enter their login and password again when it starts up, and the login/password will be verified against Active Directory (forgive me if my terminology is not correct here).
The login is all-or-nothing; if their password is correct, there is no (current) concern with retrieving groups, rights or anything of that nature.
The development environment is not AD-based, and is not on a domain.  Are there any options for simulating this kind of login without going through the process of setting up a domain controller and adding the development and test environment machines to it?
There will be some opportunity to do deployment testing during the course of the project (IOW create a test login app, deploy it to the user and make sure the login works before final deployment).  At the same time, I will need to use some sort implementation that works in the test/dev environment.
Any thoughts?  Would you recommend against simulating this in lieu of setting up a DC?

A: Use ADAM (Windows Server 2003 Active Directory Application Mode)

For organizations that require
  flexible support for directory-enabled
  applications, Microsoft has developed
  Active Directory Application Mode
  (ADAM). ADAM is a Lightweight
  Directory Access Protocol (LDAP)
  directory service that runs as a user
  service, rather than as a system
  service. Active Directory Application
  Mode represents a breakthrough in
  directory services technology that
  provides flexibility and helps
  organizations avoid increased
  infrastructure costs.

That is, a free AD server from Microsoft that you can run on your desktop.

A: If you're on Windows 8 you can go to Add/Remove Windows Features and check AD LDS. Once it's finished configuring, run mmc and add ADSI Edit. It'll default to a domain controller on the network and you can populate your own instance of AD.


text:
Q: How to "attach" an existing model to an existing DbConnection when creating an Entity Framework DbContext? I have an assembly with an EDMX model. I can successfully create a DbContext specifying in the constructor a connection string with a reference to that assembly (metadata=res://MyAssembly/MyModel.csdl|res://MyAssembly/MyModel.ssdl|res://MyAssembly/MyModel.msl ...), and in that case everything works fine.
However, now I'm faced with a situation where I'm getting an existing DbConnection from an external source, as well as an existing DbTransaction. I'd like to have a strongly-typed Entity Framework view over this DbConnection. So, instead of using the connection-string DbContext constructor, I am using a different DbContext constructor that takes a DbConnection (and then using context.Database.UseTransaction() to set the existing transaction).
In this case, as soon as I try accessing one of my tables, I am getting an error, The entity type MyType is not part of the model for the current context. - it seems that my model isn't "attached" to the existing DbConnection.
So, my questions are:

*

*Is it possible to somehow "attach" a model from my EDMX-containing assembly to an existing DbConnection?

*I've noticed there's a DbContext constructor that takes both a DbConnection and a DbCompiledModel. This seems to be exactly what I need. How can I extract a DbCompiledModel from an existing EDMX-containing assembly?

A: Just my luck, found an answer right after posting a bounty :) Almost the entire answer (minus the part about transactions) was here - I didn't think of searching for SqlConnection instead of DbConnection.
Essentially, given an existingDbConnection and an existingDbTransaction:
var workspace = new MetadataWorkspace(
            new string[] { "res://*/" },
            new Assembly[] { Assembly.Load("My.Assembly.Name")});
            // can use Assembly.GetExecutingAssembly() if in current assembly
var wrappedConnection = new EntityConnection(workspace, existingDbConnection, false);
var context = new DbContext(wrappedConnection, false)
context.Database.UseTransaction(existingDbTransaction);


text:
Q: If a zero entropy distribution implies high information a priori, what does it mean ex posteriori? The following counteracts the statements made for the maximum entropy principle case in order to posit a pseudo "minimum entropy principle" case that is simply the polar opposite of the former.
A continuous random variable that has only 1 certain outcome is said to have a Shannon entropy of 0 because its distribution (outcome) is fully certain.
In turn, this zero-entropy variable is said to have maximum information in the sense that unexpected outcomes (all outcomes other than the 1 certain outcome) possess high information a priori. Distributions with such low entropy are undesirable because they represent the case where strong assumptions are made about the variable's outcomes a priori. In this case, we have strongly assumed that the variable will only generate the certain outcome and not deviate from it, based maybe purely on historical observations of the variable.
But what does a zero/low entropy variable mean ex post after the empirical data outcomes, unexpected or not, are actually realized? Does high information still exist in the zero entropy distribution? has its information content dissipitated somehow?  has its entropy changed from $0$? How and why


text:
Q: Mocha Test is not passing I created a function here with assert testing:
function renderInventory(arr) {
  var str = '';
  for(var i = 0; i < arr.length; i++){
    for(var j = 0; j < arr[i].shoes.length; j++){
       str += arr[i].name + ', ' + arr[i].shoes[j].name + ', ' + arr[i].shoes[j].price + '\n';
    }
  }
  return str;

}

var currentInventory = [{
    name: 'Brunello Cucinelli',
    shoes: [{
        name: 'tasselled black low-top lace-up',
        price: 1000
    }, {
        name: 'tasselled green low-top lace-up',
        price: 1100
    }, {
        name: 'plain beige suede moccasin',
        price: 950
    }, {
        name: 'plain olive suede moccasin',
        price: 1050
    }]
}, {
    name: 'Gucci',
    shoes: [{
        name: 'red leather laced sneakers',
        price: 800
    }, {
        name: 'black leather laced sneakers',
        price: 900
    }]
}];

var actual = renderInventory(currentInventory);
var expected = "Brunello Cucinelli, tasselled black low-top lace-up, 1000" + '\n' +
"Brunello Cucinelli, tasselled green low-top lace-up, 1100" + '\n' +
"Brunello Cucinelli, plain beige suede moccasin, 950" + '\n' +
"Brunello Cucinelli, plain olive suede moccasin, 1050" + '\n' +
"Gucci, red leather laced sneakers, 800" + '\n' +
"Gucci, black leather laced sneakers, 900";

function assertrenderInventory(actual, expected, testName){
  if(actual === expected){
    console.log('passed');
  }else{
    console.log('FAILED [' + testName + '] Expected "' + actual + '" to be "' + expected + '"');
  }
}

assertrenderInventory(actual, expected, 'testing renderInventory');

Basically what this does is that it get the designer name and shoe name with it's price all in one line by iterating through the array. But for some reason no matter how I tried to do the testing it still failed and there is a 'split' error on the mocha test.
Here's the mocha test:
describe('render inventory', function() {
  it('renders_first_line_correctly', function() {
    var inventory = [
      {
        name: 'Brunello Cucinelli',
        shoes: [
          {name: 'tasselled black low-top lace-up', price: 1000},
          {name: 'tasselled green low-top lace-up', price: 1100},
          {name: 'plain beige suede moccasin', price: 950},
          {name: 'plain olive suede moccasin', price: 1050}
        ]
      },
      {
        name: 'Gucci',
        shoes: [
          {name: 'red leather laced sneakers', price: 800},
          {name: 'black leather laced sneakers', price: 900}
        ]
      }
    ];

    var actual = renderInventory(inventory).split('\n');
    var expected = 'Brunello Cucinelli, tasselled black low-top lace-up, 1000';
    expect(actual[0]).toBe(expected);
  });

  it('renders_second_line_correctly', function() {
    var inventory = [
      {
        name: 'Brunello Cucinelli',
        shoes: [
          {name: 'tasselled black low-top lace-up', price: 1000},
          {name: 'tasselled green low-top lace-up', price: 1100},
          {name: 'plain beige suede moccasin', price: 950},
          {name: 'plain olive suede moccasin', price: 1050}
        ]
      },
      {
        name: 'Gucci',
        shoes: [
          {name: 'red leather laced sneakers', price: 800},
          {name: 'black leather laced sneakers', price: 900}
        ]
      }
    ];

    var actual = renderInventory(inventory).split('\n');
    var expected = 'Gucci, black leather laced sneakers, 900';
    expect(actual.pop()).toBe(expected);
  });
});

Any idea what should I do to pass the test here?
You can check my codes here: https://jsbin.com/zeviponeda/edit?html,js,console

A: you'r renderInventory appends '\n' to the end line also but your expected does not end with '\n'; the actual expected should be
var expected = "Brunello Cucinelli, tasselled black low-top lace-up,
1000" + '\n' +
"Brunello Cucinelli, tasselled green low-top lace-up, 1100" + '\n' +
"Brunello Cucinelli, plain beige suede moccasin, 950" + '\n' +
"Brunello Cucinelli, plain olive suede moccasin, 1050" + '\n' +
"Gucci, red leather laced sneakers, 800" + '\n' +
"Gucci, black leather laced sneakers, 900" + '\n';

for the same reason actual.pop() results in empty string


text:
Q: Global variables in Python with file names I am writing a Python 3 program with Tkinter, which is running under Windows 8.1.
I need to select two folders which will be used together in another function. Currently, I have two select file buttons, which open the select folder dialog box:
def select_file_1(self):
    global first_file
    first_file = filedialog.askdirectory()

def select_file_2(self):
    global second_file
    second_file = filedialog.askdirectory()

These work correctly: whenever the buttons are clicked, it comes up and asks for a directory.
Then, there is only one other time the first_file and second_file variables are used, which I also note as global variables before using them. This is when another button is selected:
def create_composite(self):
    global first_file
    global second_file

    f1 = open(first_file, "r")
    f2 = open(second_file, "r")

However, this results in the following error: NameError: name 'first_file' is not defined when trying to read the line above beginning with f1 = open.
If it helps for clarity, here is the relevant part of my interface in the screenshot below. select_file_1 is called by clicking the first choose file and select_file_2 is called by clicking the second choose file. Then, create_composite is called by clicking create class.

A: The snippets you have posted work correctly, so long as select_file_1() and select_file_2() are called before create_composite.
If you are still having problems you need to create a complete, small, working bit of code that you can post so others can see the problem.
Oh, and filedialog.askdirectory returns the name of a directory, not of a file -- trying to open that is not a good idea.


text:
Q: Laravel Auth::attempt no funciona correctamente Acabo de empezar con Laravel y poco a poco voy sacando cosas en claro, el problema que se me presenta es que al introducir los datos en mi formulario login, y compararlos con mi bbdd la autentificación de estas credenciales siempre sale falso, y no entiendo porque, os dejo unos fragmentos de código:
LoginController:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class LoginController extends Controller
{

    public function iniciarSesion(Request $request)
    {
        $credenciales = array(
            'email' => $request->email,
            'password' => $request->contraseña
        );
        if (Auth::attempt($credenciales)) {
            // Authentication passed...;
            return redirect()->route('core.get.dashboard');
        }
        //La autenticación no ha funcionado

    }

    public function cerrarSesion()
    {
        Auth::logout();
        return redirect()->intended('inicio');
    }
    //
}

Usuario Factory:
<?php

namespace Database\Factories;

use App\Models\Usuario;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UsuarioFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Usuario::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => 'Julia',
            'email' => 'admin@admin.com',
            'password' => bcrypt('contrasena'), // contraseña
            'updated_at' => now(),
            'created_at' => now(),
        ];
    }
}

BBDD:

Formulario Login:
<form class="mt-8" action="{{ route('admin.post.iniciar-sesion') }}" method="post">
        @csrf

                Correo electrónico
                <input id="email" name="email" value="{{ old('email') }}" type="email" required placeholder="Correo electrónico" class="appearance rounded relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900  focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5">

                    Contraseña

                        Contraseña olvidada?

                <input id="contraseña" name="contraseña" value="{{ old('password') }}" type="text" required placeholder="******" class="appearance-none rounded relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:shadow-outline-blue focus:border-blue-300 focus:z-10 sm:text-sm sm:leading-5">

            <button type="submit"class="group relative w-full mt-6 flex justify-center py-2 px-4 border border-transparent text-sm leading-5 font-medium rounded-md text-white bg-brand-600 hover:bg-brand-500 focus:outline-none focus:border-brand-700 focus:shadow-outline-brand active:bg-brand-700 transition duration-150 ease-in-out">
                Iniciar sesión
            </button>

    </form>

Según estos datos el usuario debería ser "admin@admin.com" y la pass seria "contrasena". Pues al introducir estos datos en el login me da falso.
Gracias de antemano.


text:
Q: How to reset state variable value to its initial value always when a component is rendered in React I have a React component which is like a graph where you can click on different nodes to get additional info. I have a boolean state variable (clickedNode) in this component to determine if I need to render another component (basically tables with info) when a node is clicked. So from this graph component, I'm calling this table component and in the table component I have another state variable (clickedTableRow). Basically, I want this state variable to initialize to false always when this table component is rendered. I have some logic which sets this variable to true in table component but how can I initialize this variable to false always when table component is called from the graph component?
For reference, this is the template for my code:
  const Graph=()=>{

    //graph rendering code

    {clickedNode?(<div> <Table /> </div>):("")}

  }

  const Table = props => {

    let[clickedTableRow,setTableRowClicked]=useState(false)  // I want clickedTableRow to be initialized to false always

    //rest of the table code
  }

A: You can use regular variable instead of state: let clickedTableRow = false


text:
Q: Unreadable result when clicking ListView I am displaying a list of peoples names in a ListView.
When I click on a name I have it set up to display a Toast message showing the name of the person clicked.
However the toast is displaying unreadable data and I can't figure out how to make it just display the name.
Below is the toast message:
"com.example.friends.Person@50db3a clicked!"
I wanna display something like
"Joe bloggs clicked!".
The list gets its data from an arraylist containing Person objects.

A: Override toString() method in Person class and return the person's name or whatever you want to appear. For example:
@Override
public String toString() {
    return name;
}


text:
Q: VLC plugin for android browser i found VLC for Android Beta (https://play.google.com/store/apps/details?id=org.videolan.vlc.betav7neon&hl=sk) which enables to play videos in VLC player on Android. But I need VLC plugin for browser on Android (for default browser or for chrome or any other browser). Is it possible ? Can you suggest mi anything ? When I installed VLC for Android Beta it not contains web plugin...
btw, I am using android 4.1.1.

A: There is no VLC web plugin for Android and it's highly questionable (if not impossible) if it's actually even technically feasible to develop such a thing.
Just open your links in the VLC for Android, e.g. by using the vlc:// protocol handler which will be introduced by the next update.


text:
Q: Closing mapped streams - what's the idea? It's well known that Javadoc says about Stream interface:

Streams have a BaseStream.close() method and implement AutoCloseable,
but nearly all stream instances do not actually need to be closed
after use. Generally, only streams whose source is an IO channel (such
as those returned by Files.lines(Path, Charset)) will require closing.
Most streams are backed by collections, arrays, or generating
functions, which require no special resource management. (If a stream
does require closing, it can be declared as a resource in a
try-with-resources statement.)

Ok, but at the same time there are methods like flatMapToInt in this interface:
IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);

for which Javadoc specification says:

Each mapped stream is closed after its contents have been placed into
this stream.

So, I didn't get the idea: if IntStream isn't designed to have IO channel in its source, why is it closed inside this method?
For example, ReferencePipeline implementation does it in this way:
try (IntStream result = mapper.apply(u)) {
   if (result != null)
       result.sequential().forEach(downstreamAsInt);
}

More general question could be: should we care about closing streams like IntStream (or its descendants) or not? If not, then why does flatMapTo* care?
EDIT @Tunaki has provided me with a very interesting email link. But this all is about flatMap, where, I agree, we should close the stream in general case. But my question is about special cases: flatMapToInt, flatMapToLong and so on, where I don't see any necessity of closing streams.
EDIT-2 @BrianGoetz is appealed here, because it is his cited email, therefore he is in the subject :)

A: The general rule about resource handling is that whoever is responsible for closing a resource is the one that opened it. The flatMap operation is the only operation in the Stream API that opens a Stream, so it is the only operation that will close it.
Quoting from this mail, Brian Goetz said:

To summarize, flatMap() is the only operation that internally closes the
  stream after its done, and for good reason -- it is the only case where
  the stream is effectively opened by the operation itself, and therefore
  should be closed by the operation too.  Any other streams are assumed to
  be opened by the caller, and therefore should be closed by the caller.

The example given is the following. Consider
try (Stream<Path> paths = Files.walk(dir)) {
    Stream<String> stream = paths.flatMap(p ->  {
        try {
            return Files.lines(p);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}

The method reference Files::lines returns a Stream<String> of the lines of the file. When the flat mapping operation is over, it is expected that the opened resource used to read the file is closed. The question is: closed by what? Well, closed by flatMap itself because it is the operation that opened the Stream in the first place.
Files.lines returns a Stream with a pre-registered close handler that closes the underlying BufferedReader. When the flatMap operation is done, this close handler is invoked and the resources are correctly released.

The reason this idea is backported to flatMapTo* operations is the same: adhering to the above rule that every resource allocated by a process should be closed by that process.
Just to show that you can build an IntStream which would have an underlying resource to close, consider the following Stream pipeline where each path is not flatmapped to its lines but to the number of character in each line.
try (Stream<Path> paths = Files.walk(dir)) {
    IntStream stream = paths.flatMapToInt(p ->  {
        try {
            return Files.lines(p).mapToInt(String::length);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}


text:
Q: Disable resizing of ckeditor not working I have a ckeditor inside dialog box of jquery.I need to make the ckeditor non resizable.I have tried config.resize_enabled = false;,but its not working. I have also tried to set max-width,then also its not working.
<script src="include/ckeditor/ckeditor.js"></script>
<script src="include/ckeditor/adapters/jquery.js"></script>

<textarea id="dialog_description" style="width: 440px; max-height: 200px; min-height: 170px;">
</textarea>

$(function() {
    CKEDITOR.editorConfig = function(config) {
        config.resize_enabled = false;
        config.resize_maxWidth = 600;
    };

    $("#dialog_loader").dialog({
        resizable: false,
        height: "auto",
        modal: true,
        minWidth: 800,
        autoOpen: false,
        position: 'center top',
        open: function() {
            $('#dialog_description').ckeditor();
        },
        close: function() {
            $('#dialog_description').ckeditorGet().destroy();
        },
        buttons: {
            //some stuff
        }
    });
});


text:
Q: "Class, open your books TO/AT page 13!"—Is it a matter of dialectal difference? My original notion was,

*

*A) If there's a movement and a destination (as in the case of thumbing a book to reach a certain page), it should be to:
Class, open your books to page 13!

*B) If there's none, then at:
There on the counter rested my cookbook, open at page 13.
The tome fell open right at the middle page.
Then I asked around and rummaged in corpora and found out that my reasoning was flawed. [IMO, there's either something wrong with logic or with language—or both. Somebody fix the whole mess please.] In fact, when it comes to opening or being open, the preposition is almost always to in AmE, whereas BrE is probably mixed, and (sometimes?) there is even a strong preference for at (especially in cases like B above).
I'll close with some of the search results that I mentioned, and leave the rest to others to hash out. Speakers of other dialects are more than welcome to chip in as well!

*

*shut the book for a moment, then open it back up to page one and begin again – COCA

*Students, if you could please open your math books to page two  – COCA

*Open your grammar at page fourteen   – BNC

*every time I took up the book it opened at page 92, although I have never deliberately read that page   – BNC

*I happened to open the Rome Treaty at page 89 of the English text – Hansard Corpus

*his first act on sitting down to breakfast was to open the tabloid at page three, fold it and prop it against the sugar bowl  – BNC

A: In brief, it may make sense to think of the choice of preposition as both based in dialect and based on semantic requirements.
First, I agree with your general findings that the choice of preposition in this context is based in dialect. Other informal sources attest it, like several people in a Word Reference forum post. UK dictionaries also tend to model the open ... at usage: Oxford Dictionaries (at), Oxford Learner's Dictionary (at). This pattern seems to be common enough that many American and UK speakers don't recognize it as a dialect difference until they encounter the other version. It's that subtle.
That said, there are also non-dialect explanations for the choice of preposition. Famed British linguist David Crystal wrote a blog post in 2011 explaining the difference semantically, though his choices (perhaps writing from a UK perspective) are "at" and "on":

A correspondent writes to ask if he can say both 'Open your book on page...' and 'Open your book at page...' Is there a difference?
...
'Opening a book' is an interesting example of overlap between the two perspectives. In one way it's a reference to location - so, 'at'. Most people would open a book 'at' a particular page. But people have a semantic reason for asking someone to open a book at a particular point - so 'on' isn't ruled out. In the first case, they're thinking 'where'; in the second, they're thinking 'what'.

If Crystal were writing from an American perspective, "to" would have a sense of location or position with "open a book," but "at" or "on" would be used in other cases. Perhaps that sense of to would be as you describe in (A), as the preposition in the phrasal verb "go to," or as something like definition 4a for the preposition "to" in the Oxford English Dictionary:

Expressing simple position: At, in (a place, also figurative a condition, etc.).

So in American dialects, there may be a further semantic breakdown between "at" as denoting a static location, "to" denoting a purposeful action toward a location, and "on" as a more literal descriptor of place.
In other words, using Crystal's language, at denotes "where (static)," to denotes "where (purpose or goal)," and on denotes "what." Because UK English already uses "open at," within that system at denotes both kinds of location ("where") without a further distinction except in a phrasal verb where to is already baked in, like "go to."

A: In this context, "Open your books at page 13." if proper, is the minority alternative. "Open your books to page 13." is certainly more common across the major dialects of English.
The action of opening a book describes a movement of sorts towards a specific page, so to would be the better preposition. At, on the other hand, does not typically describe movement, rather it tends to suggest a fixed position.
The chaos becomes clearer when both usages are applied to other nouns:

*

*Open your mind at new events. (Only be receptive during new events)

*Open your mind to new events. (Be receptive to the new events)

*Open the door at the house. (Ambiguous)

*Open the door to the house. (The front door)


text:
Q: window.print on IE7 I am trying to print an HTML page on IE7 but it only prints 1 out of 3 pages. I prints fine on Firefox and IE8. Is there a bug on IE7?
Here is the code:
Click here to print this page.

A: This is a problem with IE7 only. If you clear all your floats before each DIV and inside your print.css make the position property as static for all the DIVs.


text:
Q: HttpWebRequest, How to Send POST Data with Application/JSON Content-Type?
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";

POST data was send (I check using Fiddler) returned from Yahoo :
{"error":{"code":-1003,"detail":"Unsupported Content Type Error","description":"Unsupported Content Type Error"},"code":-1003}

I'm writing Yahoo Messanger client that require application/json; charset=utf-8 as content type, and when I set :

request.ContentType = "application/json; charset=utf-8";

No POST data send, returned from Yahoo :
{"error":{"code":-1005,"detail":"Invalid Argument Error","description":"Invalid Argument Error"},"code":-1005}
UPDATE
I was try to send this 2 values via POST method : presenceState & status.
As stated in Yahoo Messager IM API supported content-type are application/json.
And in my code, if I set content-type to application/json, HttpWebRequest didn't send those 2 values via POST.

A: Take a look on following example
byte[] data = CreateData(value);
var requst = (HttpWebRequest) WebRequest.Create(uri);
requst.Method = "POST";
requst.ContentType = "application/json";
requst.ContentLength = data.Length;
using (Stream stream = requst.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

Where CreateData is
public static byte[] Create<T>(T value)
{
    var serializer = new DataContractJsonSerializer(typeof (T));
    using (var stream = new MemoryStream())
    {
        serializer.WriteObject(stream, value);
        return stream.ToArray();
    }
}

A: I'm super late to the party, but I ended up here trying to figure out what I was messing up, so maybe this will help someone else.
If in your c# code you set your content type and then add some other headers-- something like this:
httpWebRequest.ContentType = @"application/json; charset=utf-8";
WebHeaderCollection headers = new WebHeaderCollection();
headers.Add("Authorization", "Bearer "+oAuthBearerToken);
httpWebRequest.Headers = headers;

what's actually happening, is that when you write to .ContentType, under the hood it's setting Content-Type in your request's WebHeaderCollection. And then you go ahead and overwrite them. This could happen to any header you set like that before you add a bunch of custom ones. If this is what you're doing, just set the custom headers first, and then write to the .Whichever headers.

A: Based on your error, the first one is failing as the content type of the request doesn't match that of what Yahoo is expecting.  This makes sense and your second example is going towards the right path, but based on your posting it seems you are getting a response.  With fiddler you should be able to compare your posting with that of a proper request through the site.  That might help pinpoint where it is going wrong.
But regardless we will need to be seeing a bit more of what you are doing as there is nothing showing hte contents of your post for us to review.

A: i was struggling with the exact same issue.
as noted in the documentation (http://developer.yahoo.com/messenger/guide/ch01s04.html), you need to have an empty body ({}) in the POST request.
using javascript & jQuery, i sent a simple empty object string in the POST body, and that works:
    $.ajax({
        type: 'POST',
        url: 'http://developer.messenger.yahooapis.com/v1/session',
        data: JSON.stringify({ }),
        processData: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader('Authorization', OAuth.getAuthorizationHeader("yahooapis.com", message.parameters));
            xhr.setRequestHeader('Content-Type','application/json; charset=UTF-8');
            xhr.setRequestHeader('X-Yahoo-Msgr-User-Agent','YahooMessenger/1.0 (yourapp; 1.0.0.1)')
        }});

hope that helps.

A: My error maybe is the same your error. The problem is resolved by change type of presenceState to int type not string type.
ClassLogon objLogon = new ClassLogon
  {
    presenceState = ***0***,
    presenceMessage = "I am logn"
  };

I hope you resolve this.


text:
Q: C++ program calculates n times n for the numbers 1 to 9 I have to write a program that calculates n times n for the numbers between 1 and 9 using a function.
The output should be like 1, 4, 27, 256...
I can feel I'm very close to finishing it but I just can't figure out what the problem is, here is the code I wrote:
#include <iostream>
using namespace std;
int result, number, n;

void function1()
{
    result = number;
    for (int x = 1; x < number; x++)
    {
        result = number*result;
    }
}
int main()
{
    for (n = 1; n < 10; n++)
    {
        function1();
        cout << result << endl;
        system("pause");
        return 0;
    }
}

A: Try this :-
#include <iostream>
#include <math>
using namespace std;
int result, number, n;

void function1(int number)
{
  int result;
  result = pow(number,number);
  cout<<result;
}
int main()
{
  for (n = 1; n < 10; n++)
  {
    function1(n);
    system("pause");
  }
  return 0;
}


text:
Q: How to properly call CKEDITOR.plugins.addExternal in Angular 2? In angular 2 (via ng2-ckeditor) I am trying to use CKEditor-ShowProtected-Plugin which is not served from the ckeditor cdn.
That is why I try following:
import { CKEditorModule } from 'ng2-ckeditor';
declare var CKEDITOR:any;
CKEDITOR.plugins.addExternal('showprotected', '../assets/ckeditor-showprotected-plugin', 'plugin.js');

and here is my CKEDITOR_CONFIG:
private CKEDITOR_CONFIG = {
 'extraPlugins': 'showprotected',
  ...
}

however, the CKEDITOR.plugins.addExternal(..) does not seem to be taken into account, because ckeditor is still trying to fetch the ckeditor-showprotected-plugin from cdn:
error_handler.js:54 EXCEPTION: [CKEDITOR.resourceManager.load]
Resource name "showprotected" was not found at "https://cdn.ckeditor.com/4.5.11/full/../assets/ckeditor-showprotected-plugin?t=G87Eplugin.js".

A: I haven't get a chance to implement in Angular 2 ,but it in Angular 1.x do the following changes in config.js
CKEDITOR.editorConfig = function( config ) {

//end of configurations add following lines
 config.extraPlugins += (config.extraPlugins.length == 0 ? '' : ',') + '<your_plugin_name>';
 config.allowedContent = true;

}

and add your plug-in dependencies in ckeditor/plugins/ folder


text:
Q: How can i define the predicate skos:hasTopConcept? My question is short, I am confused about the above predicate. I have used it like this;
ex:Superclass a skos:Concept;
            skos:prefLabel "Superclass";
            skos:altLabel "Parent class";
            skos:hasTopConcept ex:Class, ex:ClassHierarchy .

It seems to me that this predicate is used the same way as Broader, can I get some clarification on this
Thank

A: skos:ConceptScheme describes a knowledge organization system, a container of concepts. Usually, a concept exists in at most one scheme, since for example skos:notation is supposed to provide a value for the concept in its scheme (for equivalent concepts in different schemes, there are specific mapping relations).
Your usage is incorrect, since skos:hasTopConcept is used on a concept scheme, with a concept as its object. It means that the concept is in some way the most generic, the broadest, i.e. there is nothing broader in that scheme (but there could be in general, in other schemes). The inverse is skos:topConceptOf, which implies skos:inScheme.
Assuming your scheme is used for denoting relations between specific classes, you probably intended to model it in this way:
ex:ClassRelations a skos:ConceptScheme ;
  skos:hasTopConcept ex:Class .

ex:Class a skos:Concept ;
  skos:topConceptOf ex:ClassRelations . # redundant since the inverse was already specified (inScheme is sufficient)

ex:Superclass a skos:Concept ;
  skos:broader ex:Class .

However I don't think this is a good use of SKOS here. We are modelling class relations here, and while "is superclass of" makes sense, it is not more specific than "is class of", since that makes no sense. Specifying a plain old RDF property works just as well.
Going with the "class hierarchy" concepts in some programming language, it would be more suited for an actual hierarchy, like types, reference/value types, interfaces etc., or specific classes/types like Object, String, Collection, List etc.


text:
Q: in java why so much date and time handling function In java why so much. date and time handling features
eg
java.util , java.sql , calendar , java 8 Date and Time

*

*can we use java.util to save in the database. if so then why java.sql introduced

*while inserting into database should we convert the java.util to java.sql and then save. if so then what will be benefits of it

A: tl;dr

*

*Use only java.time classes.

*Never use date-time classes in the java.util and java.sql
packages.

You asked:

can we use java.util to save in the database. if so then why java.sql introduced

Use neither. Both are now outmoded by the java.time classes.
And you asked:

while inserting into database should we convert the java.util to java.sql and then save. if so then what will be benefits of it

Use neither. Use only the java.time classes.
myPreparedStatement.setObject( … , myOffsetDatetime ) ;

…and:
OffsetDateTime myOffsetDateTime = myResultSet.getObject( … , OffsetDateTime.class ) ;

JSR 310
You asked:

In java why so much. date and time handling features

The date-time classes in the java.util and java.sql packages are terribly flawed in their design. They were built decades ago by people who did not understand the complexities and subtleties of date-time handling.
As a whole the information technology industry largely ignored mastering the details of date-time handling in programming. Quite astounding that so many decades passed with no real complete well-designed solution.
In 2014, the JCP community, including Sun/Oracle, voted unanimously to adopt JSR 310. The java.time classes became part of Java 8 and later. This framework is now leading the industry.
Adopting JSR 310 meant that the date-time classes in the java.util and java.sql packages became legacy, supplanted entirely by the java.time classes. At one point the legacy classes were marked for deprecation, then undone for reasons undisclosed.
Converting
No need for you to ever use those terrible legacy classes again. Avoid java.util.Date, Calendar, GregorianCalendar, SimpleDateFormat, java.sql.Date, and so on.
If interoperating with old code not yet updated for java.time, you can convert. Call the new to… and from… methods added to the old classes.
Back-ports
For Java 6 & 7, use the back-port library, ThreeTen-Backport. Further adapted for early Android (before 26) in the ThreeTeABP library.
JDBC
JDBC 4.2 and later requires support for exchanging java.time objects with the database. Your JDBC driver has likely been updated by now.
Learn about methods such as PreparedStatement::setObject and ResultSet::getObject.
For a moment, that is, for columns of a data type akin to the SQL-standard type TIMESTAMP WITH TIME ZONE, support for java.time.OffsetDateTime is required. Oddly, support for the more commonly used Instant and ZonedDateTime is not addressed in the JDBC specification. Your driver may or may not support those types. If not, you can easily convert by calling the at…, to…, and with… methods. To make your JDBC code more portable across drivers, exchange only OffsetDateTime objects, and convert to/from Instant/ZonedDateTime as needed.
OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime ) ;
ZoneId z = ZoneId.of( "Africa/Casablanca" ) ;
ZonedDate zdt = odt.atZoneSameInstant( z ) ;

For columns with only a date and a time-of-day but lacking the context of a time zone or an offset-from-UTC (therefore not a moment), that is, for a data-type akin to the SQL-standard TIMESTAMP WITHOUT TIME ZONE, use java.time.LocalDateTime.

Evolution
The Joda-Time project is the predecessor to java.time. Lessons learned there were used in designing java.time. Joda-Time is now in maintenance-mode.
Joda-Time, JSR 310, java.time, ThreeTen-Backport, and ThreeTen-Extra are all led by the same man, Stephen Colebourne.

A: *

*java.util.Date can't be used to save in database, because there are 3 different data types on database side: DATE, TIME and TIMESPAMP. To reflect these 3 types the java.sql.Date, java.sql.Time and java.sql.Timespamp were introduced respectively

*Java 8 time API is recommended, there's no necessity anymore to use legacy and to deal with a converting between java.util and java.sql


text:
Q: JetBrains RubyMine 3.2.4 debugger not working Running with Ruby 1.9.2
The IDE complains that The gem ruby-debug-base19x is required and offers to install it.
However, upon attempting to install it it displays the message

Failed to install gems. Following gems were not installed: C:/Program
  Files (x86)/JetBrains/RubyMine
  3.2.4/rb/gems/ruby-debug-base19x-0.11.30.pre2.gem: Error installing ruby-debug-base19x-0.11.30.pre2.gem: The 'linecache19' native gem
  requires installed build tools. Please update your PATH to include
  build tools or download the DevKit from
  'http://rubyinstaller.org/downloads' and follow the instructions at
  'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
  C:/Program Files (x86)/JetBrains/RubyMine
  3.2.4/rb/gems/ruby-debug-ide-0.4.17.beta8.gem: Error installing ruby-debug-ide-0.4.17.beta8.gem: The 'ruby-debug-ide' native gem
  requires installed build tools. Please update your PATH to include
  build tools or download the DevKit from
  'http://rubyinstaller.org/downloads' and follow the instructions at
  'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'
  linecache19 (0.5.12): Error installing linecache19: The 'linecache19'
  native gem requires installed build tools. Please update your PATH to
  include build tools or download the DevKit from
  'http://rubyinstaller.org/downloads' and follow the instructions at
  'http://github.com/oneclick/rubyinstaller/wiki/Development-Kit'

I followed its advice to download the DevKit - but the DevKit upon attempting to install, said that it was already correctly installed as part of Ruby.
Any advice?

A: The problem is not specific to RubyMine, I'd try to reinstall Ruby and DevKit from scratch.
Verify that DevKit actually works using a test from the installation guide:
gem install rdiscount --platform=ruby
ruby -rubygems -e "require 'rdiscount'; puts RDiscount.new('**Hello RubyInstaller**').to_html"

If it works fine, try to install the debug gems manually from the console using the following commands:
gem install ruby-debug-base19x --pre
gem install ruby-debug-ide --pre

Post logs, provide more details if it still doesn't work for you.

A: The gem that rubymine debugger installs by itself conflicts with the existing debug gem in the gemset. Uninstall the existing debug gems, you can get a list by running gem list | grep debug and let rubymine install its own version. Also make sure that you do not have a debug gem mentioned in the Gemfile and also there should not be any debug gem in the global gemset.

A: I had the same problem.
i was able to get it working by uninstalling and reinstalling RubyMine. Then everything worked perfectly, as expected.

A: There is an open issue on this at the RubyMine forum. The answer by Roman Melnik worked for me (but my environment is Mac OS).


text:
Q: Trim Image to Content Box Ignoring Text at Top/Bottom? The Question Title May sound basic but for me it's not :D
I want to crop out the image from the dashed line to the next black border at bottom from the image.
Demo Image
The Content Box (The Outer Box) is not at a fixed position. It varies in height width and top.
The text at top and bottom are not always there sometimes they exist some times they don't.
So to detect the dashed line i started using openCV match template.
To Escape from finding the bottom line (the black line at bottom next to the dashed line) work I thought of trimming the image to content (I just needed to crop the image from top so I don't have to find the height of image from dashed line to bottom border) and for that I used Sharp Library.
But the problem is if the text exists the trimming is done just to the text but I want the trimming to be done to the black bordered box.
The text isn't extractable sometimes so can't verify if it's there or not.
How can i trim the image to border while ignoring the Text at Top and Bottom ?
Can't use OpenCV multiple times (to detect the borderBox) as the function will be deployed at firebase functions and the cropping needs to be done under 5 seconds. the detection of the dashed line itself is taking 8 seconds
Code
/**
 * The Idea is to crop the image to content/Border Box
 * Then Find the Dashed Line with OpenCV
 * OpenCV will give the X (Position from Top) Value of the Dashed Line.
 * Using that X value with Sharp Library We'll Crop the Image from TOP.
 *
 * But The Problem is The Trim to Content won't work if there is other
 * Content (Like Text in my Case) in the path from corners to the Content Box.
 */

// Trimming to Content / Bordered Box
sharp(filePath).trim(50).toBuffer()
    .then(async (buffer) => {

        /**
         * The Image Here is Trimmed to The Content / Border Box
         * Only if there is no text on the corners or at the
         * Top and Bottom of the image.
         *
         * How to Ignore them so the Trimming to Content Can
         * Be done right ?
         */

        // Stored Trimmed Image as sharp Instance for later Use
        let trimmedImage = sharp(buffer);

        let { width, height } = await trimmedImage.metadata();

        // Template Matching
        let findBuffer = await sharp("./dashedTemplate.jpeg").resize(width).toBuffer();

        let img1 = await loadImage(buffer);
        let img2 = await loadImage(findBuffer);

        img1 = cv.imread(img1);
        img2 = cv.imread(img2);

        let canIn = createCanvas();
        cv.imshow(canIn, img1);

        let canFi = createCanvas();
        cv.imshow(canFi, img2);

        let src = cv.imread(canIn);
        let temp = cv.imread(canFi);

        let dest = new cv.Mat();
        let mask = new cv.Mat();

        cv.matchTemplate(src, temp, dest, cv.TM_CCOEFF_NORMED, mask);

        let result = cv.minMaxLoc(dest, mask);

        let maxPoint = result.maxLoc;
        src.delete(); dest.delete(); mask.delete();

        // Position from top where the ExepectImaged was found
        let cvTop;

        cvTop = maxPoint.y + 8;

        // Save the final Image.
        trimmedImage
        .extract({ top: cvTop, left: 0, width: width, height: (height - cvTop) })
        .toFile("./output/" + path.basename(filePath, ".jpeg") + "_cropped.jpeg");
    })


text:
Q: Possible to code a search box that searches for a specific tag in a div and then shows it / hides others? With out making a database backend, is it possible to somehow create a search box on an html / css page, probably with jquery for everything, that say I have four div boxes on the page, and each div box contains certain flavor text or keywords. Is it possible to make a search box that when a keyword is searched for, it then hides the other div boxes that don't contain that keyword, and then shows only those that do.
I am aware and know of .hide / .show /.toggle in jquery, but how would one begin to code a simple search box that would perform that kind of functionality? Anyone have any ideas or general direction?

A: $("#search").on("keyup", function() {
    var key = this.value;
    $(".tosearch").each(function() {
       var $this = $(this);
       $this.toggle($(this).text().indexOf(key) >= 0);
    });
});

Demo: http://jsfiddle.net/upsgk/
Note that this performs a case-sensitive search. To ignore case you'll need a couple of calls to toLowerCase(). E.g. http://jsfiddle.net/upsgk/1/

A: Here's a list of the key components you'll need:

*

*inputtxt.value (jQuery: $("input").val()): returns the value written inside a text input.

*elm.innerHTML (jQuery: $("elm").html()): returns a string containing the contents of an element.

*str.indexOf(pattern): returns the index of the first occurrence of pattern in str. If pattern doesn't exist instr, then .indexOf() returns -1.

Putting those together, you get something like this: little link. The code is pretty self-explaining, but here's a commented version of the JavaScript part:
$("#search").on("keydown keyup keypress change", function() { //when the textbox is changed
    var query = $("#search").val(); //save its content
    $(".box").each(function() { //for each box
        var cur = $(this); //get the current box
        if(cur.html().indexOf(query) == -1) { //see if the current box contains the query
            cur.hide("fast"); //it doesn't; hide it
        }
        else {
            cur.show("fast"); //it does, show it
        }
    });
});

A: I do not want to do the project for you but here is an idea to start with
var query= $('#search').val();
var str = $('#div1').val();

if (str.indexOf(query) >= 0){
   // display box
}
else{
  // hide box
}

A: Yes it is possible.

*

*First listen to the search box prevent defautl using
$('input[type="submit"]').click(function(e){e.preventDefault();});

*Program your code to get search box value.

*Hide all divs $("div").css("display","none");

*Show all divs that have the id $("#"+valueOfBox").css("display","true");


text:
Q: Add DELETE to query that returns duplicate records | SQL Server i need your help.
I've this query that detect a duplex records:
SELECT
    name, email, COUNT(*)
FROM
    users
GROUP BY
    name, email
HAVING
    COUNT(*) > 1

So i need to delete the results, so i've try this:
Delete FROM
    users
GROUP BY
    name, email
HAVING
    COUNT(*) > 1

but doesn't work. Could tell me an help ? thank.

A: Try this query:
DELETE
FROM users
WHERE ID NOT IN
(SELECT MAX(ID)
FROM users
GROUP BY name, email)

A: Since there is no ID Column (Primary Key) in your question, assuming there is no ID column.
So below CTE will delete duplicate records.
;WITH CTE AS (
SELECT name
, email
, ROW_NUMBER() Over(Partition by name, email Order by(Select 1)) as Sno
FROM users
)
DELETE FROM CTE WHERE SNO>1

A: I'm assuming you want to JUST remove the duplicate rows not all the rows relating to the duplicate rows.
You can use ROW_NUMBER here.  You haven't provided the whole schema for the USERS table so here's an example
CREATE TABLE dbo.Users(
     Id INT IDENTITY(1,1)
    ,[Name] NVARCHAR(50)
    ,eMail NVARCHAR(50)
    ,DateCreated DATETIME
)

SELECT
     Id
    ,[Name]
    ,eMail
    ,DateCreated
    ,RN = ROW_NUMBER()OVER(PARTITION BY Name, eMail ORDER BY DateCreated ASC)
FROM dbo.Users

you can change this query to a Common Table Expression and then you can DELETE from it
;WITH cteDups
AS(
    SELECT
         Id
        ,[Name]
        ,eMail
        ,DateCreated
        ,RN = ROW_NUMBER()OVER(PARTITION BY Name, eMail ORDER BY DateCreated ASC)
    FROM dbo.Users
)
DELETE FROM cteDups WHERE RN > 1

The RN > 1 will remove the duplicate records only


text:
Q: Use container's environment variable for a command lie I would like to use some environment variables in a bash script that contains :
#!/usr/bin/env bash
docker-compose exec apache bash -c "\
    printenv | grep BLACKFIRE\
    && blackfire-agent --register --server-id=$BLACKFIRE_SERVER_ID --server-token=$BLACKFIRE_SERVER_TOKEN \
    && /etc/init.d/blackfire-agent restart"
echo "Blackfire agent configured !"

I pass the variable from my .env :
BLACKFIRE_SERVER_ID=xxxxx
BLACKFIRE_SERVER_TOKEN=xxxxx
BLACKFIRE_CLIENT_ID=xxxxx
BLACKFIRE_CLIENT_TOKEN=xxxxx

using docker-compose.yml
environment:
  - DAMART_ENV=dev
  - BLACKFIRE_SERVER_ID=${BLACKFIRE_SERVER_ID}
  - BLACKFIRE_SERVER_TOKEN=${BLACKFIRE_SERVER_TOKEN}
  - BLACKFIRE_CLIENT_ID=${BLACKFIRE_CLIENT_ID}
  - BLACKFIRE_CLIENT_TOKEN=${BLACKFIRE_CLIENT_TOKEN}

The apache container has the environment variables (here is the result of printenv)

If I change the variables by their values it works but I don't want to use them directly in this script.
How should I call the variables for them to work.

A: The code repository usually has a function to store secret keys and environment tokens.  For instance, github secrets can be kept in https://github.com/user/repo/settings/secrets/actions for your actions or https://github.com/user/repo/settings/secrets/codespaces/new for the repo.

A: The problem comes from the use of " (double quotes) that made the string to be interpreted not by the container but by the machine running the docker exec. This machine did not have the env variables as they are set in the container.
Replace with ' (simple quotes) make the script to use the environment variables set in the container.
docker-compose exec apache bash -c '\
   blackfire-agent --register --server-id=$BLACKFIRE_SERVER_ID --server-token=$BLACKFIRE_SERVER_TOKEN \
   && /etc/init.d/blackfire-agent restart'


text:
Q: Redux Toolkit Query not invalidating tags and cache in non - debug or production mode In my application when a user is logged in as a guest an authorization token is stored in Async Storage which is then used to fetch data from the API.
When the Guest logs into their account, The token is updated in Async Storage and is also updated in RTK Query
The API was created using createApi in Redux Toolkit
The base query of the createApi is
baseQuery: fetchBaseQuery({
    baseUrl: API_HOST,
    prepareHeaders: async headers => {
      const token = await AsyncStorage.getItem('token');
      console.log('Preparing Headers', token);
      if (token) {
        headers.set('authorization', `Token ${token}`);
      }
      return headers;
    },
    refetchOnMountOrArgChange: 30,
  }),

After the user signed in the headers of the RTK Query is changed to the updated token
Preparing Headers f770b8635dc3e5613a648fc****************
I use invalidateTags from createAPI to invalidate the cache data
dispatch(commonApi.util.invalidateTags(ALL_TAG_TYPES));
Here ALL_TAG_TYPES is an array of all tag types in the application
export const ALL_TAG_TYPES = [
  TAG_USER_AUTH,
  TAG_HOME_DATA,
  TAG_COURSE_DATA,
  TAG_BUNDLE_DATA,
  TAG_LIVE_CLASS_DATA,
  TAG_USER_ALL_DATA,
  TAG_USER_COURSE_DATA,
  TAG_USER_PROFILE_DATA,
  TAG_USER_WORKBOOK_DATA,
  TAG_PAYMENT_DATA,
  TAG_WORKSHOP_DATA,
]

The cache is invalidated in Debug Mode , Whereas fails to update in non - debug / production mode
React Redux version used is 7.2.5
Redux js toolkit version used is 1.6.1
The header of the query is changed whereas the cache data isn't invalidated

A: The above error was because Redux doesn't deep check objects in Production mode to enable faster invalidation.
Since the schema of the JSON didn't change the cache was not invalidated in production
You need to pass serializableCheck and  immutableCheck as true in your middleware to enable deep objects check in production in debug mode they are on by default
This might affect the speed of checks in production in case of large json objects. Hence they are disabled by default in production.
export const store = configureStore({
  reducer: {
    auth: authReducer,
    [commonApi.reducerPath]: commonApi.reducer,
  },
  middleware: getDefaultMiddleware =>
    getDefaultMiddleware({
      serializableCheck: true,
      immutableCheck: true,
    }).concat([
      commonApi.middleware,
      immutableInvariantMiddleware,
      rtkQueryErrorLogger,
    ]),
});

Redux Docs on Default Middleware - https://redux-toolkit.js.org/api/getDefaultMiddleware#included-default-middleware


text:
Q: return array of objects based on object of keywords I have this object containing data for each keyword:
const a = {
  word1: { mains: [ 5 ], secondaries: [1, 22, 50] },
  word2: { mains: [ 5, 66 ], secondaries: [1] },
  word3: { mains: [ 5 ], secondaries: [1] },
}

And I want this array of objects containing data of the above object sorted based on length of mains array and secondaries array for each keyword, I mean :
mains.length + secondaries.length

Here is the desired output:
[

  { keyword: 'word3', mains: [ 5 ], secondaries: [1] }, // length of mains and secondaries = 2
  { keyword: 'word2', mains: [ 5, 66 ], secondaries: [1] }, // length of mains and secondaries = 3
  { keyword: 'word1', mains: [ 5 ], secondaries: [1, 22, 50] }, // length of mains and secondaries = 4

]

What is the proper solution to achieve such a functionality?

A: simply

const objA =
  { word1: { mains: [ 5] ,     secondaries: [ 1, 22, 50] }
  , word2: { mains: [ 5, 66] , secondaries: [ 1]         }
  , word3: { mains: [ 5] ,     secondaries: [ 1]         }
  }

const sumLen = ([_, {mains,secondaries}]) => mains.length + secondaries.length ;

const result = Object.entries(objA)
                .sort((a,b)=>sumLen(a)-sumLen(b))
                .map(([keyword,obj])=>({keyword, ...obj}))

console.log( result )
.as-console-wrapper { max-height: 100% !important; top: 0 }

A: Here a "one-liner" solution:

const a = {
  word1: { mains: [5], secondaries: [1, 22, 50] },
  word2: { mains: [5, 66], secondaries: [1] },
  word3: { mains: [5], secondaries: [1] }
}

const result = Object.entries(a).map(
  ([keyword, item]) => ({keyword, ...item})
).sort(
  (a, b) => (a.mains.length + a.secondaries.length) - (b.mains.length + b.secondaries.length)
)

console.log(result);

This will first use map() to transform a object entries into an array of objects with keyword property, then sort() this based on the sums of lengths.

A: const a = {
    word1: { mains: [ 5 ], secondaries: [1, 22, 50] },
    word2: { mains: [ 5, 66 ], secondaries: [1] },
    word3: { mains: [ 5 ], secondaries: [1] },
};

let array = [];
for (let prop in a) {
    let newProp = {keyword: prop};
    array.push(Object.assign(newProp, a[prop]));
}

array.sort((a, b) => {
    return (a.mains.length + a.secondaries.length) -
            (b.mains.length + b.secondaries.length);
});


text:
Q: Using JQuery and JSON to consume Asp.net Server-Side Asynchronous Web Methods I defined two webservices calls in ASP.NET:
 1.BeginLengthyProcedure and EndLengthyProcedure (Asynchronous web method)
 2.LengthProcedureSync
namespace ServiceDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class AsyncWebService : System.Web.Services.WebService
{
    public delegate string LengthyProcedureAsyncStub(int milliseconds);

    public string LengthyProcedure(int milliseconds)
    {
        System.Threading.Thread.Sleep(milliseconds);
        return "SuccessAsync";
    }

    public class MyState
    {
        public object previousState;
        public LengthyProcedureAsyncStub asyncStub;
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public IAsyncResult BeginLengthyProcedure(int milliseconds, AsyncCallback cb, object s)
    {
        LengthyProcedureAsyncStub stub = new LengthyProcedureAsyncStub(LengthyProcedure);
        MyState ms = new MyState();
        ms.previousState = s;
        ms.asyncStub = stub;
        return stub.BeginInvoke(milliseconds, cb, ms);
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string EndLengthyProcedure(IAsyncResult call)
    {
        MyState ms = (MyState)call.AsyncState;
        string res = ms.asyncStub.EndInvoke(call);
        return res;
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string LengthyProcedureSync(int milliseconds)
    {
        System.Threading.Thread.Sleep(milliseconds);
        return "SuccessSync";
    }
}
}

Then I consumed them using JQuery, I don't want to use ASP.NET AJAX. LengthProcedureSync worked fine, but LenghtyProcudure didn't work. Is there anything I missed?
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>

<script type="text/javascript">
    function testJson() {
        $.ajax({
            type: "POST",
            //Didn't work
            url: "AsyncWebService.asmx/LengthyProcedure",
            //Work
            //url: "AsyncWebService.asmx/LengthyProcedureSync",
            data: "{'milliseconds':'2000'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                $("#jsonResponse").html(msg.d);
            },
            error: function (msg) {

            }

        });
    };

</script>

A: Unfortunately, the .NET Framework's ASP.NET AJAX web service handler (which is used for JSON) does not provide support for asynchronous web service calls whereas the default ASP.NET web service handler does. There is an excellent book "Building a Web 2.0 Portal with ASP.NET 3.5" written by Omar AL Zabir describing a workaround for this shortcoming of the ASP.NET AJAX web service handler (see chapter 7, page 177). There is also a sample chapter available on MSDN. Hope, this helps!

A: change this
public string LengthyProcedure(int milliseconds)
     {
         System.Threading.Thread.Sleep(milliseconds);
         return "SuccessAsync";
     }

to this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string LengthyProcedure(int milliseconds)
     {
           System.Threading.Thread.Sleep(milliseconds);
           return "SuccessAsync";
     }


text:
Q: Extract numbers from multiple strings in an array and then sum - Excel I have an array as seen in this screenshot:

It is dynamically created from stacks of data above them in the column.
What I would like to do is work with the numbers you see totaled in these cells without using helper cells. Is that possible?
For example, I would like to find the average number of lines, or I would like to find the average weight or volume (cft=cubic feet).
I can figure out a way to do this using helper cells, easily enough, but can I use one formula to parse the data and then compile it all in one single cell?
If the answer is "no", I will accept that as a viable response and mark it as such if nothing else is forthcoming.

A: Just for the lines, assuming you have the text "lines" with the number, you could use:
=left(A1,find(" ",A1,1)-1)

for each cell and then calculate from there... Assumed the data starts in cell A1...
Sometimes the4 result is not recognized as a number so:
=left(A1,find(" ",A1,1)-1)*1

can change that..

A: You can use array formula like this and drag it down.
Use Evaluate formula option to see how it works in steps , alternatively you can select the part of the formula and press F9 to see the result of the selected part.

=AVERAGE(IFERROR(VALUE(LEFT(B31:K31,SEARCH(" ",B31:K31)-1)),B31:K31))

A: Building off the response from @Solar Mike, I discovered I can embed an array inside of the LEFT function, and if you enter the formula as an array formula, you can make this work.
The solution that works for this: =SUM(LEFT(B31:L31,FIND(" ",B31:L31,1)-1)*1)
It needs to be entered as an array formula by using Ctrl+Shift+Enter, this is what puts the "curly braces" around the formula, and you know you've done it correctly {}
Thank you @Solar Mike, I learned something new today!

A: I would suggest that instead of building a text string as the answer in the cells and then having to use complicated array formulas to remove the added text, you apply custom formatting,
for example #,##0 "lines"
Then you can just use standard AVERAGE etc formulas.


text:
Q: Passing argument to thread by std::ref in slows down execution? I have a question.
I was today playing with threads. I wanted to make sure that on 2-core processor, when I split a task into 2 parts I will get a near 2x increase in execution time (no locks involved here).
I wanted to use simple mechanism without any fancy things like async etc., just a simple thread running a function executing some very simple caclulations.
I wrote a function summing integers from a given range and saving the result in the ouptput parameter passed by reference.
I added measuring time and run the example with 1 thread.
Then I changed the program to run the same function in 2 separate threads, with split range. Of course in order to return the result to the main thread by reference I had to use std::ref (to be able to create a thread). I was much surpriced when I noticed that the execution time of the program almost did not change at all.
Then I created a new function doing the same but acepting reference_wrapper and run it in the 1-thread program. The execution time now was 2x the time of the program with 2 threads. So I somehow confirmed that the 2-thread program like this may get 2x speed-up compared to 1-thread program, when they both use std::ref. But the bad thing is that I can run 1-thread program without bothering of using std::ref and this program runs as fast as 2-thread program with std::ref.
Below I paste the program containing all 3 options and the output on my 2-core machine.
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>

using namespace std;
using namespace std::chrono;

int work(uint64_t b, uint64_t e, uint64_t& sum)
{
    for (int i = b; i < e; ++i)
    {
        sum += i;
    }
}

int work1(uint64_t b, uint64_t e, std::reference_wrapper<uint64_t> sum)
{
    for (int i = b; i < e; ++i)
    {
        sum += i;
    }
}

int main() {
    uint64_t sum = 0u;
    high_resolution_clock::time_point t1 = high_resolution_clock::now();
    work(0, 1000000000000000000, sum);
    high_resolution_clock::time_point t2 = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>( t2 - t1 ).count();
    cout << "one thread, duration = " << duration << endl;

    sum = 0u;
    t1 = high_resolution_clock::now();
    work1(0, 1000000000000000000, std::ref(sum));
    t2 = high_resolution_clock::now();
    duration = duration_cast<microseconds>( t2 - t1 ).count();
    cout << "one thread, std::ref, duration = " << duration << endl;

    uint64_t sum21 = 0u;
    uint64_t sum22 = 0u;
    t1 = high_resolution_clock::now();
    thread th1(work, 0, 500000000000000000, std::ref(sum21));
    thread th2(work, 500000000000000000, 1000000000000000000, std::ref(sum22));
    th1.join();
    th2.join();
    sum = sum21 + sum22;
    t2 = high_resolution_clock::now();
    duration = duration_cast<microseconds>( t2 - t1 ).count();
    cout << "two threads, std::ref, duration = " << duration << endl;

    return 0;
}

Results:
one thread, duration = 7777627
one thread, std::ref, duration = 17021098
two threads, std::ref, duration = 7426095

My question is: why does std::ref slow things down so much?
Regards
YK