Q: Dict Update method only adds last value I have the following code (link here)
I have looked at similar posts and examples online but have not been able to understand / resolve the issue on why .update only adds the last value to the dictionary
import json

def main():
    jsonData = {'CompanyId': '320193', 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents':
        [{'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2020-09-26'}, 'value': '39789000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2019-09-28'}, 'value': '50224000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2018-09-29'}, 'value': '25913000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'instant': '2021-09-25'}, 'value': '35929000000'}],

        'NetIncomeLoss': [{'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'value': '94680000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'}, 'value': '57411000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'}, 'value': '55256000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2020-09-27', 'endDate': '2021-09-25'}, 'segment':
        {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '94680000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2019-09-29', 'endDate': '2020-09-26'},
        'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'}, 'value': '57411000000'},
        {'decimals': '-6', 'unitRef': 'usd', 'period': {'startDate': '2018-09-30', 'endDate': '2019-09-28'},
        'segment': {'dimension': 'us-gaap:StatementEquityComponentsAxis', 'value': 'us-gaap:RetainedEarningsMember'},
        'value': '55256000000'}]}

    jsonDump = json.dumps(jsonData)
    actualJson = json.loads(jsonDump)
    finalJson = fixData(actualJson)
    print(finalJson)

def fixData(jsonData):
    jsonDump = json.dumps(jsonData)
    actualJson = json.loads(jsonDump)
    finalObject = {}
    finalObject['CompanyId'] = actualJson.get("CompanyId")
    CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents = actualJson.get(
        "CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents")
    one = dataRepeat(CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents,"CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents")
    finalObject.update(one)
    NetIncomeLoss = actualJson.get("NetIncomeLoss")
    two = dataRepeat(NetIncomeLoss, "NetIncomeLoss")
    finalObject.update(two)
    return finalObject

def dataRepeat(item, property):
    final = {}
    test = {}
    mList = []
    super_dict = {}
    for i in item:
        decimals = i.get("decimals")
        unitRef = i.get("unitRef")
        if (i.get("period").get("startDate")):
            startDate = i.get("period").get("startDate")
        else:
            startDate = None
        if (i.get("period").get("endDate")):
            endDate = i.get("period").get("endDate")
        else:
            endDate = None
        if (i.get("period").get("instant")):
            instant = i.get("period").get("instant")
        else:
            instant = None
        propertyValue = i.get("value")

        final['Decimals'] = decimals
        final['UnitRef'] = unitRef
        final['StartDate'] = startDate
        final['EndDate'] = endDate
        final['Instant'] = instant
        final[f"{property}"] = propertyValue

        mList.append({"Decimals": final['Decimals']}),
        mList.append({"UnitRef": final['UnitRef']}),
        mList.append({"StartDate": final['StartDate']}),
        mList.append({"EndDate": final['EndDate']}),
        mList.append({"Instant": final['Instant']}),
        mList.append({f"{property}": final[f"{property}"]})

#    ou = {}
#    for d in mList:
#        for key, value in d.items():
#            ou.setdefault(key, []).append(value)
#    return ou
    ou = {}
    for d in mList:
        ou.update(d)
    return ou

main()

What I get :
{'CompanyId': '320193', 'Decimals': '-6', 'UnitRef': 'usd', 'StartDate': '2018-09-30', 'EndDate': '2019-09-28', 'Instant': None, 'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '35929000000', 'NetIncomeLoss': '55256000000'}

vs Entire Data:
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': None}
{'EndDate': None}
{'Instant': '2020-09-26'}
{'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '39789000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': None}
{'EndDate': None}
{'Instant': '2019-09-28'}
{'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '50224000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': None}
{'EndDate': None}
{'Instant': '2018-09-29'}
{'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '25913000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': None}
{'EndDate': None}
{'Instant': '2021-09-25'}
{'CashCashEquivalentsRestrictedCashAndRestrictedCashEquivalents': '35929000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': '2020-09-27'}
{'EndDate': '2021-09-25'}
{'Instant': None}
{'NetIncomeLoss': '94680000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': '2019-09-29'}
{'EndDate': '2020-09-26'}
{'Instant': None}
{'NetIncomeLoss': '57411000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': '2018-09-30'}
{'EndDate': '2019-09-28'}
{'Instant': None}
{'NetIncomeLoss': '55256000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': '2020-09-27'}
{'EndDate': '2021-09-25'}
{'Instant': None}
{'NetIncomeLoss': '94680000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': '2019-09-29'}
{'EndDate': '2020-09-26'}
{'Instant': None}
{'NetIncomeLoss': '57411000000'}
{'Decimals': '-6'}
{'UnitRef': 'usd'}
{'StartDate': '2018-09-30'}
{'EndDate': '2019-09-28'}
{'Instant': None}
{'NetIncomeLoss': '55256000000'}

Expected output would be where the finalJson contains all the data

A: You have the lot of inefficiences in code that is detracting from an issue at hand.
Ex:
jsonDump = json.dumps(jsonData)
    actualJson = json.loads(jsonDump)

What is the point? To equal just as:
actualJson = jsonData

Or even:
actualJson = jsonData.copy()

Next:
finalObject = {}
    finalObject['CompanyId'] = actualJson.get("CompanyId")

This can be to:
finalObject = {'CompanyId' :  actualJson.get("CompanyId") }

Then:
if (i.get("period").get("instant")):

But i.get if not there, is None, so I think for in case your error, then don't handle as such:
if (i["period"].get("instant")):

And then also:

f"{property}"

Specifically, here:
mList.append({f"{property}": final[f"{property}"]})

But what is property? I think it's just a string:

property

So:
mList.append({property: final[property]})

A: What I see from your data:
We know that a dictionary does not have duplicate keys:
I want to show with an example:
d={}

list_of_dict=[{1:'a',2:'b'},{1:'c'}]

Now, when you apply update:
for x in list_of_dict:
  d.update(x)

Now, you will get:
#{1: 'c', 2: 'b'}

You see update() will override the the value of key 1 from 'a' to 'c'.
This is what exactly happening in your code


Q: Is every model of MK (Morse-Kelley-Set-Theory) well-founded? On page 2 in "The Hyperuniverse Project and Maximality" is written:

The models $\mathcal{M}$ of MK are of the form $\langle M, \in, \mathcal{C} \rangle$, where $M$ is transitive model of ZFC, $\mathcal{C}$ the family of classes of $\mathcal{M}$ (i.e. every element of $\mathcal{C}$ is a subset of $M$) and $\in$ is the standard $\in$ relation.

Why can we assume that $M$  is transitive? If we knew, that every model of MK is well-founded, we could use the Mostowski collapse lemma. But is this the case?
Remark: In the book MK is formulated in a two-sorted version (have a look at the link).

A: As Caicedo pointed out in the comments by "models" only "standard models" are meant. The argument that there are illfounded models of MK is exactly the same as for ZFC (e.g. here). If we assume the axiom of foundation at the background level such an illfounded model is necessarily not isomorphic to a transitive model. If we don't have foundation in the metatheory this is not always the case (see this question).


Q: C++ Segmentation Fault Confusing {CLOSED} I know that Seg Sault is caused by accessing data that isn't yours, but I don't see why this small bit of code to assign values to and print a 9X9 2d array returns Seg Fault. Please help!
The code looks like this:
using namespace std;
#include <iostream>;
#include <string>;
string output = "|";
string topBoard[9][9];

int main() {
    for (int i = 0; i < 9; i++) {
        for (int ii = 0; ii < 9; ii++) {
            topBoard[i][ii] = "empty";
        }
    }
    for (int ii = 0; ii < 9; ii++) {
        cout << "-----------------------------------------------------------------";
        output = "|";
        for (int i = 0; i < 9; i++) {
            output = output + topBoard[ii][i] + "|";
        }
        cout << output;
    }
    return(0);
};

Output:
Segmentation Fault
Process exited with code 139
Anyone have any idea why this might happen?
EDIT: I use cloud9 if anyone wants to check it out, works great for working on your stuff just about anywhere.
Further Editing:
here is the code with all your edits:
using namespace std;
#include <iostream>
#include <string>
const int Height = 9;
const int Width = 9;
string output = "|";
string topBoard[Height][Width];

int main() {
    for (int i = 0; i < Height; i++) {
        for (int ii = 0; ii < Width; ii++) {
            topBoard[i][ii] = "empty";
        }
    }
    for (int ii = 0; ii < Height; ii++) {
        cout << "-----------------------------------------------------------------";
        output = "|";
        for (int i = 0; i < Width; i++) {
            output = output + topBoard[ii][i] + "|";
        }
        cout << output;
        }
        return(0);
}

A: This code runs perfectly fine in Visual Studio 2013. Only change is that the last semicolon needs to come after the return statement not after }. Here is the output:
-----------------------------------------------------------------|empty|empty|em
pty|empty|empty|empty|empty|empty|empty|empty|----------------------------------
-------------------------------|empty|empty|empty|empty|empty|empty|empty|empty|
empty|empty|-----------------------------------------------------------------|em
pty|empty|empty|empty|empty|empty|empty|empty|empty|empty|----------------------
-------------------------------------------|empty|empty|empty|empty|empty|empty|
empty|empty|empty|empty|--------------------------------------------------------
---------|empty|empty|empty|empty|empty|empty|empty|empty|empty|empty|----------
-------------------------------------------------------|empty|empty|empty|empty|
empty|empty|empty|empty|empty|empty|--------------------------------------------
---------------------|empty|empty|empty|empty|empty|empty|empty|empty|empty|empt
y|-----------------------------------------------------------------|empty|empty|
empty|empty|empty|empty|empty|empty|empty|empty|--------------------------------
---------------------------------|empty|empty|empty|empty|empty|empty|empty|empt
y|empty||empty|empty|empty|empty|empty|empty|empty|empty|empty||----------------
-------------------------------------------------|||empty|empty|empty|empty|empt
y|empty|empty|empty|empty|


Q: Vulkan Dynamic Buffer With Different Texture Per Object I am currently using a dynamic buffer to store the uniforms of multiple objects and update them individually without changing the shader. The problem is that when i am adding a VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER to my descriptor the render is this (I can't post images due to low reputation)! Just the color of the background of the texture. This is my initialization of the descriptor().
descriptorWrites[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
    descriptorWrites[0].dstSet = descriptorSet;
    descriptorWrites[0].pNext = NULL;
    descriptorWrites[0].dstBinding = 0;
    descriptorWrites[0].dstArrayElement = 0;
    descriptorWrites[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC;
    descriptorWrites[0].descriptorCount = 1;
    descriptorWrites[0].pBufferInfo = &bufferInfo;

    descriptorWrites[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
    descriptorWrites[1].dstSet = descriptorSet;
    descriptorWrites[1].pNext = NULL;
    descriptorWrites[1].dstBinding = 1;
    descriptorWrites[1].dstArrayElement = 0;
    descriptorWrites[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
    descriptorWrites[1].descriptorCount = 1;
    descriptorWrites[1].pImageInfo = &imageInfo;

And this is my fragment shader:
#version 450
#extension GL_ARB_separate_shader_objects : enable

layout(set=0, binding = 1) uniform sampler2D texSampler;

layout(location = 0) in vec3 fragColor;
layout(location = 1) in vec2 fragTexCoord;

layout(location = 0) out vec4 outColor;

void main() {
    outColor = texture(texSampler, fragTexCoord*2);
}

What could be the reason of this? I have updated descriptor layout, and the validation layer don't throw any errors and the dynamic buffer was working perfectly even for multiple objects. Is the binding corrupted or something like that?


Q: the scaling problem of Sobolev inequality How to show that by replacing $\psi(x)$ with $\psi(\lambda x)$, an inequality of the form
$$
\int|\nabla\psi|^2dx\geq C\left(\int|\psi|^qdx\right)^\frac{2}{q}
$$ can only hold for $q=6$ in $N=3$?

A: Let $u_{\lambda}(x):=\psi(\lambda x)$. If $\psi$ is infinitely many times differentiable, then $\frac{\partial }{\partial x_j}u_{\lambda}(\lambda x)=\lambda \frac{\partial u_{\lambda}}{\partial x_j}$, and when we integrate (assuming it's over $\Bbb R$), we make the substitution $t=\lambda x$, so the Jacobian of the inverse is $\frac 1{\lambda^3}$ and we would have
$$\int_{\Bbb R^3}|\nabla \psi(x)|^2\lambda^2dx\lambda^{-3}=\frac 1{\lambda}\int_{\Bbb R^3}|\nabla \psi(x)|^2dx\geq C\frac 1{\lambda^{6/q}}\left(\int_{\Bbb R^3}|\psi(x)|^qdx\right)^{2/q}$$
hence
$$\lambda^{6/q-1}\int_{\Bbb R^3}|\nabla \psi(x)|^2dx\geq C\left(\int_{\Bbb R^3}|\psi(x)|^qdx\right)^{2/q}.$$
If $q>6$, then $6/q-1<0$, and you get a contradiction when $\lambda\to 0^+$. If $q<6$, make $\lambda$ go to $+\infty$ to get what we want.

This argument helps us when we forget the critical exponent in Sobolev embeddings.


Q: overflow-y scroll and overflow hidden issue in pop-up window I have a problem, and I cant find solution for that..
I have pop-up window, positioning fixed and 100% height and width.
I want to set  overflow-y: scroll to block .item-details, if there be much content - user can scroll, but only that block .item-details.
I have already set that
.item-details {
border-top: 1px solid #e7e7e7;
padding-top: 38px;
overflow-y: scroll;
}

but it dont work..
Here is JsFiddle DEMO, thanks for any help.

A: You are missing a height attribute on .item-details
Is this what you're after?
DEMO


Q: Adjusting height and width of div and its contents I am trying to adjust the height and width of an HTML parent Div without changing the child div styles. Is there any option to adjust the div dimensions?
Example Scenario:
I have a tree that I am planning to use as a common code to create multiple trees. One small one big etc. So without changing the tree leaves and stem styles(child divs inside parent div), do we have an option to change parent div dimensions so that child divs will be automatically adjusted accordingly?
My fiddle is here

A: build this using only background instead of inner divs and rely on percentage values:

.tree {
  border:1px solid;
  width:100px;
  display:inline-block;
  background:
    radial-gradient(circle at 36% 51%,green 22%,transparent 23%),
    radial-gradient(circle at 52% 37%,green 22%,transparent 23%),
    radial-gradient(circle at 64% 52%,green 22%,transparent 23%),
    linear-gradient(brown,brown) bottom/15% 50%;
  background-repeat:no-repeat;
}
.tree:before {
  content:"";
  display:block;
  padding-top:150%;
}

A: I am not sure why you cannot do it:

Also keep the css code separate it is easy to manage, I have modified for you.

Parent Div


Q: Git pull the last push that was done I have made many changes to my source files and would just like to pull the last push that was done. I would like it to delete any new files, and revert modified files to the last version. I basically want to just revert to how the origin master last was.
Is there a way to do this without deleting the directory, re-initializing git, and then cloning the repo?

A: git reset --hard will bring you back to the last commit, and git reset --hard origin/master will bring you back to origin/master.

A: You can revert the change
Read more:
http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html

A: Another option is just to discard all your changes
git checkout .

And then
git pull


Q: Why is the UITextField placeholder text decreasing in size? I have a peculiar problem in Interface Builder with placeholder text. Some of the placeholder text is smaller than the rest and I can't find a reason why. When I duplicate a UITextfield with full-sized placeholder text it changes instantly to a smaller font.
Xcode 6.1.1 on Mac OS X 10.10.2

A: This is just a visual bug in Xcode 6. Whenever you copy an element with text, that text's font-size seems to visually be altered. However, when you build and run the app, it should show up normal on your device or simulator.
You can fix the visual bug by clicking on the copied element, going to the attributes inspector, and then changing the font-size down one and then back up one.


Q: Startup (and services) profiles in Windows I'm trying to find a solution that would allow me to setup different startup profiles for Windows 7 and Windows 2008.
The idea is be able to boot (or reboot) Windows with a custom set of startup applications and services for different usage. E.g. A fast profile with minimal programs and services; a development profile with SQL Server, MySQL, IIS, Dropbox and SVN etc. etc.
It would be nice if I could choose the profile after booting.. so maybe a fast boot with minimal startup applications/services and then a profile choice that would then load up the required profile.

A: Take a look at Startup Manager Project. Maybe it doesn't completelly solve your problem but is a good reference to begin:

As the name suggests, Startup Manager (aka st-m) is an open source
  startup manager for the Windows platform.
Startup Manager can:

*

*Make programs start on logon (add items)

*Rename existing items

*Delete existing items

*Disable existing items

*Enable existing items

*Create a batch file with programs that start in a certain order

  Startup Manager supports:

*

*Startup folders (all users and current user)

*Registry sections

*

*All the run and services sections (all and current user)

*Computer sections: winlogon (userinit and shell) and BHO (browser helper objects)

*Win.ini sections (load and run)


Q: pattern matching, tuples and multiplication in Python What is be best way to reduce this series of tuples
('x', 0.29, 'a')
('x', 0.04, 'a')
('x', 0.03, 'b')
('x', 0.02, 'b')
('x', 0.01, 'b')
('x', 0.20, 'c')
('x', 0.20, 'c')
('x', 0.10, 'c')

into:
('x', 0.29 * 0.04 , 'a')
('x', 0.03 * 0.02 * 0.01, 'b')
('x', 0.20 * 0.20 * 0.10, 'c')

EDIT:
X is a constant, it is known in advance and can be safely ignored
And the data can be treated as pre-sorted on the third element as it appears above.
I am trying to do it at the moment using operator.mul, and a lot of pattern matching, and the odd lambda function... but I'm sure there must be an easier way!
Can I just say thank you for ALL of the answers. Each one of them was fantastic, and more than I could have hoped for. All I can do is give them all an upvote and say thanks!

A: Here's a functional programming approach:
from itertools import imap, groupby
from operator import itemgetter, mul

def combine(a):
    for (first, last), it in groupby(a, itemgetter(0, 2)):
        yield first, reduce(mul, imap(itemgetter(1), it), 1.0), last

A: Here's a more stateful approach. (I like @Sven's better.)
def combine(a)
    grouped = defaultdict(lambda: 1)

    for _, value, key in a:
        grouped[key] *= value

    for key, value in grouped.items():
        yield ('x', value, key)

This is less efficient if the data are already sorted, since it keeps more in memory than it needs to. Then again, that probably won't matter, because it's not stupidly inefficient either.

A: Given that you are ultimately going to multiply together all of the found values, instead of accumulating a list of the values and multiplying them at the end, change your defaultdict to take an initializer method that sets new keys to 1, and then multiply as you go:
data = [('x', 0.29, 'a'),
('x', 0.04, 'a'),
('x', 0.03, 'b'),
('x', 0.02, 'b'),
('x', 0.01, 'b'),
('x', 0.20, 'c'),
('x', 0.20, 'c'),
('x', 0.10, 'c'),]

from collections import defaultdict

def reduce_by_key(datalist):

    proddict = defaultdict(lambda : 1)
    for _,factor,key in datalist:
        proddict[key] *= factor

    return [('x', val, key) for key,val in sorted(proddict.items())]

print reduce_by_key(data)

Gives:
[('x', 0.011599999999999999, 'a'),
 ('x', 5.9999999999999993e-06, 'b'),
 ('x', 0.004000000000000001, 'c')]


Q: Python: Add values to dictionary Let say we have an array of positive integers and some integer x/
Each element in the array represents a missions and it's difficulty level and we want to find the minimum number of days to complete all the missions.
The difference between the difficult level of any two mission performed on the same day should not be greater than an integer x.
For example:
Arr = [5,8,2,7]
x = 3

5 and 8 can be performed in the first day
2 on the second day and 7 in the last day
I would like to get the following result:
dict = {key1:[5,8],key2:[2],key3:[3]}

A: your question is a little vague as to what the answer could be, did you want a value to return true if this is the case? did you want to gauruntee a way to fill the dictionary in a way where your condition is true?
if you want to check that your condition is true, try:
bool_dict = {}
for key, val in dict.items():
    if max(val)-min(val)>x:
        bool_list[key]=False

    else: bool_dict[key]=True

print(bool_dict)

A: Here's my implementation:
def missions_to_dict(arr, x):
    curr_key = 1
    last_mission = arr[0]
    dict = {"key1": [last_mission]}

    # Loop through all missions
    for curr_mission in arr[1:]:
        # Check to see if current mission is x away from last mission
        if abs(curr_mission - last_mission) <= x:
            # Add it to same key as last mission
            dict[f"key{curr_key}"].append(curr_mission)
        # Otherwise, need to create new key
        else:
            curr_key += 1
            dict[f"key{curr_key}"] = [curr_mission]
        # Set current mission to last mission
        last_mission = curr_mission

    return dict


Q: How can I natively launch an external app from within Xamarin.Forms? As the question title suggests, I'm looking for a way to launch an external app from within a Xamarin.Forms app. For example, my app has a list of addresses, and when the user taps on one of them, the built-in map app for the current platform would open (Google Maps for Android, Apple Maps for iOS). In case it matters, I am only targeting Android and iOS.
I could use a dependency service and write the app-launching code on a per-platform basis, of course, but I'd prefer if I only had to write it once. Is there a native way to do this in Xamarin.Forms? I was unable to find anything that officially documented this on the Xamarin site or forums.

A: Use Device.OpenUri and pass it the appropriate URI, combined with Device.OnPlatform to format the URI per platform
string url;

Device.OnPlatform(iOS: () =>
  {
     url = String.Format("http://maps.apple.com/maps?q={0}", address);
  },
  Android: () =>
  {
    url = String.Format("http://maps.google.com/maps?q={0}", address);
  });

Device.OpenUri(url);

A: As of Xamarin.Forms v4.3.0.908675 (probably v4.3.0) Device.OpenUri is deprecated and you should use Launcher.TryOpenAsync from Xamarin.Essentials instead. Although you will find it troublesome, or at least I did.

A: Use Below code, and add namespaces Xamarin.Essentials and Xamarin.Forms
if (Device.RuntimePlatform == Device.iOS)
{
    // https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
    await Launcher.OpenAsync("http://maps.apple.com/?daddr=San+Francisco,+CA&saddr=cupertino");
}
else if (Device.RuntimePlatform == Device.Android)
{
    // opens the 'task chooser' so the user can pick Maps, Chrome or other mapping app
    await Launcher.OpenAsync("http://maps.google.com/?daddr=San+Francisco,+CA&saddr=Mountain+View");
}
else if (Device.RuntimePlatform == Device.UWP)
{
    await Launcher.OpenAsync("bingmaps:?rtp=adr.394 Pacific Ave San Francisco CA~adr.One Microsoft Way Redmond WA 98052");
}


Q: How to use the new AndroidX Media2? I am using Media App Architecture as a guide for building a music player app. But it uses the classes from support media-compat / Androidx Media.
But now AndroidX Media2 is available in stable channels and I don't see any word of it. What is it?

*

*is AndroidX Media2 supposed to deprecate AndroidX Media?

*is there a developer guide or other sources of documentation for AndroidX Media2?

Please, no links to JavaDoc, thanks.

A: Jetpack Media3 has launched!
https://developer.android.com/jetpack/androidx/releases/media3
This blog post gives a great explanation about how the media libraries evolved. I strongly recommend integrating with androidx.media3.
If for whatever reason you cannot use androidx.media3, my recommendation is to stick with androidx.media instead of androidx.media2 due to the latter not being supported by other media integrations, such as Cast Connect. Integrating Media2 with ExoPlayer is also quite a bit more complex.
From my perspective, the key benefit of switching from Media1 to Media2 is the ability to provide more fine-grained permission controls. See Jaewan Kim's blog post that goes in depth about the more complex SessionPlayerConnector API and permissions to accept or reject connections from a controller in media2.
If you have an existing Media1 implementation using MediaSession (preferably using ExoPlayer with MediaSessionConnector), and have no need for the permission controls in Media2, you can either stick with Media1 or upgrade to Media3.
The “What's next for AndroidX Media and ExoPlayer” talk from Android Dev Summit 2021 goes much more in depth on Media3.

A: All the documentation I was able to find was useless and outdated. androidx.media and the appcompat media libraries are both superseded by androidx.media2 (but not deprecated for some reason). The most high-level API for media apps appears to be MediaLibraryService for the service and MediaBrowser for the frontend. Just make absolutely sure you declare the right intent filters on the service (which are in the javadoc :P)

A: Here is my working solution using Media2 libs (AndroidX):

*

*Add 3 dependencies in Build.gradle

implementation "androidx.media2:media2-session:1.2.0"
implementation "androidx.media2:media2-widget:1.2.0"
implementation "androidx.media2:media2-player:1.2.0"

*Create layout activity_video_player.xml and put this code into it:
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@+id/accompany_agent_details"
     style="@style/Layout.Default">
     <LinearLayout
         android:id="@+id/videoLayout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentStart="true"
         android:layout_alignParentLeft="true"
         android:layout_alignParentTop="true"
         android:orientation="vertical">

         <android.widget.VideoView android:id="@+id/simpleVideoView"
             android:layout_width="match_parent"
             android:layout_height="300dp" />
     </LinearLayout>
 </RelativeLayout>

 <style name="Layout.Default">
     <item name="android:layout_width">match_parent</item>
     <item name="android:layout_height">match_parent</item>
 </style>

*Create activity class SimpleVideoActivity:
    public class VideoPlayerActivity extends FragmentActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_video_player_android_x);
            VideoView simpleVideoView = findViewById(R.id.simpleVideoView);
            MediaMetadata mediaMetaData = new MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_TITLE, "Put your video text here").build();
            UriMediaItem item = new UriMediaItem.Builder(Uri.parse("Put your video URL here")).setMetadata(mediaMetaData).build();
            MediaPlayer mediaPlayer = new MediaPlayer(this);
            simpleVideoView.setPlayer(mediaPlayer);
            mediaPlayer.setMediaItem(item);
            mediaPlayer.prepare();
            mediaPlayer.play();
        }
    }


Q: Toggle class with expand/collapse all multiple accordions I am having trouble with a jquery script I am trying to write. It looks right to me but not quite there yet. Can someone please help me understand why this isn't working?
jQuery('.expand').click(function(){
    jQuery('.expandnav').find('div.menu-body').show('slow');

    if( ('.menu-body').is(':visible') ){
        (this).addClass('collapse-active');
    }else{
        (this).removeClass('collapse-active');
    }
});

When .expand is clicked .menu-body does show but the conditional doesn't seem to run. I have tested with alerts and no response...
i am using toggleClass on each individual accordion as there are many to the page but I need the addClass/removeClass to swap the +,- images. Hope that makes sense. Bottom line is the conditional is not responding.
Any help is greatly appreciated

A: You'll want to use the callback method of $.fn.show, read more at http://api.jquery.com/show/
Here's a fiddle showing the proposed change: http://jsfiddle.net/pewt8/


Q: Kerberos error KDC_ERR_S_PRINCIPAL_UNKNOWN, should I care? We've got a lot of Kerberos auth used in our environment that mostly seems to work, but a few errors still pop up when we turn on Kerberos error logging.  The two that bother me the most are both KDC_ERR_S_PRINCIPAL_UNKNOWN which according to http://technet.microsoft.com/en-us/library/cc772897(WS.10).aspx is that the SERVER is not in the Kerberos db.  Assume a domain of corp.lan, the two error messages are for servername: app.corp.lan and dc1.corp.lan.  Now when I do a setspn -l app , I get plenty of spn's , but none for app.corp.lan.  Same for dc1, setspn -l dc1 returns 15+ records, setspn -l dc1.corp.lan retruns an error.  Is this a 'real' error we should be trying to track down and fix or is that just some odd app doing bad Kerb requests?

A: You need to check on the error messages for what service these SPN's are not registered.
It means that kerberos Auth will fail for these services.
Maybe there's a NTLM second option, maybe not.
You should check this per service returning an error.
I've noticed that sometimes the error message doesn't show the kerberos service that the ticket is being requested for, so you could use Ethereal to check this out. I wish there was some sort of querying (like sql) onto event viewer.
If its all working I usually don't bother, but you could find something bellow the carpet later if you ever need using something that is broken and you never knew.


Q: using profile and boot method within confint option, with glmer model I am using glmer with a logit link for a gaussian error model.
When I try obtaining the confidence intervals, using either profile or the boot method with the confint option, I obtain an error for use of profile likelihood, and with bootstrapping:
> Profile: Computing profile confidence intervals ... Error in
> names(opt) <- profnames(fm, signames) :    'names' attribute [2] must
> be the same length as the vector [1]
>
> Boot: Error in if (const(t, min(1e-08, mean(t, na.rm = TRUE)/1e+06)))
> { :    missing value where TRUE/FALSE needed In addition: Warning
> message: In bootMer(object, FUN = FUN, nsim = nsim, ...) :   some
> bootstrap runs failed (9999/10000)

I have looked at online suggestions on how to overcome the profile issue, by installing the lme4 development tool and I have also eliminated all NAs from the dataset. However, in both instances, I still receive the same two error messages.
Is anybody able to offer any help as to whether this is a lme4 issue, or whether it's more fundamental.
Here is code to produce the first 20 observations and the model format:
df2 <- data.frame(
prop1 = c(0.46, 0.471, 0.458, 0.764, 0.742, 0.746, 0.569, 0.45,    0.491,    0.467, 0.464,
        0.556, 0.584, 0.478, 0.456, 0.46, 0.493, 0.704, 0.693, 0.651),
prop2 = c(0.458, 0.438, 0.453, 0.731, 0.738, 0.722, 0.613, 0.498, 0.452, 0.451, 0.447,
        0.48, 0.576, 0.484, 0.473, 0.467, 0.467, 0.722, 0.707, 0.709),
site = c(1,1,2,3,3,3,4,4,4,4,4,5,5,5,6,6,7,8,8,8)
)
df2$site <- factor(df2$site)

model <- glmer(prop2 ~ prop1 + (1|site),
           data=df2, family=gaussian(link="logit"))
summary(model)

The response is a proportion (0,1), as is the covariate. I have used the logit link to keep the expected values of the response bound between (0,1), rather than being unbound with the normal, though this data fits a LMM reasonably well.
I will also analyse the difference between the two proportions, for which I expect some differences (and fitted values) to violate the (0,1) boundary - so I will model this with either an identity link with gaussian error, or logit link on the scaled difference (coercing this to be (0,1)).
Also, given that there may only be 1-5 records per site, I will naturally consider running linear regression or GLM (proportions), and treat site as a fixed effect in the modelling process, if the estimate of the random effects variance is zero (or very small).

A: For your example it works with bootstrap:
confint(model, method = "boot")
#                   2.5 %      97.5 %
# .sig01      12.02914066 44.71708844
# .sigma       0.03356588  0.07344978
# (Intercept) -5.26207985  1.28669024
# prop1        1.01574201  6.99804555

Take into consideration that under your proposed model, although your estimation will be always between 0 and 1, it is expected to observe values lower than 0 and greater than 1.

A: You've identified a bug with the current version of lme4, partially fixed on Github now (it works with method="boot"). (devtools::install_github("lme4/lme4") should work to install it, if you have development tools installed.)
library(lme4)
fit_glmer <- glmer(prop2 ~ prop1 + (1|site),
       data=df2, family=gaussian(link="logit"))

Profiling/profile confidence intervals still don't work, but with a more meaningful error:
try(profile(fit_glmer))
## Error in profile.merMod(fit_glmer) :
##   can't (yet) profile GLMMs with non-fixed scale parameters

Bootstrapping does work. There are lot of warnings, and a lot of refitting attempts failed, but I'm hoping that's because of the small size of the data set provided.
bci <- suppressWarnings(confint(fit_glmer,method="boot",nsim=200))

I want to suggest a couple of other options.  You can use glmmADMB or glmmTMB, and these platforms also allow you to use a Beta distribution to model proportions.  I would consider modeling the difference between proportion types by "melting" the data (so that there is a prop column and a prop_type column) and including prop_type as a predictor (possibly with an individual-level random effect identifying which proportions were measured on the same individual) ...
library(glmmADMB)
fit_ADMB <- glmmadmb(prop2 ~ prop1 + (1|site),
       data=df2, family="gaussian",link="logit")
## warning message about 'sd.est' not defined -- only a problem
## for computing standard errors of predictions, I think?

library(glmmTMB)
fit_TMB <- glmmTMB(prop2 ~ prop1 + (1|site),
       data=df2, family=list(family="gaussian",link="logit"))

It sounds like your data might be more appropriate for a Beta model?
fit_ADMB_beta <- glmmadmb(prop2 ~ prop1 + (1|site),
       data=df2, family="beta",link="logit")
fit_TMB_beta <- glmmTMB(prop2 ~ prop1 + (1|site),
       data=df2,
       family=list(family="beta",link="logit"))

Compare results (fancier than it needs to be)
library(broom)
library(plyr)
library(dplyr)
library(dwplot)

tab <- ldply(lme4:::namedList(fit_TMB_beta,
                        fit_ADMB_beta,
                        fit_ADMB,
                        fit_TMB,
                        fit_glmer),
      tidy,.id="model") %>%
    filter(term != "(Intercept)")
dwplot(tab) +
    facet_wrap(~term,scale="free",
                       ncol=1)+theme_set(theme_bw())


Q: How to offer a chooser to get content for multiple mime types? I want to have one button in my app that lets the user pick images or any other files from the apps on the device. Here's the code in my activity for letting the user pick files from apps such as Dropbox and Drive:
    private static int RESULT_GET_CONTENT = 1;

    public void getFileContent() {
        Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
        fileIntent.setType("file/*");
        startActivityForResult(fileIntent, RESULT_GET_CONTENT);
    }

That brings up a list of the available apps. When the user chooses one that app lets him browse the files.
To pick images from the Gallery I can change the intent's type to "image/*".
How do I change this to bring up a list of apps that includes files apps (Dropbox & Drive) and image apps (Gallery)?

A: It turns out that the solution is very simple. I just needed to use "*/*" as the type and then add the openable category which filters out things like contacts that I don't want.
public void getFileContent() {
    Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
    fileIntent.setType("*/*");
    fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(fileIntent, RESULT_GET_CONTENT);
}


Q: Running batch jobs in Pivotal Cloud foundary We have a requirement to migrate mainframe batch jobs to PCF cloud but as 3R's of security Rotate, Repave and Repair it might be possible that in the instance where batch job is running as spring batch that instance can be repaved/repair and our running jobs got terminated. In that scenario how to ensure that during repavement/repair of an PCF instance our jobs will not get impacted. We are looking for best way to migrate jobs in PCF cloud, any help/suggestion will be really helpful.


Q: How can I use flavors to set different endpoints to my app? I've an app and I want to have an English version too (It's only in Spanish now). I've already created all the strings and resources, and I want to use them and set different endpoints to my app whether it's the english version or the spanish one. How can I do that?
I know I could use flavors but I've never read about setting different endpoints with flavors, is it possible to use flavors or do I have to use something else?
P.S.: By "endpoints" I mean servers that answer http REST requests
Thanks!

A: So you would have 2 different folders values and values-es. The best way for you is to create config.xml file in both folders with different url e.g.:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="endpoint">http://endpoint.com/en/index.html</string>
</resources>

To get the value for particular language you would get it like ordinary string:
context.getString(R.string.endpoint);

A: Flavours is not what you want to use because then you will build different APK file.
You probably want to have a unique app with different languages capability.
The Android doc has a great explanation about how to do this :
http://developer.android.com/training/basics/supporting-devices/languages.html


Q: Tensors as multilinear maps I am aware that many books on differential geometry define tensors as multilinear maps. Namely
$$
V\otimes W := L_2(V^* \times W^*,\Bbb F)
$$
I am also aware that this space is isomorphic to the tensor product in the finite dimensional case, but I am wondering if it is a good idea to think of tensor products as multilinear maps. Is there any reason why one would like to make this identification in the finite dimensional case? Or does this definition come from the idea that students new to the subject may have an easier time with this less abstract definition?
Thanks


Q: Setf variable to computing time? I want to set variable to computing time like this
(setf a (time (+ 1 1)))

but instead of time I get this
Break 1 [7]> a
2

How can I set a to computing time?

A: Use GET-INTERNAL-RUN-TIME (or GET-INTERNAL-REAL-TIME):
(setf a
      (let ((start (get-internal-run-time)))
        (+ 1 1) ;This is the computation you want to time.
        (- (get-internal-run-time) start)))

Divide by INTERNAL-TIME-UNITS-PER-SECOND if you want the result in seconds.
You would probably want to make a function or macro if you do this a lot.

A: See the answer of Lars.
TIME writes implementation dependent information to the trace output. If you want its output as a string:
(with-output-to-string (*trace-output*)
  (time (+ 1 1)))


Q: Query parameters for root component in Angular IO I have a very simple Angular 4+ application that fetches data from API and displays the data. I believe this should be possible by using just the root component:{path: 'main', component: MainComponent}
and QueryParams like ?id=1.
I am able to fetch the query param, but for some reason my router repeats the route+params part of the URL after the already existing route+params part. For example my local address malforms from localhost:4200/main?id=1 into localhost:4200/main?id=1/main?id=1.
The ActivatedRoute does pick the correct query parameter from the URL but I would like to keep the URL as sanitized as possible. How do I prevent this duplication from happening? I have set <base href='/'> as per routing requirements in my index.html.
Module:
@NgModule({
  imports: [
    BrowserModule,
    RouterModule,
    RouterModule.forRoot(
      [
        { path: 'main', component: MainComponent},
      ]),
    CommonModule,
    HttpModule,
    FormsModule,
    NgbModule.forRoot()
  ],
  declarations: [MainComponent],
  providers: [
    {provide: APP_BASE_HREF, useValue: window.document.location.href},
    DataService,
    WindowService,
    HttpUtil
  ],
  bootstrap: [MainComponent]
})
export class MainModule{}

Component:
@Component({
  selector: 'main-component',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css']
})

export class MainComponent implements OnInit {

  constructor(private dataService: DataService,
              private activatedRoute: ActivatedRoute) {
  }

  ngOnInit() {
    this.activatedRoute.queryParams.subscribe((params: Params) => {
      if (!(Object.keys(params).length === 0 && params.constructor === Object)) {
        console.log(params);
      }
    });
  }
}

A: This is caused by your APP_BASE_HREF
{provide: APP_BASE_HREF, useValue: window.document.location.href}

You are telling the app to use window.document.location.href main?id=1 as your basehref. Angular then appends its own routes to the end of the basehref. This is why you are getting the duplication
 localhost:4200/main?id=1(< APP_BASE_HREF)/main?id=1(< ROUTE)

Here are the docs on the functionality of APP_BASE_HREF (https://angular.io/api/common/PathLocationStrategy#description)


Q: Make Discord-Bot to reply same message for any command I want my bot to reply the same message for no matter whatever command it receives. I know how to reply to commands when they are knows but here I want to reply a particular string irrespective of the command.
I tried:
[Command("")]
public async Task gg()
{
    await ReplyAsync("gg");
    await Context.Channel.SendMessageAsync("hi there");
}

but apparently I get a runtime error as it can not add a blank or null command. (error log is useless)
Not placing the [Command(string)] at all would never trigger the task for what I could make out.

A: Assuming that you where following the Discord.NET documentation tutorials in setting up a command service...
You probably have a HandleCommand function, or something equivalent to that. It should contain a line of code that looks like this:
if(!(message.HasStringPrefix("PREFIX", ref argPos))) return;
Which basically means "if this message does not have the prefix at the start, exit the function". (Where message is a SocketUserMessage and argPos is a int, usually 0)
Put your line of code after that, so it would look like this...
//Blah
if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; }
await message.Channel.SendMessageAsync("blah");
//stuff

But, if you want the bot to only reply if the bot doesn't find a suitable command for the current command the user send, you can do this instead:
if(!(message.HasStringPrefix("PREFIX", ref argPos))) { return; }
            var context = new CommandContext(client, message);
            var result = await commands.ExecuteAsync(context, argPos, service);

            if(!result.IsSuccess) {
                //If Failed to execute command due to unknown command
                if(result.Error.Value.Equals(CommandError.UnknownCommand)) {
                    await message.Channel.SendMessageAsync("blah");
                } else {
                    //blah
                }
            }

A: It's not possible to implement this as a command. You have to subscribe to the MessageReceived Event of your DiscordSocketClient and simply send a message back to the channel when it fires.
private async Task OnMessageReceived(SocketMessage socketMessage)
{
    // We only want messages sent by real users
    if (!(socketMessage is SocketUserMessage message))
        return;

    // This message handler would be called infinitely
    if (message.Author.Id == _discordClient.CurrentUser.Id)
        return;

    await socketMessage.Channel.SendMessageAsync(socketMessage.Content);
}


Q: Does Three.js support OES_texture_float? I want to render position or depth to a floating texture.
I use
vsnTexture = new THREE.WebGLRenderTarget(window.innerWidth, window.innerHeight,
            { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat ,type:THREE.FloatType });

as the render target.
Then, I tested
var gl = this.renderer.getContext();
    if( !gl.getExtension( "OES_texture_float" ) ){
        console.error( "No OES_texture_float support for float textures!" );
    }

and found no error. Chrome supports OES_texture_float, and I step into THREE.js:
_gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
 //console.log(glType);

I found glType =5126(gl.FLOAT) ,when I set the WebGLRenderTarget:type:THREE.FloatType. This means I could use OES_texture_float. Do I have something wrong? Because whatever I set the type:THREE.FloatType or use the default ( THREE.UnsignedByteType), I both get the same render texture.
Am I not using the OES_texture_float correctly?

A: Yes, it does. This example shows how to use it:
http://threejs.org/examples/#webgl_gpgpu_birds


Q: UITableView scrollToRow breaks UIView.animate() in UITableViewCell I want to create a chat-like view, and in order to simulate a message being written, I have added a dot-bubble cell, with the dot's alphas animating from 0 to 1.
I have added this animation in the custom cell's layoutSubviews() method.

However, I am also calling tableView.scrollToRow() so the table view always shows the last cells to the user. But I realized that calling this method would break the animations inside of my cells (whether I am animating or not the scrollToRow() method).
What should I do? Thanks for your help.

A: Just create two instance method in Your typing indicator cell
one for start animation and another for resetAnimation
class TypingCell: UITableViewCell {
    fileprivate let MIN_ALPHA:CGFloat = 0.35

    @IBOutlet weak var dot0: UIView!
    @IBOutlet weak var dot1: UIView!
    @IBOutlet weak var dot2: UIView!

    private func startAnimation() {
        UIView.animateKeyframes(withDuration: 1.5, delay: 0, options: [.repeat, .calculationModeLinear], animations: {
            UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.1666, animations: {
            self.dot0.alpha = MIN_ALPHA
            })
            UIView.addKeyframe(withRelativeStartTime: 0.16, relativeDuration: 0.1666, animations: {
            self.dot0.alpha = 1
            })
            UIView.addKeyframe(withRelativeStartTime: 0.33, relativeDuration: 0.1666, animations: {
            self.dot1.alpha = MIN_ALPHA
            })
            UIView.addKeyframe(withRelativeStartTime: 0.49, relativeDuration: 0.1666, animations: {
            self.dot1.alpha = 1
            })
            UIView.addKeyframe(withRelativeStartTime: 0.66, relativeDuration: 0.1666, animations: {
            self.dot2.alpha = MIN_ALPHA
            })
            UIView.addKeyframe(withRelativeStartTime: 0.83, relativeDuration: 0.1666, animations: {
            self.dot2.alpha = 1
            })
        }, completion: nil)
    }

    func resetAnimation() {
        dot0.layer.removeAllAnimations()
        dot1.layer.removeAllAnimations()
        dot2.layer.removeAllAnimations()

        DispatchQueue.main.async { self.startAnimation() }
    }

}

Reset your animation on tableView(_: willDisplay: cell: forRowAt:)
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if let cell = cell as? TypingCell {
        cell.resetAnimation()
    }
}


Q: Let R be the relation defined on the set of real numbers by xRy iff x=y or xy=1 Give the equivalence class of 3, -2/3, and 0.
I'm unsure if the equivalence classes for these should just be {3,3}, {2/3,2/3}, and {0,0}. If they extended to the xy=1 condition, I'm unsure about what they would look like in that case. Any help would be appreciated!

A: Several comments here.
First, it would be good to verify that $ R$ is indeed an equivalence relation.
Second, you note sets like $\{0,0\}$... While this is not incorrect, you should notice that for whatever element $a$, you have $\{a,a\}=\{a\}$.
Third, the equivalence class you mentioned are not correct. For example you have
$$\overline{3}=\{3,1/3\}$$
Fourth, the equivalence class of $0$ is a "special case". Do you see why?


Q: Local version of jquery not working right Developing a theme for someone else, nornally on sites I'd maintain I'd use google CDN to load jquery like so:
//don't use (deregister) WP's jQuery version
wp_deregister_script( 'jquery' );

//Use jQuery from Google Code
wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
wp_enqueue_script('jquery'););

But after deleting that WordPress's local version breaks my site, it's loading the same version just from wp-includes, jquery 1.11.1.
When I use google CDN it's all fine.
When I use the local version it just throws up errors in my JS like 'Uncaught TypeError: undefined is not a function' on the first line of my main.js file.
Totally perplexed as to what would cause this issue.


Q: How to set current date to a fixed value in hsqldb? For my unit tests I need to freeze the current date. Otherwise the unit tests that work today will break next week.
Is there a way to freeze the current date (or sysdate) in HSQLDB?


Q: Restrict Multiple Items in Json I am creating a JSON schema in which a field is a array field and can have two custom types. Now i want that this field can have one custom type with max item as 1 and another as 0 to n.
"field-1": {
    "type": "array",
    "system-generated": true,
    "anyOf": [{
            "items": {
                "$ref": "customItem1"
            }
        }, {
            "items": {
                "$ref": "customItem2"
            }
        }
    ]
}

Considering the above same, i want that field-1 have customItem1 max one instance and customItem2 have zero to n instances.

A: Unfortunately, there is no way to enforce that an array contains a specific number of something. The closest you can do is to enforce that something exists (1 to n) in an array.
If "customItem1" is always the first item, it can be done.
{
  "type": "array",
  "anyOf": [
    {
      "items": [
        { "$ref": "#/definitions/customItem1" }
      ],
      "additionalItems": { "$ref": "#/definitions/customItem2" },
    },
    {
      "items": { "$ref": "#/definitions/customItem2" }
    }
  ],
  "definitions": {
    "customItem1": { "type": "string" },
    "customItem2": { "type": "boolean" }
  }
}


Q: How to deal with large data in Apriori algorithm? I would like to analyze customer data from my e-shop using association rules. These are steps that I took:
First: My dataframe raw_data has three columns ["id_customer","id_product","product_quantity"] and it contains 700,000 rows.
Second: I reorder my dataframe and I get a dataframe with 680,000 rows and 366 columns:
customer = (
    raw_data.groupby(["id_customer", "product_id"])["product_quantity"]
    .sum()
    .unstack()
    .reset_index()
    .fillna(0)
    .set_index("id_customer")
)
customer[customer != 0] = 1

Finally:  I would like to create a frequency of items:
from mlxtend.frequent_patterns import apriori
frequent_itemsets = apriori(customer, min_support=0.00001, use_colnames=True)

but now I got an error MemoryError: Unable to allocate 686. GiB for an array with shape (66795, 2, 689587) and data type float64
How to fix it? Or how to compute frequent_itemsets without using apriori function?

A: If you have data that is too large to fit in memory, you may pass a function returning a generator instead of a list.
from efficient_apriori import apriori as ap

def data_generator(df):
  """
  Data generator, needs to return a generator to be called several times.
  Use this approach if data is too large to fit in memory.
  """
  def data_gen():
        yield [tuple(row) for row in df.values.tolist()]

  return data_gen

transactions = data_generator(df)
itemsets, rules = ap(transactions, min_support=0.9, min_confidence=0.6)


Q: Is there a way to use two @* in an xpath selector to select an element? I have an HTML element I would like to select that looks like this:
<button data-button-id="close" class="modal__cross modal__cross-web"></button>

Now clearly I can use this XPath selector:
//button[(contains(@data-button-id,'close')) and (contains(@class,'modal'))]

to select the element.  However, I would really like to select buttons that have both close and modal contained in any attributes. So I can generalize the selector and say:
//button[(contains(@*,'close')) and (contains(@class,'modal'))]

and that works.  What I'd love to do is extend it to this:
//button[(contains(@*,'close')) and (contains(@*,'modal'))]

but that doesn't return any results. So clearly that doesn't mean what I'd like it to mean.  Is there a way to do it correctly?
Thanks,
Craig

A: It looks like you're using XPath 1.0: in 1.0, if you supply a node-set as the first argument to contains(), it takes the first node in the node-set. The order of attributes is completely unpredictable, so there's no way of knowing whether contains(@*, 'close') will succeed or not. In 2.0+, this gives you an error.
In both 1.0 and 2.0, @*[contains(., 'close')] returns true if any attribute contains "close" as a substring.

A: This expression works:
 //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]
Given this html
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
<button key="close" last="xyz_modal"></button>

Testing with xmllint
echo -e 'cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]\nbye' | xmllint --html --shell test.html
/ > cat //button[attribute::*[contains(.,"close")] and attribute::*[contains(.,"modal")]]
 -------
<button data-button-id="close" class="modal__cross modal__cross-web"></button>
 -------
<button key="close" last="xyz_modal"></button>
/ > bye

A: Try this one to select required element:
//button[@*[contains(., 'close')] and @*[contains(., 'modal')]]


Q: Pass arguement to custom permision class in django I have a custom permission class that extends the rest framework base permission. I am trying to pass an argument allowed_groups that will be a list of all the groups that have access to the particular view.
This is my current custom permission implementation.
class CustomUserPermisions(BasePermission):

    message = "Ooops! You do not have permissions to access this particular site"
    def has_permission(self, request, view):
        allowed_groups = [ 'group_hr', 'super_admin', 'employee']
        user1 = Employee.objects.filter(user__email=request.user).first()
        user_groups = user1.user_group.all()
        for group in user_groups:
            if group.title in allowed_groups:
                return True
        return False

I have tried adding an argument as follows.
class CustomUserPermisions(BasePermission, allowed_groups):

    message = "Ooops! You do not have permissions to access this particular site"
    def has_permission(self, request, view):
        allowed_groups = [ 'group_hr', 'super_admin', 'employee']
        user1 = Employee.objects.filter(user__email=request.user).first()
        user_groups = user1.user_group.all()
        for group in user_groups:
            if group.title in allowed_groups:
                return True
        return False

but this is the error I am currently receiving.
class CustomUserPermisions(BasePermission, allowed_groups):
NameError: name 'allowed_groups' is not defined

Is there a better way that I can do this?

A: I guess you are a newcomer to python.
You should read https://docs.python.org/3/tutorial/classes.html to get better understanding about python classes.
class CustomUserPermisions(BasePermission, allowed_groups):
means that the class CustomUserPermisions inherits from the classes BasePermission and allowed_groups. allowed_groups is not a class, so you get an error.
You should create a class attribute for allowed group :
class CustomUserPermisions(BasePermission):
    def __init__(self, allowed_groups):
        self.allowed_groups = allowed_groups
        self.message = "Ooops! You do not have permissions to access this particular site"

    def has_permission(self, request, view):
        user1 = Employee.objects.filter(user__email=request.user).first()
        user_groups = user1.user_group.all()
        for group in user_groups:
            if group.title in self.allowed_groups:
                return True
        return False

and then call the class constructor :
permissions = CustomUserPermisions(['group_hr', 'super_admin', 'employee'])


Q: How do you track down JavaScript's "Unexpected token" errors when you get an irrelevant line number? I've looked through a few questions about JavaScript reporting an unexpected token without giving a helpful line number (line 1 at localhost/index.html is "<!DOCTYPE html>"):
Uncaught SyntaxError: Unexpected token u                                      localhost:/1

Now I've seen a number of "Uncaught SyntaxError" posts, but I wanted to step back one meta-level and ask not just what is wrong with my current code (React JSX is at http://pastebin.com/P3Epzi0q and the HTML at http://pastebin.com/0abjnmZz is not particularly interesting), but how to best pin down what to do when dealing with an "Uncaught SyntaxError" that includes only irrelevant attribution as to where the culprit is.
My present attempt, besides using breakpoints and stepping through, is to drill down on where in my code it is happening. I am loading external sources including Showdown, jQuery, and ReactJS, but the crash is occurring between the two console.log() statements in my code:
  console.log("Reached 10");
  React.render(<Pragmatometer />,
    document.getElementById('main'));
  console.log("Reached 11");

That's still an awful lot of territory, and I am drilling down to try and see where is the last place I can place a console.log() statement that happens before the crash, and what is the earliest place I can place a console.log() statement that does not happen, just the crash.
Besides possibly more finesse with the Chrome debugger (or is that the answer?), what is the best way to tell where the issue is? Is there a linter that gives more helpful diagnostics and in particular a line number for the fault?
Maybe this question belongs on programmers.stackexchange.com, but it seems that there are repeated questions about uncaught SyntaxErrors, and the responses have pinpointed faults in code snippets but have not (so far as I have seen) explained how to pinpoint a fault when you don't have a useful line number.
Is my present vaguely binary-search-inspired use of drilling down in logging the best route? Is there something better?
Thanks,

A: Breadcrumb remark: I spent an hour with the debugger, partly because I did not realize that stepping-in would continue to move forward after the error was thrown.
In this case, I was acting on bad or obsolete information that localStorage[foo] would return null if nothing was saved; it was returning undefined which passed my non-null check, and JSON.parse() was throwing an exception at being fed the string "undefined".


Q: Connection of VB.NET to SQL server I had a project running perfectly i.e. entering values in database linked by code. But in the other project I am implementing it shows values correctly submitted, gives no error while running but values are not entered in database.
Private Sub frmAddresume_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    cn.ConnectionString = "Data Source=ROHAN-PC\SQLEXPRESS;initial catalog=Libeasy;Integrated Security=true"

    DateTimePicker1.Value = DateTime.Now.ToShortDateString()
End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
    If (TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "") Then
        cn.Open()
        cmd.Connection = cn
        cmd.CommandText = "insert into StudResume values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DateTimePicker1.Value.ToShortDateString() + "'," + TextBox3.Text + ")"

        cmd.Dispose()
        cn.Close()

        MsgBox("Details saved Successfully", MsgBoxStyle.Information, "Done")
        TextBox1.Text = ""
        TextBox2.Text = ""
        TextBox3.Text = ""

        DateTimePicker1.Value = Now
        TextBox1.Focus()
    Else
        MsgBox("Please Enter Complete Details", MsgBoxStyle.Critical, "Error")
    End If
End Sub

A: You've missed the executenonquery(),so the query you have provided is niether executed.replace the below code and eeverything will be working.
cmd.Connection = cn
        cmd.CommandText = "insert into StudResume values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DateTimePicker1.Value.ToShortDateString() + "'," + TextBox3.Text + ")"
cmd.ExecuteNonQuery()
        cmd.Dispose()
        cn.Close()

Ie Add cmd.ExecuteNonQuery() after providing the commandtext.

A: change your button3 code as the following, it will give u an error message in msgbox, post the error message here so may we can help,
        If (TextBox1.Text <> "" And TextBox2.Text <> "" And TextBox3.Text <> "") Then
            Try
                cn.Open()
                cmd.Connection = cn
                cmd.CommandText = "insert into StudResume values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + DateTimePicker1.Value.ToShortDateString() + "'," + TextBox3.Text + ")"

                cmd.Dispose()
                cn.Close()

                MsgBox("Details saved Successfully", MsgBoxStyle.Information, "Done")
                TextBox1.Text = ""
                TextBox2.Text = ""
                TextBox3.Text = ""

                DateTimePicker1.Value = Now
                TextBox1.Focus()
            Catch ex As Exception
                MsgBox(ex.Message)
            Finally

            End Try

        Else
            MsgBox("Please Enter Complete Details", MsgBoxStyle.Critical, "Error")
        End If

A: Try this way
 cn =new SqlConnection("Data Source=ROHAN-PC\SQLEXPRESS;initial catalog=Libeasy;Integrated Security=true")


Q: How can I add ImageView's with swipe option IMAGE. How can I achive effect shown in image. Im working on browser and for choosing current active tab I want to build something similarlike this. User will be able to swipe view right or left and if user click on view there will be zooming animation to fit the screen.

A: You can use this library to swipe between images with effects:
https://github.com/daimajia/AndroidImageSlider
dependencies {
        compile "com.android.support:support-v4:+"
        compile 'com.squareup.picasso:picasso:2.3.2'
        compile 'com.nineoldandroids:library:2.4.0'
        compile 'com.daimajia.slider:library:1.1.5@aar'
}

Add the Slider to your layout:
<com.daimajia.slider.library.SliderLayout
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="200dp"
/>

Wiki:
https://github.com/daimajia/AndroidImageSlider/wiki/Slider-view


Q: Trigger uses class, writing test case for that class does not increase trigger coverage? So I've got a trigger, T, for which i have class A which is where I stored all the "backend" logic.
The coverage for A is 100% but T has not seen any coverage increase and I'm wondering if this is normal behavior and if not how I go about doing so?

A: Okay, I THINK I figured it out - the trigger's code coverage describes the lines covered by the trigger only, not the components that it is calling (which themselves should have tests, also).
I was very confused because the number of lines of code in my trigger is the same as the number of components (components meaning methods defined within some class) so I didn't understand why the coverage wasn't going up.


Q: Why a jquery datepicker change days for months? I'm working on MVC project, and using the jquery datepicker I have problems in the post.
I use a partial view which contains the text box and the jquery function. Like this:
 @model Nullable<System.DateTime>
<div class="row-fluid input-append">
    @if (Model.HasValue && Model.Value != DateTime.MinValue)
    {
        @Html.TextBox("", String.Format("{0:dd/MM/yyyy}", Model.Value), new { @class = "input-small date-picker",@readonly = true, style = "cursor:pointer; background-color: #FFFFFF; text-align: center;" })
    }
    else
    {
        @Html.TextBox("", String.Format("{0:dd/MM/yyyy}", ""), new { @class = "input-small date-picker", @readonly = true, style = "cursor:pointer; background-color: #FFFFFF; text-align: center;" })
    }
</div>

@{
    string name = ViewData.TemplateInfo.HtmlFieldPrefix;
    string id = name.Replace(".", "_");
}

<script type="text/javascript">
    $('#@id').datepicker({
        dateFormat: 'dd/mm/yy',
        todayHighlight: true,
        clearBtn: true,
        forceParse: true,
        autoclose: true,
    });
</script>

When I format the datepicker to pick the date in days/months/years, and when I pick a date the format it's ok! I mean, I select 5th of august in the calendar, and the textbox shows 05/08/2013, but the problem arise when a click save because, in the controller, the value on the date is changed days to months!
Thanks!

A: In web.config add the following:
<system.web>
    <globalization culture="en-GB" uiCulture="en-GB" />
</system.web>

It should change the default date parsing.


Q: Read or Fetch all the column headers in a excel sheet I wanted to just read all the column headers of my excel sheet.

public class Reader_2 {
        public static final String SAMPLE_XLSX_FILE_PATH = "C:/Users/kqxk171/Documents/Records Management
  Application/9.2_initial_test_report.xlsx";

    public static void main(String[] args) throws IOException {
    Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
    System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");

    Iterator<Sheet> sheetIterator = workbook.sheetIterator();

    System.out.println("Retrieving Sheets using Iterator");
    while (sheetIterator.hasNext()) {
        Sheet sheet = sheetIterator.next();
        System.out.println("=> " + sheet.getSheetName());
    }
    Sheet sheet = workbook.getSheetAt(0);

    DataFormatter dataFormatter = new DataFormatter();

    for (Row row: sheet) {
        for(Cell cell: row)
        {
            row.getRowNum();
            String cellValue = dataFormatter.formatCellValue(cell);

            System.out.print(cellValue + "\t");
        }
        System.out.println();
    }

}

}


Q: Accessing a dataframe column with index I have dataframe with A,B,C as its columns. I have set an index on it using
df.set_index('A')

Now I want to filter rows using a condition statement like
df[df.loc['A'] == '10001']

This gives me the following error:
KeyError: 'the label [A] is not in the [index]'

How do I apply a condition on the column I have set as an index?

A: You have to specify 'inplace=True'
df.set_index('A', inplace=True)

otherwise it doesn't persist.

A: Consider this df
        val
A
10001   5
10002   6
10003   3

You can filter the rows using
df[df.index == '10001']

You get
        val
A
10001   5


Q: What exception to throw - "Wrong Scenario" (Java) This is a silly question - but it bugs me.
From the existing (library) Java exceptions, which should I throw in the following.
I have a method that is used in the wrong scenario (it's basic assumption doesn't hold).
This method has no arguments - so I tend to skip the IllegalArgumentException.
As an example - consider a BinaryNode class having just two left/right child nodes.
For brevity it's nice to have a removeOnlyChild() method, which applies only if this node actually has just one child (not 0 or 2).
Obviously if someone calls n.removeOnlyChild() on a node n that has 2 children, an exception should be thrown.
Out of the standard Java exceptions - which do you think it should be, and why?
I'm actually going over the list every-once-in-a-while, when this pops-up, and just go with IllegalStateException or with InternalError.

A:
I have a method that is used in the wrong scenario (it's basic assumption doesn't hold).

That sounds like an exact match for IllegalStateException:

Signals that a method has been invoked at an illegal or inappropriate time.

Admittedly the "time" part feels a little misleading, but given the name it seems reasonable to extend the meaning to "a method has been invoked when the object is in an inappropriate state for that call". Your use is similar to that of Iterator.remove() which throws IllegalStateException if the iterator is before the first element or has already removed the "current" element.
I'd definitely go with that over InternalError which is for Virtual Machine errors, not application code errors.


Q: how can I use fs in react with electron? I want use react+webpack+electron to build a desktop app.How can I inject fs module into react so that I can use it to read native files?
I have a component such as:
class Some extends Component {
  render() {
    return
{this.props.content}

  }
}
export default Some;

in entry.js:
import React from 'react';
import { render } from 'react-dom';
import Some from './src/some.jsx';

const data = "some content";
/*
 How can I read data by fs module?
 import fs from 'fs' doesn't work here
*/
render(
  <Some content={data} />,
  document.getElementById('app')
);

I use webpack to build js codes into a bundle.js,and in index.html
...

...

In webpack.config.js:
...
plugins: [new webpack.IgnorePlugin(new RegExp("^(fs|ipc)$"))]
...

I find this config on the internet because if I don't add it the webpack will report error,but I don't know how this means.
And I have a very easy main.js which is the same as electron-quick-start's main.js
Do I lose some important things?
It can't be better if u can provide a existed example on github repo.

A: The easiest thing to do is probably to use webpack-target-electron-renderer, you can find examples of using it in electron-react-boilerplate.

A: First of all: Don't lost time with webpack with react and electron, react already have everything it need itself to pack themself when building.
As Hossein say in his answer:
const fs = window.require('fs');

that works for me.
Additionally on webpreferences on the main.js of electron i set this settings:
webPreferences: {
  preload: path.join(__dirname, 'preload.js'),
  nodeIntegration: true,
  enableRemoteModule: true,
  contextIsolation: false,
  nodeIntegrationInWorker: true,
  nodeIntegrationInSubFrames: true
}

following the electron website that webpreferences are a security problem so we need to found a better a more safer ways as described here

A: use window.require() instead of require().
const fs = window.require('fs');

A: Since Electron 12 contextIsolation is true by default and it is recommended.
So with nodeIntegration: true and contextIsolation: true
First see https://www.electronjs.org/docs/latest/tutorial/context-isolation/
FIRST in preload.js expose the require function to renderer:
require: (callback) => window.require(callback)

THEN in renderer you can import it by:
const { myAPI } = window
const fs = myAPI.require('fs')


Q: Does $\{\left|\varphi\right>\left<\psi\right|+\left|\psi\right>\left<\varphi\right||\varphi\in\{\psi\}^{\perp}\}$ split $\mathfrak{S}_1$? Let $\mathfrak{S}_1$ be the space of trace-class self-adjoint operators on $L^2(\mathbb{R}^n)$, and $\psi\in L^2(\mathbb{R}^n)$ such that $\int |\psi|^2 = 1$. Is there a projection from $\mathfrak{S}_1$ onto $$\left\{ \left|\varphi\right>\left<\psi\right|+\left|\psi\right>\left<\varphi\right|| \varphi\in\{\psi\}^{\perp}_{L^2}\right\} ?$$

If needed, one can change $\mathfrak{S}_1$ for $\mathfrak{S}_1 \cap \{ tr \cdot = 0  \}$ its subspace of vanishing-trace operators. A first question would be whether $\left\{ \left|\varphi\right>\left<\psi\right|+\left|\psi\right>\left<\varphi\right|| \varphi\in\{\psi\}^{\perp}_{L^2}\right\}$ is closed in $\mathfrak{S}_1$.

A: Yes, there is an ${\mathbb R}$-linear projection of norm one.
Let $P^\perp$ denote the orthogonal projection onto $\{\psi\}^\perp$.
The projection is given by
$$\Theta\colon S \mapsto |P^\perp \frac{S+S^*}{2}\psi \rangle \langle \psi |\,
 +\, | \psi\rangle \langle  P^\perp \frac{S+S^*}{2}\psi |$$
for $S\in{\mathfrak S}_1$.
To prove $\Theta$ has norm one, we may assume that $S=S^*$.
By considering the decomposition $L^2({\mathbb R})=\{\psi\}^{\perp\perp}\oplus\{\psi\}^\perp$,
the map $\Theta$ looks like
$$S=\left[ \begin{matrix} \alpha & \langle\phi| \\ |\phi\rangle & B \end{matrix}\right]
\mapsto \left[ \begin{matrix} 0 & \langle\phi| \\ |\phi\rangle & 0 \end{matrix}\right]
=|\phi \rangle \langle \psi |\, +\, | \psi\rangle \langle \phi|.$$
One has
$$2\|\phi\|^2=|\langle\phi|S\psi\rangle|+|\langle\psi|S\phi\rangle|\le\|S\|_1\|\psi\|\|\phi\|$$
because $\phi\perp\psi$.
One the other hand,
$$\|\,|\phi \rangle \langle \psi |\, +\, | \psi\rangle \langle \phi|\, \|_1 = 2\|\phi\|$$
by, e.g., considering the two dimensional subspace spanned by $\phi$ and $\psi$.
By combining these, one sees $\Theta$ has norm one.


Q: Posterior mean if signal is an interval rather than a realization Suppose that a signal or observation $s_1$ is drawn from the normal distribution $\mathcal{N}(\mu,\sigma^2)$, where $\sigma^2$ is known but $\mu$ is not. We want to estimate $\mu$ based on $s_1$.
Suppose further we have a normal prior distribution for $\mu$, which is $\mathcal{N}(\mu_0,\sigma_0^2)$.
In this case it is easy to determine the posterior distribution given $s_1$, which is normal (normal is a conjugate prior), and the posterior mean is also easy to determine as
$$E[\mu|s_1]=\frac{\mu_0/\sigma_0^2+s_1/\sigma^2}{1/\sigma_0^2+1/\sigma^2}.$$
Now to my question: But what if we cannot observe $s_1$ directly; instead, we only know whether the realization of $s_1$ is above or below a certain threshold $t\in\mathbb{R}$. That is, instead of observing $s_1$, we only observe $\mathbf{1}\{s_1\ge t\}$ ($\mathbf{1}$ is the indicator function).
Since the "evidence" is now an interval rather than a point realization, how to compute the posterior mean $E[\mu|\mathbf{1}\{s_1\ge t\}]$? Is the posterior distribution even normal? I am at a loss here. Any help or references to help would be greatly appreciated.
Edit: I computed the posterior distribution numerically. See the plot below (where the "signal" indicates the realization is above a threshold). The posterior density is clearly not symmetric, hence not normal. So the question remains: Is there a closed form expression for the posterior density, or a somewhat simple expression for the posterior mean?

A: Definitions

*

*$X \sim \mathcal{N}(\mu,\sigma^2)$, with $\sigma$ known and $\mu$ the parameter of interest

*$\mu_0$ and $\sigma_0$ are hyperparameters describing the prior probability distribution of $\mu$ such that $\mu\sim\mathcal{N}(\mu_0,\sigma_0)$ and $p(\mu|\mu_0,\sigma_0) = \mathcal{N}(\mu_0,\sigma_0)$

*$x$ is the observation, $p(\mu|x,\mu_0,\sigma_0)$ is the posterior probability we seek.
Bayesian Inference
Here's the Wikipedia reference for the formulas.
$$p(x|\mu_0,\sigma_0)=\int p(x|\mu,\sigma)p(\mu|\mu_0,\sigma_0)d\mu$$
$$p(\mu|x,\mu_0,\sigma_0) = \frac{p(x|\mu,\sigma)p(\mu|\mu_0,\sigma_0)}{p(x|\mu_0,\sigma_0)}$$
Interval evidence
Since we do not have a fixed $x$ but some evidence of the kind $x>t$, we must adjust the probabilities of $x$, $p(x)$ and change them to $f(t)=1-c(t)$ where $c(t)$ is the cumulative distribution function.
The $c(t)$ for a normal function is an appropriately scaled sigmoid function, which in case of a standard normal is $\frac12 +\frac12\text{erf}(\frac{x}{\sqrt{2}})$, where $\text{erf}$ is the error function.
$p(x|...)$ now becomes $p(x\geq t|...) = f(t|...)$.
Calculations
$$f(t|\mu,\sigma) = \frac12 - \frac12\text{erf}\left(\frac{t-\mu}{\sigma\sqrt2}\right)$$
$$p(\mu|t,\mu_0,\sigma_0) = \frac{f(t|\mu,\sigma)p(\mu|\mu_0,\sigma_0)}{\int f(t|\mu,\sigma)p(\mu|\mu_0,\sigma_0)d\mu}=\frac{(\frac12-\frac12\text{erf}(\frac{t-\mu}{\sigma\sqrt2}))(\frac{1}{\sqrt{2\pi\sigma_0^2}}\exp{-\frac{(\mu-\mu_0)^2}{2\sigma_0^2}})}{\int_{-\infty}^{\infty}(\frac12-\frac12\text{erf}(\frac{t-\mu}{\sigma\sqrt2}))\Biggl(\frac{1}{\sqrt{2\pi\sigma_0^2}}\exp{-\frac{(\mu-\mu_0)^2}{2\sigma_0^2}}\Biggr)d\mu}$$
The denominator is simply a scaling factor which can be ignored for the time. On qualitative analysis, the $\text{erf}$ term will scale the normal differentially for different values of $\mu$ resulting in an assymmetric skewed distribution finally. The exact scaling depends on the particular values.
Plot the numerator normalized for unit area to get the graph you seek.


Q: cshtml Razor Error messages, Conditional Formatting I'm having a strange issue with my CSHTML files this morning. One moment everything is working fine... then next moment, everything is still working, but all my code highlighting for anything with @ infront of it has gone.
The project still compiles and runs fine, but I'm getting red highlights where ever there is a
Code block.
There are loads of posts for Conditional Formatting on this site, but they all suggest changing the code. I don't want to change any code, it's all working fine. I just want to get the yellow colouring behind the @ back.
It's all working fine in the aspx files. I can't think of what I did to turn this off.

Edit
I've created a new project and copied every code file over manually.
This is how it looks in the new project.

And like this in the old

A: That's a bug in Visual Studio. You can't do anything about it. It's just that the dudes at Microsoft didn't get Syntax Highligthing and Intellisense right in Razor views. Hopefully they will in some future version of Visual Studio.
There's nothing wrong with the code you have shown. It works perfectly fine at runtime. Just the tools you are using aren't capable of realizing that.


Q: cufon glyphs support I have a problem with cufon and a few Turkish glyphs. This is the context:
I used the @font-face property to embed the custom font (Delicious-Roman) on a website. The client didn't like the fact that the font was the last one to load on each page (common issue with font-face) so I switched to cufon. When I was using font-face all the characters worked as they should, but when I used cufon a few glyphs stopped working (they simply don't show up on the page). I opened up Photoshop to test the font and indeed it doesn't have those Turkish characters (ğĞİşŞ).

*

*Why the font-face property managed to show all the characters even if the font didn't have them?

*How can I add those Turkish characters (ğĞİşŞ) to cufon?

I tried the "...and also these single characters" option on the cufon website but it didn't worked. I simply inserted the characters - ğĞİşŞ - in that text field. Is that correct?
If there is no way to add these glyphs to cufon, what is the easiest way to add them directly in the font I use?

A: The easiest way I found was to simply include the missing characters into the font and the re-use cufon. For this task I used the Glyph App - Demo version works perfectly for 30 days and you can export fonts without restriction.


Q: Fade in/out transition between pages I've written the following to create a fade in/out transition between pages. On my local setup, the page loads in smoothly, but there's no exit animation whatsoever on beforeunload, which is obviously pretty jarring.
I've created a quick demo of what I'm currently using on JSFiddle: https://jsfiddle.net/6r605auw/
Is this even the best way to handle this? If you've any suggestions as to why the beforeunload animation seems to be failing, or if you've got a better way, then I'd love to hear them.
jQuery(document).ready( function($){
  $('body').css('display, none');
  $('body').fadeIn(1000);
});

$(window).on('beforeunload', function() {
  $('body').fadeOut(1000);
});

A: You can try to use the History API with pushState and popState - in order to move from page to page seamlessly. What you're doing is bad and the mistake you're making will be more visible as more elements you put in your page.
At the time JS kicks in (and DOM is ready etc) it's already too late to do hide() or .css({display: "none"}) because the page was building and visible. You'll end up having an ugly flashy unstable-looking website/application :(
The "other" solution is to hide initially using CSS... but search engines will penalize you for that.
Use an overlay
A better way is to have a fixed full-size CSS visible overlay element -

that overlays your entire page content - and JS-(+CSS3) fadeOut that element instead (by adding a CSS class like)
#loaderOverlay{
    position: fixed;
    z-index: 99999;
    top:0; left:0; right:0; bottom:0;
    background: #fff;
    transition: 2s;       /* transition timing */
}
#loaderOverlay.hide{      /* JS-add this class on DOM ready or window load */
   visibility: hidden;
   opacity: 0;
}

Triggering the "fadeOut" in jQuery look like:
$(window).on("load", function(){
   // The overlay is initially visible, we need to hide it!
   $("#loaderOverlay").addClass("hide"); // CSS3 will animate it nicely
});

Now, the fadeIn problem...
the **beforeunload** event will kick in at the moment when the page resources are just about to be unloaded.
The unloading can last a couple of ms (+ waiting for HTTP requests...), clearly not enough time for an animation of 2s to take place - and the only way I see fit is to target all your links on the page, get the href attribute, prevent the browser to navigate - and navigate only on transitionend (not well supported) or after a 2100ms timeout period:
// When we click on some link we want our overlay to show up!
// Additionally instead of `"a"` you could make sure it's not an external link,
// a #hash anchor etc...

$(document).on("click", "a", function(evt) {

  evt.preventDefault(); // Don't navigate!

  var href = $(this).attr("href"); // grab the href

  // Animate-In our overlay
  $("#loaderOverlay").removeClass("hide");

  // wait for CSS3 to animate-in the overlay and than navigate to our next page

  setTimeout(function() {
     window.location = href; // Navigate finally
  }, 2100);

});

as you can see the above works for links, but clearly the browser's Back button is not a link in your page, and for that... recurse to the beginning of my answer.


Q: CSS: Show an element only when you hover over it The following hides the element, but I cannot recover when I hover over it.
I've checked devtools to see that it is indeed rendered on the screen, I just can't see the contents of the div.
How do I make it so the div is visible only on hover?
.visible-on-hover {
  visibility: hidden;
}

.visible-on-hover:hover {
  visibility: visible !important;
}

A: Elements with  visibility: hidden; don't receive any mouse events, so :hover never triggers on such an element.
Instead of visibility, you can work with opacity:

div {
  background-color: orange;
  height: 200px;
  width: 400px;
  padding: 50px;
}

.visible-on-hover {
  opacity: 0;
  transition: opacity .3s ease;
}

.visible-on-hover:hover {
  opacity: 1;
}

visible only on hover

A: you can not hover, focus or select a hidden element.
you can use opacity
.visible-on-hover {
  opacity: 0;
}

.visible-on-hover:hover {
  opacity: 1;
}


Q: How to get an image to stretch on a multi-screen setup? I have 3 monitors (each 1600x1200) setup in a following configuration:

I have a image that is 4800x1200, thus should neatly fit across three screens.
However, no matter what I tried it won't stretch across the screens.
If I select Fill, it take a third of the entire image and places a copy on each monitor.
If I select Fit, it compresses the image and places a miniature copy of it on each monitor.
If I select Stretch, it compresses 4800x1200 image into 1600x1200 and places it on each monitor.
If I select Tile, it's probably the closest to what I want, but it places left part of the image on my monitor 1, middle part on monitor 2 and right part on monitor 3.  If my main monitor was on the very left, this would work, but I don't like that type of setup.
If I select Center, ...I can't even figure out what's doing here, but it's not usable.
How do I get the image to properly lay out across my monitors?

A: Tile is the correct option. A workaround would be to edit the image so that it matches your display setup, i.e. instead of [1|2|3], the resulting image could be rearranged as [3|1|2].


Q: Why does my oAuth signature need "%26" at the end? I am working with imgur's API and need to set up oAuth authentication. It's going pretty smoothly but I ran into a snag...
I couldn't get the oAuth request_token endpoint to give me a success message, so I contacted the imgur devs and they gave me a critical piece of information. However, I could not find where this information comes from.
The information I am talking about is my oAuth signature. I knew the oAuth signature is just my api_secret, but in the working code provided by the imgur dev there was an ampersand tagged on the end.
This ampersand was URL-encoded, twice. It went from & to %26, then to %2526
API Secret        => 7fc6ff69*snip*c4016e7f99e076 // This does not work by itself
[oauth_signature] => 7fc6ff69*snip*c4016e7f99e076%2526 // Works
[oauth_signature] => 7fc6ff69*snip*c4016e7f99e076&  // This also works

Why is an ampersand required? Is this a bug, or is it actually mentioned somewhere in the oAuth 1.0 documentation? Is it always an ampersand, or is that just a strange coincidence? I have no idea where it came from...
EDIT: It's worth mentioning that the oauth_signature is the last variable in the request, so it should not be merging with another variable. Basically, The end of the URL must end with an ampersand (or html-encoded version of one).

A: For protected OAuth requests, the signature is typically generated by using a pair of secrets (often a shared secret and an authorized token secret).  As you've probably guessed, an ampersand ("&") is used to separate the two secrets.  However, when a single secret is used as the signature (as with imgur) the ampersand is still required, but because there is no second secrete to separate, the ampersand appears at the end of string. Another way to think of it is the ampersand is separating the api_secret and an empty secret.


Q: ES6 / JS: Regex for replacing delve with conditional chaining How to replace delve with conditional chaining in a vs code project?
e.g.
delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")

desired result
seo?.meta
item?.image.data.attributes.alternativeText

Is it possible using find/replace in Visual Studio Code?

A: I propose the following RegEx:
delve\(\s*([^,]+?)\s*,\s*['"]([^.]+?)['"]\s*\)
and the following replacement format string:
$1?.$2
Explanation: Match delve(, a first argument up until the first comma (lazy match), and then a second string argument (no care is taken to ensure that the brackets match as this is rather quick'n'dirty anyways), then the closing bracket of the call ). Spacing at reasonable places is accounted for.
which will work for simple cases like delve(someVar, "key") but might fail for pathological cases; always review the replacements manually.
Note that this is explicitly made incapable of dealing with delve(var, "a.b.c") because as far as I know, VSC format strings don't support "joining" variable numbers of captures by a given string. As a workaround, you could explicitly create versions with two, three, four, five... dots and write the corresponding replacements. The version for two dots for example looks as follows:
delve\(([^,]+?)\s*,\s*['"]([^.]+?)\.([^.]+?)['"]\s*\)
and the format string is $1?.$2?.$3.
You write:

e.g.
delve(seo,'meta')
delve(item, "image.data.attributes.alternativeText")
desired result
seo?.meta
item?.image.data.attributes.alternativeText

but I highly doubt that this is intended, because delve(item, "image.data.attributes.alternativeText") is in fact equivalent to item?.image?.data?.attributes?.alternativeText rather than the desired result you describe. To make it handle it that way, simply replace [^.] with . to make it accept strings containing any characters (including dots).


Q: Why is my @@Version unchanged after upgrading? I have SQL Server 2008 R2. I installed SQL Server 2014 with the option:

Upgrade from SQL Server 2005, SQL Server 2008, SQL Server 2008 R2 or SQL Server 2012

and the process ended correctly.
But when running on localhost:
SELECT @@Version

I still have:

Microsoft SQL Server 2008 R2 (SP2) - 10.50.4042.0 (X64)

Sorry if the question is basic but I am very lost at the moment.

A: I found the problem: The installer I had was just for SQL Server Management Studio, as @MarkSinkinson pointed out.
If you have this same problem, verify you have the correct installation file (not SSMS only, or an incompatible Edition).
Other helpful things to check, from comments originally left on the question:

*

*You may have multiple instances installed, upgraded one of them, and connected to another. Or the upgrade didn't take (this can be easy to dismiss without noticing in the final step of the upgrade wizard). Please note that 2008 and 2008 R2 are completely separate, independent releases.

*Make sure that you are connected to right instance in any case.

*Check you didn't uncheck the database engine installation option

A: You didn't select any instance when upgrading, just repeat the process and in step "select instance" choose the one you want to upgrade.
Hope it helps


Q: How could 32bit kernel read efivars from 64bit UEFI? I'm booting a GRUB EFI application compiled to x86_64-efi, on a x86_64 firwmare in UEFI only mode.
This GRUB app launches a 32bit Linux v3.18.48, with CONFIG_EFIVAR_FS=y and CONFIG_EFI_VARS=y.
Now I want to read some efivars, but I cannot even mount the efivarfs:
mount -t efivarfs efivarfs /sys/firmware/efi/efivars

which returns "No such device" (ENODEV).
It was expected since dmesg says:
No EFI runtime due to 32/64-bit mismatch with kernel

Looking at the Linux source:
     if (!efi_runtime_supported())
         pr_info("No EFI runtime due to 32/64-bit mismatch with kernel\n");
     else {
         if (efi_runtime_disabled() || efi_runtime_init())
             return;
     }

and
static inline bool efi_is_native(void)
{
    return IS_ENABLED(CONFIG_X86_64) == efi_enabled(EFI_64BIT);
}

static inline bool efi_runtime_supported(void)
{
    if (efi_is_native())
        return true;

    if (IS_ENABLED(CONFIG_EFI_MIXED) && !efi_enabled(EFI_OLD_MEMMAP))
        return true;

    return false;
}

seems that efi_runtime_supported() will always return false to me, since CONFIG_X86_64=n and CONFIG_EFI_MIXED depends on CONFIG_X86_64=y.
Is there any workaround that could allow me to read the efivars, under these conditions?
Constraints:

*

*x86_64 firmware with UEFI only mode;

*GRUB x86_64-efi will launch Linux;

*Linux kernel v3.18.48 (may be patched), 32bits.

A: No, the 32-bit OS can't make 64-bit UEFI calls.
I hesitate to say anything can't be done in software, but this is about as close to impossible as you can get. You can't make 64-bit UEFI calls without switching to 64-bit mode, which would be extremely difficult to do the after the 32-bit OS boots.
One possible approach would be to change GRUB to read the variables and save them and provide a 32-bit interface for the OS to retrieve them. Since GRUB doesn't generally persist after the OS boots, this would be a significant change.

A: I was able to boot a 32-bit Ubuntu on 64-bit EFI machine with help of package grub-efi-amd64-signed, installed via chroot.
See the HowTo here (in German): https://wiki.ubuntuusers.de/Howto/Installation_von_32-Bit_Ubuntu_auf_EFI-System/
Anyway I sometimes have trouble, when GRUB gets updated.


Q: Rendering dinamically GenericHtmlControl/Literal merged with an Asp.net Control My Environment is: ASP.NET 4.62 / C# / Boostrap 4 framework
My application renders bootstrap 4 menu from database query.
I've a div in aspx page

and i add code behind as
 myNav.InnerHtml = mystr.ToString()

Now i need to integrate in the menu a LoginView asp.net control.
Obviously if i add
<asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled">

as string, the browser will receive a string a not renders a control ASP.NET.
I need to render something like this
....previous items menu
<asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled">
<AnonymousTemplate>

Login

 Login

</AnonymousTemplate>
<LoggedInTemplate>

     Hallo,
        <asp:LoginName runat="server" CssClass="username" />
        !
       <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Exit"
       LogoutPageUrl="~/Logout.aspx" />

 </LoggedInTemplate>
 </asp:LoginView>
...closing boostrap menu tag

Which is best way to resolve this type of problem ?
I need to change approach ?

A: You are creating the HTML at the server side; that is a possibility, but as you see, it makes it hard to combine this with ASP.NET server controls.
It would be better to put the HTML on the .aspx-page. I understand that your database knows which menu-items should be visible. And that you want to add 1 additional item, where users can login.
You could use (for example) a GridView with one column.
<Columns>
   <asp:TemplateField>
      <ItemTemplate>

Your HTML here

<%# Item.SomeProperty %>

      </ItemTemplate>
   </asp:TemplateField>
</Columns>

Use the data from your database to render one 'row' per menuitem in the grid. You can customize the TemplateField so it contains the bootstrap-layout as you need it.
It might also be possible to keep your current approach. I think then you should at least not create your opening and closing bootstrap-menu tags in the code-behind. You should put those tags on the .aspx-page itself, the structure would then be:
<opening tag bootstrap menu>

<asp:LoginView id="LoginView1" runat="server" ViewStateMode="Disabled"> ... </ ..>
<closing tag bootstrap menu>


Q: image.Save lossless quality, in XP, pixelated on Windows7? So I've come across a rather odd situation.
I'm using the following to Save a PNG (lossless) image,
    public static void SaveJpeg(string path, Image image, int quality)
    {
        if ((quality < 0) || (quality > 100))
        {
            string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality.  A value of {0} was specified.", quality);
            throw new ArgumentOutOfRangeException(error);
        }
        EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
        ImageCodecInfo imgCodec = GetEncoderInfo("image/png");
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = qualityParam;
        image.Save(path, imgCodec, encoderParams);
    }

public static ImageCodecInfo GetEncoderInfo(string mimeType)
    {
        string lookupKey = mimeType.ToLower();
        ImageCodecInfo foundCodec = null;
        if (Encoders.ContainsKey(lookupKey))
        {
            foundCodec = Encoders[lookupKey];
        }
        return foundCodec;
    }

This code works great in XP, the image gets saved lossless, when I zoom in, I see no pixelation whatsoever however, when this same compiled application is ran on a windows7 machine, the saved image looks pixelated.
Is this due to the way I'm saving the image or perhaps something changing with the image save functionality / encoding in windows 7?

A: Your Win7 image is anti-aliased.
This is good, not bad; it makes the text smoother.
It's controlled by properties in the Graphics class.


Q: Set the selectedIndex property and selectedItems is empty I have an wpf application that use the MVVM with a datagrid. I set the selectedIndex property in the viewModel, but the SelectedItems property is empty. Shouldn't it have the selected the selected item?

A: Not necessarily.
One way of doing this is to set SelectedItem property in the datagrid xaml to a property on your view model which implements INotifyPropertyChanged.
Then set the xaml binding mode to two way.
Then if you click on a selected item it will trigger a change from the xaml binding to update the value in the view model