text:
Q: How to find method implementation in numpy repo I just read about the Box-Mueller approach for generating normal random variables and want to see if the method in numpy python uses the same approach. To this end, I want to look at the source code. I've been combing through the GitHub repository but haven't had any luck yet. The folder "random" seems to not have the code I'm interested in. In particular, I want the code that is invoked when calling -
import numpy as np
rand = np.random.normal(size=10)

Is anyone able to point me to this part of the code and generally explain how to effectively perform these kinds of searches.
EDIT: The line of code below isn't of much help in this case since it just points to the init.py file that doesn't have too much in it.
print(numpy.random.__file__)

A: It looks like the code you are looking for is here:
https://github.com/numpy/numpy/blob/464f79eb1d05bf938d16b49da1c39a4e02506fa3/numpy/random/mtrand/mtrand.pyx#L1551
As you can see, it's located under random/mtrand/mtrand.pyx. If you are wondering about .pyx: Cython states:

"A .pyx file is compiled by Cython to a .c file, containing the code of a Python extension module. The .c file is compiled by a C compiler to a .so file (or .pyd on Windows) which can be imported directly into a Python session."

You were looking for the definition of normal so I searched for "def normal".
Here's the code at that link:
def normal(self, loc=0.0, scale=1.0, size=None):
    """
    normal(loc=0.0, scale=1.0, size=None)
    Draw random samples from a normal (Gaussian) distribution.
    The probability density function of the normal distribution, first
    derived by De Moivre and 200 years later by both Gauss and Laplace
    independently [2]_, is often called the bell curve because of
    its characteristic shape (see the example below).
    The normal distributions occurs often in nature.  For example, it
    describes the commonly occurring distribution of samples influenced
    by a large number of tiny, random disturbances, each with its own
    unique distribution [2]_.
    Parameters
    ----------
    loc : float or array_like of floats
        Mean ("centre") of the distribution.
    scale : float or array_like of floats
        Standard deviation (spread or "width") of the distribution.
    size : int or tuple of ints, optional
        Output shape.  If the given shape is, e.g., ``(m, n, k)``, then
        ``m * n * k`` samples are drawn.  If size is ``None`` (default),
        a single value is returned if ``loc`` and ``scale`` are both scalars.
        Otherwise, ``np.broadcast(loc, scale).size`` samples are drawn.
    Returns
    -------
    out : ndarray or scalar
        Drawn samples from the parameterized normal distribution.
    See Also
    --------
    scipy.stats.norm : probability density function, distribution or
        cumulative density function, etc.
    Notes
    -----
    The probability density for the Gaussian distribution is
    .. math:: p(x) = \\frac{1}{\\sqrt{ 2 \\pi \\sigma^2 }}
                     e^{ - \\frac{ (x - \\mu)^2 } {2 \\sigma^2} },
    where :math:`\\mu` is the mean and :math:`\\sigma` the standard
    deviation. The square of the standard deviation, :math:`\\sigma^2`,
    is called the variance.
    The function has its peak at the mean, and its "spread" increases with
    the standard deviation (the function reaches 0.607 times its maximum at
    :math:`x + \\sigma` and :math:`x - \\sigma` [2]_).  This implies that
    `numpy.random.normal` is more likely to return samples lying close to
    the mean, rather than those far away.
    References
    ----------
    .. [1] Wikipedia, "Normal distribution",
           https://en.wikipedia.org/wiki/Normal_distribution
    .. [2] P. R. Peebles Jr., "Central Limit Theorem" in "Probability,
           Random Variables and Random Signal Principles", 4th ed., 2001,
           pp. 51, 51, 125.
    Examples
    --------
    Draw samples from the distribution:
    >>> mu, sigma = 0, 0.1 # mean and standard deviation
    >>> s = np.random.normal(mu, sigma, 1000)
    Verify the mean and the variance:
    >>> abs(mu - np.mean(s)) < 0.01
    True
    >>> abs(sigma - np.std(s, ddof=1)) < 0.01
    True
    Display the histogram of the samples, along with
    the probability density function:
    >>> import matplotlib.pyplot as plt
    >>> count, bins, ignored = plt.hist(s, 30, density=True)
    >>> plt.plot(bins, 1/(sigma * np.sqrt(2 * np.pi)) *
    ...                np.exp( - (bins - mu)**2 / (2 * sigma**2) ),
    ...          linewidth=2, color='r')
    >>> plt.show()
    """
    cdef ndarray oloc, oscale
    cdef double floc, fscale

    oloc = <ndarray>PyArray_FROM_OTF(loc, NPY_DOUBLE, NPY_ARRAY_ALIGNED)
    oscale = <ndarray>PyArray_FROM_OTF(scale, NPY_DOUBLE, NPY_ARRAY_ALIGNED)

    if oloc.shape == oscale.shape == ():
        floc = PyFloat_AsDouble(loc)
        fscale = PyFloat_AsDouble(scale)
        if np.signbit(fscale):
            raise ValueError("scale < 0")
        return cont2_array_sc(self.internal_state, rk_normal, size, floc,
                              fscale, self.lock)

    if np.any(np.signbit(oscale)):
        raise ValueError("scale < 0")
    return cont2_array(self.internal_state, rk_normal, size, oloc, oscale,
                       self.lock)

As mentioned here in a duplicate question (that I found after answering this) you can also try the following (but in this case it may not have gotten you much further than you did on your own):
import numpy.random
print(numpy.random.__file__)

# /home/adam/.pyenv/versions/datasci/lib/python3.6/site-packages/numpy/random/__init__.py

To trace the connection to rk_gauss you'll see rk_normal in the above code which links to:
double rk_normal(rk_state *state, double loc, double scale)
{
    return loc + scale*rk_gauss(state);
}

So its:
Here to here to here. I think that's just a matter of seeing what other functions the function you are interested in calls.


text:
Q: C method for moving structs between dynamic arrays i have a card game in C (i have to make it in C, class project). And i created a method for moving Structs from one dynamic array to another. Unfortunately the method works at first, but later when i call it in the program it starts throwing malloc() errors. Deck is a struct that contains a int size and a dynamically allocated Card *deck, and Card is a struct for holding a single card. Is there something i am missing, or that has to be defined in another way ?
void moveCard(Deck *src, Deck *dest, int n){
    Card *tmpCards = NULL;
    Card tmp = (*src).deck[n];                          // get card to be copied
    int newSize = dest->size + 1;                       //increase dest size by 1
    tmpCards = (Card *) malloc(sizeof(Card) * newSize); // allocate new memory area
    memmove(&(tmpCards[0]), &(dest->deck[0]), sizeof(Card) * (newSize - 1));
        // copy all the cards from old memory area to new area
    dest->deck = tmpCards;  // reassign old pointer to new memory area
    dest->size = newSize;   // reevaluate size
    dest->deck[newSize - 1] = tmp; // copy card to end of new area

    tmpCards = NULL; // empty out pointer (no functionality, just for easier reading)
    newSize = src->size; // reevaluate newSize
    tmpCards = (Card *) malloc(sizeof(Card) * (newSize - 1));
                     // allocate smaller mem area by 1
    memmove(&(tmpCards[0]),&(src->deck[0]), sizeof(Card) * (n));
                     // copy all cards up to the n-th point
    memmove(&(tmpCards[n]),&(src->deck[n+1]), sizeof(Card) * (newSize - n));
                     // copy all cards from the n+1 -th point

    src->size = newSize -1; // reevaluate size
    src->deck = tmpCards;     // reassign pointer

    // since all input parameters were pointers, no return is necessary
}

Edit: to the people concerned by the fact that I don't release memory. The original code has 2 free commands in them (free(dest->deck) and free(src->deck)). but only one of them worked. The other created again memory corruption for some odd reason, so I found it better, not to put them into this example.

A: I think you are running out of memory because you are not releasing any memory. You are only allocating new memory.
void moveCard(Deck *src, Deck *dest, int n){
    Card *tmpCards = NULL;
    Card tmp = (*src).deck[n];                          // get card to be copied
    int newSize = dest->size + 1;                       //increase dest size by 1
    tmpCards = (Card *) malloc(sizeof(Card) * newSize); // allocate new memory area
    memmove(&(tmpCards[0]), &(dest->deck[0]), sizeof(Card) * (newSize - 1));
        // copy all the cards from old memory area to new area

    // **** CORRECTION ****
    // Free previously allocated memory for dest->deck
    free(dest->deck);

    dest->deck = tmpCards;  // reassign old pointer to new memory area
    dest->size = newSize;   // reevaluate size
    dest->deck[newSize - 1] = tmp; // copy card to end of new area

    tmpCards = NULL; // empty out pointer (no functionality, just for easier reading)
    newSize = src->size; // reevaluate newSize
    tmpCards = (Card *) malloc(sizeof(Card) * (newSize - 1));
                     // allocate smaller mem area by 1
    memmove(&(tmpCards[0]),&(src->deck[0]), sizeof(Card) * (n));
                     // copy all cards up to the n-th point
    memmove(&(tmpCards[n]),&(src->deck[n+1]), sizeof(Card) * (newSize - n));
                     // copy all cards from the n+1 -th point

    src->size = newSize -1; // reevaluate size

    // **** CORRECTION ****
    // Free previously allocated memory for src->deck
    free(src->deck);

    src->deck = tmpCards;     // reassign pointer

    // since all input parameters were pointers, no return is necessary
}

PS You should use memcpy instead of memmove. memmove is the right function to use if the source and the destination overlap. memcpy is the right function to use if the source and the destination do not overlap.

redpajama_set_name: RedPajamaStackExchange


text:
Q: I can't figure out How to call previously created function inside another function? Here is my example:
//This is my first function created and works just fine
function fullName(firstName, lastName){
  console.log(firstName +" "+ lastName);
}
fullName("Jason", "Doe");

//Below is my second function created after the first function and now I want to call "Jason, Doe 33" inside a fullNameAndAge function getting the Jason Doe form above function.
function fullNameAndAge(firstName, lastName, age){

    console.log(firstName +" "+ lastName +" "+ age);
}
fullNameAndAge(fullName(), 33);

A: You have a few things wrong with this.

*

*You aren't returning anything from your functions.

*fullNameAndAge expects 3 arguments passed to it. Even if fullName returned something, it would only be passing 2 arguments to fullNameAndAge

*You aren't passing anything to fullName inside of your fullNameAndAge call.

Edit
Your code should look like this:

function fullName(firstName, lastName) {
        return firstName + " " + lastName;
    }

    fullName("Jason", "Doe");

    function fullNameAndAge(fullName, age) {
        console.log(fullName + " " + age);
    }

    fullNameAndAge(fullName("Jason", "Doe"), 33);

A: If you want to call one function from another then just simply do it.
Something like thisL

function fullName(firstName, lastName){
  console.log(firstName +" "+ lastName);
}

function fullNameAndAge(firstName, lastName, age){
    fullName(firstName, lastName);
    console.log(age);
}
fullNameAndAge('John', `Doe`, 33);

A: If you want to call the first function inside the second function then you can put it inside that function:
function fullNameAndAge(firstName, lastName, age) {
    fullName(firstName, lastName);
    console.log(firstName +" "+ lastName +" "+ age);
}
fullNameAndAge("Jason", "Doe", 33);

A: Is this what you were after?
function fullName(firstName, lastName){
  return (firstName +" "+ lastName);
}

function fullNameAndAge(firstName, lastName, age){

   return fullName(firstname, lastname)+" "+ age);
}
fullNameAndAge("Jason", "Doe", 33);

A: There are a few problems here. I will try to articulate as best I can what you are doing wrong and possible methods to fix.
First, You are calling fullName without its arguments here:
fullNameAndAge(fullName(), 33);

Once you define a function as taking a certain amount of arguments, you (generally speaking) always want to call it with those arguments.
Second, the function fullName does not return anything, it only calls console.log. In order for you to use the return value of fullName in fullNameAndAge, you must return the values from fullName. One suggestion would be
function fullName(firstName, lastName){
  return { firstName, lastName };
}

Here we are returning an object literal with the keys firstName and lastName mapping onto the values contained therein. We can now access this from fullNameAndAge:
function fullNameAndAge(fullNameObj, age){
  console.log(fullNameObj.firstName +" "+ fullNameObj.lastName +" "+ age);
}

So we can now call it like this:
fullNameAndAge(fullName("Jason", "Doe"), 33);

function fullName(firstName, lastName){
  return { firstName, lastName };
}

function fullNameAndAge(fullNameObj, age){
  console.log(fullNameObj.firstName +" "+ fullNameObj.lastName +" "+ age);
}

fullNameAndAge(fullName("Jason", "Doe"), 33);


text:
Q: Shall I use HSM to decrypt message instead of using an application server that link to HSM to decrypt the message Our company is using an HSM to store the private keys of individuals.  So the messages are all encrypted with their public keys.  The problem to me is that whether I should use a server to connect to the HSM to get the private key and then decrypt the message in the server or to pass the encrypted message to HSM and ask the HSM to decrypt for me (so that the key does not need to pass outside the HSM).  But, is HSM usuallyhas this function; if yes, will it be too slow?   The messages are emails and the instant messages.

A:
...whether I should use a server to connect to the HSM to get the private key and then decrypt the message in the server or to pass the encrypted message to HSM and ask the HSM to decrypt for me

If you have a proper HSM, never allow exporting the plain private keys out of it. Otherwise having an HSM to protect the keys would be useless. Just have the HSM to do the decryption on the data.
You can consider adding an application server to the picture anyway just to have an abstraction layer between your client applications and the HSM. Depending on the HSM you have, you probably have two options:

*

*Have an application server with a physical HSM attached (e.g. PCI-e card) exposing your own API to the client applications.

*Use networked HSM and register your application server as its client.

Typically (pretty much always) your code can consume the HSMs through PKCS#11 or similar interface / crypto engine (e.g. Chil for Thales HSMs).
Especially for PKCS#11 there are plenty of libraries available for almost any programming language. HSM vendors also often provide their set of software libraries for you to consume.
The bottom line is that if your HSM is a proper FIPS approved HSM, allowing exporting the private keys would make your money being wasted.

But, is HSM usuallyhas this function; if yes, will it be too slow?

Most of the general purpose HSMs are fast in general crypto operations. But again this depends greatly what kind of HSM you have.

A:
First rule of using HSM is never extract sensitive keys outside of
  HSM.

This is illogical because you pay huge amount of money to purchase a HSM to store keys on it but your keys are still outside of HSM.
HSMs are for encrypting-decrypting small amount of data not for mass data cryptographic processing. For Emv cards,PINS, cryptograms etc. only small amounts are processed.
If you want to encrypt messages and emails(I think they are multiple MB size) you need to have multiple HSMs depends on your needs and its expensive.
On my previous company we had a solution to similar problem.  We have a Master Key on HSM that encrypt localy used master keys(LUMK) that used for encryption of mails,messages etc. We store LUMKs on database encrypted and when we need those keys we simply decrypt them on HSM and use on our program for cryptographic processing. This scheme provide sufficient protection for our keys and data.


text:
Q: R: How to convert the output-list from a FQL-query into a data.frame? I wonder how to transform a list generated by a FQL-query into a structured data frame.
I use Rfacebook to ask FQL-queries like:
getFQL("SELECT name, friends_count, sex, languages FROM user WHERE uid IN
       (SELECT uid2 FROM friend WHERE uid1=me()), token)

This provides me with a list as output, which looks like:
[[1]]
[[1]]$name
[1] "Peter Fuller"

[[1]]$friend_count
[1] 186

[[1]]$sex
[1] "male"

[[1]]$languages
list()

[[2]]
[[2]]$name
[1] "Max Tester"

[[2]]$friend_count
[1] NULL

[[2]]$languages
[[2]]$languages[[1]]
[[2]]$languages[[1]]$id
[1] 1.056736e+14

[[2]]$languages[[1]]$name
[1] "English"

[[2]]$languages[[2]]
[[2]]$languages[[2]]$id
[1] 1.060595e+14

[[2]]$languages[[2]]$name
[1] "Italian"

[[2]]$languages[[3]]
[[2]]$languages[[3]]$id
[1] 1.144157e+14

[[2]]$languages[[3]]$name
[1] "Persian"

My aim is to convert the list into a data frame, such that the list above looks like:
          name friend_count                    languages
1 Peter Fuller          186                          NA
2   Max Tester           NA   Englisch, Italian, Persian

Unfortunately, my efforts with unlist() and matrix failed.

A: First unlist each record separately giving LL, then concatenate into a common string components with the same name using tapply and toString.  Then use rbind.fill from plyr to create the final data frame:
library(plyr) # rbind.fill

LL <- lapply(L, unlist)
fun <- function(x) as.data.frame(as.list(tapply(x, names(x), toString)))
do.call(rbind.fill, lapply(LL, fun))

giving:
  friend_count         name  sex                             languages.id
1          186 Peter Fuller male                                     <NA>
2         <NA>   Max Tester <NA> 1.056736e+14, 1.060595e+14, 1.144157e+14
             languages.name
1                      <NA>
2 English, Italian, Persian

Note that we assumed this input:
L <- list(list(name = "Peter Fuller", friend_count = 186, sex = "male",
     languages = list()),
  list(name = "Max Tester", friend_count = NULL,
      languages = list(list(id =  1.056736e+14, name = "English"),
        list(id = 1.060595e+14, name = "Italian"),
        list(id = 1.144157e+14, name = "Persian"))))


text:
Q: Uploading an image file with Nightwatch.js I'm running front-end tests using nightwatch.js using the Chrome Driver. I need to test that image uploading works properly, presumably through the provided file input since there are callbacks that run on a successful post.
I'm aware that this can be done using sendKeys method of the Selenium Web Driver.
How can you accomplish this using javascript and nightwatch.js?
Can you access the Selenium webdriver or an interface with it?

A: Use this for uploading image from local desktop
.setValue('input[type="file"]', require('path').resolve('/home/My-PC/Desktop/img.png'))

A: As someone above has mentioned, you can pass the absolute path to your input[type="file"] as if you were typing text into a field.
This uses nightwatch's setValue function. You can retrieve the current directory path using Node's __dirname global var.
For example:
.setValue('#upload-input', __dirname + '\\upload.jpg')

A: Use client.setValue function to set the absolute path of your image. Here is the working example in my project.
client.setValue('#editPictures .modal-body input[type="file"]', '/Users/testing/pictures/CAM00003.jpg');

A: In my case there is a div with id="Upload Icon" which has input with type="file"
.setValue('//div[@id="Upload Icon"]/input[@type="file"]', require('path').resolve(__dirname + '/categoryIcon.png'))

The above code working fine for me.

A: This solution worked for me:
.setValue('#file-upload', require('path').resolve('C:/Users/Mihai/Desktop/test.png'))

A: this worked for me.
.setValue('input[type="file"]', require('path').resolve('/home/My-PC/Desktop/img.png'))
Only thing maybe others running into might the different versions of firefox where it didn't work 2 yrs back for a co-worker.


text:
Q: MySQL - SELECT something IF (something is true) I've got a database with 3 columns, "ID", "username", "password". I'm pretty new on SQL (still learning :P ), and well, I'm not able to get my idea working. This is for an Android app. I've made an login, you enter the login data and I've arranged everything for working but this:
I need a SQL query that retrieves ID of the account ONLY IF username and password matches. This is what I've so far:
<?php
    $username = $_POST['username'];
    $password = $_POST['password'];
    $hostname = "-----";
    $dbuser   = '-----';
    $dbpass   = '-----';
    $dbname   = '-----';

    //connection to the database
    $dbhandle = mysql_connect($hostname, $dbuser, $dbpass) or die("Unable to connect to MySQL " . \mysql_error() . "
");

    //select db

    mysql_select_db($dbname, $dbhandle) or die("Unable to connect to DB: " . \mysql_error() . "
");
    $result = mysql_query("SELECT usr_id IF (username = '$username' AND password = '$password') FROM people") or die("Error: " . mysql_error());
    echo $result;
?>

I know Google is my friend, but when I've tried to find it out, the references just gave me non-relevant information, or at least, not relevant for this case.
So, anyway, thank for your time!

A: Try using WHERE instead of IF, so:
"SELECT usr_id FROM people WHERE username = '".$username."' AND password = '".$password."'"

A: use WHERE clause to filter such conditions,
SELECT usr_id
FROM people
WHERE username = '$username' AND password = '$password'

A: $result = mysql_query("SELECT usr_id FROM people WHERE username = '$username' AND password = '$password');
 $result_array=mysql_fetch_assoc($result);
echo $result_array['usr_id'];


text:
Q: locking down linux and recording all root actions I would like to do a few things.  I would like to have a sudoers file that gives access to all commands except for "sudo su -" and also "sudo rm {anything in var log}".  The second one is purely so someone can't delete what they have been doing.  This way I have history of all the commands the admins run as root.....with a timestamp would even be better if possible?
Then, we run our servers with a user called serveruser.  I would prefer that any commands someone wants to run as that user also has to do something like sudo every time and we log every command as the user that actually ran the command.  I do NOT want someone doing "sudo su - serveruser" and then running commands as I have no access to who ran the commands.
How does one go about locking down a server so I can see all this information and have traceability.  We just want the ability to see what was being done to a system when it goes bad such that we can possibly reverse the mistake and talk to the person that was doing the work as well.
thanks,
Dean

A: Short answer: YOU CAN NOT DO THAT (in any feasible way that is) using nothing by sudo
If you take away sudo su - functionality, then you have to specify what they can run individually. And what I heard through the grapevine, sudo is not bullet-proof. You can fool it and make it do things that administrators are trying to prevent you from doing.
What you need is an auditing system and it needs to log to a remote host, which is not accessible with the root privileges from your local server. Otherwise, you are giving the keys for the kingdom to the people you (obviously) don't trust and hoping for the best.
If this is a workplace requirement, I'd strongly suggest spending the money and getting PowerBroker from Beyond Trust (formerly known as Symark). It ain't cheap but it does what you need:dishing out granular privileges and logging them.

A: I found there are some decent things out there like rootsh and other ones as well that it might be possible to write a short script.  It is not 100% secure but I don't need that...if one of our admins wanted to destroy our system, they could anyways....we all just want the traceability so our admins might start running "fakesudo.sh user" which gets the job done for us.


text:
Q: BitmapImage and Image components does not display loaded bitmap? [Bindable]
protected var bmp : Bitmap = new Bitmap();
...

var loader : Loader = new Loader();
    loader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );
    loader.load( new URLRequest( fileObj.url ) );

function onComplete( event : Event ) : void
{
    trace( Bitmap( LoaderInfo( event.target ).content ).bitmapData.height );

    bmp = ( new Bitmap( Bitmap( LoaderInfo( event.target ).content ).bitmapData ) ) ;

}
...

<s:BitmapImage id="cameraSource" width="100%" height="100%" source="{ bmp }" scaleMode="stretch" />

I am using this source code to load a localy stored image file.
It is loaded fine, but due some reason is not displayed.

*

*Why the follow source code doesn't display the loaded image ?

// Flex 4.6 and Flex 4.8 tested, mobile AIR application

A: Best guess is that your binding isn't triggering an update, try assigning the property directly
cameraSource.source = bmp; //at the end of onComplete

Either this or the container for the BitmapImage is constraining it's size, you could also try setting a literal explicit pixel size temporarily instead of a percent.

A: Seems like It is my fault of not sufficient explaining the situation.
The whole thing is moved into a View, but once a browse for picture view is been pushed, it is destroying the data into current view.
The follow row of code is fixing everything
destructionPolicy="never"


text:
Q: SQL Inner Join: Weird Result I have data that looks like this:
Table_A:

Source     tableName     systemid
A           table_1       123abcA2
B           table_1       222DEFD3
C           table_1       369CCCB3

Table_B:

Source     tableName     systemid
Q          table_2       123abc
R          table_2       222DEF
C          table_2       369CCC

I ran the following query:
select a.Source, a.tableName, a.systemid as a_systemid, b.systemid as b_systemid
from table_a as a
inner join table_b as b on a.systemid = b.systemid

Here is what came back:
Source     tableName     a_systemid     b_systemid
A           table_1       123abcA2       123abc
B           table_1       222DEFD3       222def
C           table_1       369CCCB3       369CCC

Shouldn't I get nothing returned? As nothing matches.
Table A system id = nvarchar data type

Table b systemid = uniqueidentifier data type

A: Implicit casting is occuring and essentially truncating your string data which causes a match. You need to explicitly cast the uniqueidentifier to an nvarchar(max).
Please see this question and answer.
DECLARE @t1 TABLE([Source] CHAR(1),tableName VARCHAR(10),systemid nvarchar(max))
DECLARE @t2 TABLE([Source] CHAR(1),tableName VARCHAR(10),systemid uniqueidentifier)
INSERT INTO @t1 SELECT 'A','table_1','15b993cc-e8be-405d-bb9f-0c58b66dcdfe_1'
INSERT INTO @t1 SELECT 'B','table_1','4cffe724-3f68-4710-b785-30afde5d52f8_1'
INSERT INTO @t1 SELECT 'C','table_1','7ad22838-ddee-4043-8d1f-6656d2953545_1'
INSERT INTO @t2 SELECT 'Q','table_2','15b993cc-e8be-405d-bb9f-0c58b66dcdfe'
INSERT INTO @t2 SELECT 'R','table_2','4cffe724-3f68-4710-b785-30afde5d52f8'
INSERT INTO @t2 SELECT 'C','table_2','7ad22838-ddee-4043-8d1f-6656d2953545'

select a.Source, a.tableName, a.systemid as a_systemid, b.systemid as b_systemid
from @t1 as a
inner join @t2 as b on a.systemid = CONVERT(NVARCHAR(MAX),b.systemid)

As a practice, you should always explicitly cast mismatched datatypes for clarity as well as prevent weird "what is going on?!?!" stuff.


text:
Q: How to make an obstacle hit a wall not go through the wall/obstacle I need some help figuring out how i can make the ambulance go around the obstacle rather than going through it. This is what i have so far...
My plan is to make a racing game, the red box represents my car and I'm trying to figure out how to make it so it doesn't collide with the rectangles so they can't just cheat and cross over to the finish line, they have to go through the track. This is what i want to do
https://i.stack.imgur.com/apgBf.png
So far i just have the car and one of the rectangles but can't get it to not cross over the rectangle.
I'm trying to make it so the ambulance can't just go past that obstacle but has to go around it, i want to make a track, a racing game but stuck
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace FinalProject
{
    /// <summary>
    /// This is the main type for your game.
    /// </summary>
    public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        int count;
        int speed = 5;
        Texture2D background, carUp, carDown, carRight, carLeft, obstacle;
        Rectangle backgroundRec, carRec, carRecDown, carRecUp, carRecLeft, carRecRight, carRec1, obstacleRec;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
            carRec = new Rectangle(500, 300, 100, 100);
            carRecDown = new Rectangle(500, (300 + speed), 100, 100);
            carRecLeft = new Rectangle((500 - speed), 300, 100, 100);
            carRecUp = new Rectangle(500, (300 - speed), 100, 100);
            carRecRight = new Rectangle((500 + speed), 300, 100, 100);
            backgroundRec = new Rectangle(0, 0, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);
            obstacleRec = new Rectangle(100, 240, 100, 300);
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);

            carUp = Content.Load<Texture2D>("up");
            carDown = Content.Load<Texture2D>("down");
            carRight = Content.Load<Texture2D>("right");
            carLeft = Content.Load<Texture2D>("left");
            background = Content.Load<Texture2D>("background");
            obstacle = Content.Load<Texture2D>("obstacle");
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// game-specific content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            KeyboardState keys = Keyboard.GetState();
            GamePadState pad1 = GamePad.GetState(PlayerIndex.One);
            carRecDown.Y = carRec.Y - speed;
            carRecLeft.X = carRec.X - speed;
            carRecRight.X = carRec.X + speed;
            carRecUp.Y = carRec.X + speed;
            // Keyboard

            if (keys.IsKeyDown(Keys.Up) && !(obstacleRec.Intersects(carRecUp)))
            {
                count = 1;
                carRec.Y -= speed;
            }
            if (keys.IsKeyDown(Keys.Down) && !(obstacleRec.Intersects(carRecDown)))
            {
                count = 2;
                carRec.Y += speed;
            }
            if (keys.IsKeyDown(Keys.Right) && !(obstacleRec.Intersects(carRecRight)))
            {
                count = 3;
                carRec.X += speed;
            }
            if (keys.IsKeyDown(Keys.Left) && !(obstacleRec.Intersects(carRecLeft)))
            {
                count = 4;
                carRec.X -= speed;
            }

            /* if (obstacleRec.Intersects(carRec))
             {
                 carRec.X +=1 ;
             }*/

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            spriteBatch.Draw(background, backgroundRec, Color.White);
            spriteBatch.Draw(obstacle, obstacleRec, Color.White);
            if (count == 0)
                spriteBatch.Draw(carUp, carRec, Color.White);
            if (count == 1)
                spriteBatch.Draw(carUp, carRec, Color.White);
            if (count == 2)
                spriteBatch.Draw(carDown, carRec, Color.White);
            if (count == 3)
                spriteBatch.Draw(carRight, carRec, Color.White);
            if (count == 4)
                spriteBatch.Draw(carLeft, carRec, Color.White);
            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}

A: If you want to do path finding, You should create a graph representing your race track use BFS or Djikstra algorithm.
For the collisions, read about basic collision detection methods. If you want to do a very basic collision detection, just calculate the next location of the car twice, once for the movement on each axis, Then check if these created locations collide with the map. If so, just block the car from moving in this axis.
Here is a short pseudo code:
Vector2 movement = ...

Rectangle nextPosX = ....
Rectangle nextPosY = ....
if (IntersectingWithMap(nextPosX))
   movement.x = 0
if (IntersectingWithMap(nextPosY))
   movement.y = 0

currPos += movement;


text:
Q: Replace data labels in ggplot2 heatmap with actual column names in a shiny app Hello I have a simple shiny app which creates a heatmap. The problem is that after I melt the initial dataset into "gen3" I get label names like gen3[,1]: DADA but I want to take gene_symbol: DATA instead (I want the same with the other labels as well). Is this possible with ggplot2? I assume I should use paste() somehow or manually change the labels.
#data
gene_symbol<-c("DADA","SDAASD","SADDSD","SDADD")
ASDDA<-c("normal","over","low","over")
ASDDb<-c("normal","over","low","over")
ASDDAf<-c("normal","over","low","over")
Gene_states2<-data.frame(gene_symbol,ASDDA,ASDDb,ASDDAf)

#ui.r
library(shiny)
library(ggplot2)
library(plotly)
library(extrafont)
library(dplyr)

fluidPage(

  # App title ----
  titlePanel(div("GENES HEATMAP",style = "color:blue")),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(width = 3

    ),
    # Main panel for displaying outputs ----
    mainPanel(

      tabsetPanel(type = "tabs",
                  tabPanel("Heatmap",

                           fluidRow(
                             tags$style(type="text/css",
                                        ".shiny-output-error { visibility: hidden; }",
                                        ".shiny-output-error:before { visibility: hidden; }"

                             ),
                             plotlyOutput("sc")
                           )

                  ))
      )))
#server.r
function(input, output,session) {

rt<-reactive({
    req(input$file1)
csvdata <- read.csv(input$file1$datapath,
                    header = input$header

)

if(input$disp == "head"){
  head(csvdata)
} else{
  csvdata
}

row.has.na <- apply(csvdata, 1, function(x){any(is.na(x))})
csvdata2 <- csvdata[!row.has.na,]

csvdata2

})
  output$sc<-renderPlotly({
    library(ggplot2); library(reshape2)
    gen3 <- melt(rt(), id.var = colnames(rt())[1])
    p1<-ggplot(gen3, aes(gen3[,1],gen3[,2])) + geom_tile(aes(fill = gen3[,3]),
                                                         colour = "white") + scale_fill_manual(values=c("yellow", "red", "blue"))+
      labs(x = "gene_symbol",y="sample",fill="value")+
      theme(title = element_text(family = "Calibri",
                                 size = 10,
                                 face = "bold"),
            axis.title = element_text(family = "Calibri Light",
                                      size = 16,
                                      face = "bold",
                                      color = "black"),
            axis.text = element_text(family = "Calibri",
                                     size = 11),
            axis.title.y = element_text(margin = margin(t = 0, r = 25, b = 0, l = 25)),
            panel.background = element_rect(fill = NA),
            panel.grid.major = element_line(colour = "grey50"))
    ggplotly(p1)%>%
      layout( autosize = F, width = 1450, height = 600,hoverlabel = list(bgcolor = "white",
                                                                         font = list(family = "Calibri",
                                                                                size = 9,
                                                                                color = "black")))

  })

}

A: In ggplot there is no need to specify the data.frame name in aesthetics (aes) after you've already told it which data.frame to use.
Simply do this:
ggplot(gen3, aes(gene_symbol, variable)) + geom_tile(aes(fill= value) ... and so on.
If you don't want variable and value to show up in your hoverlabel, just change colnames of gen3 after you melt it to whatever you do want to show up.


text:
Q: Create a table with an autoinc field using FireDAC TFDTable Is there are way to use the TFDTable.CreateTable method in Delphi to automatically create the trigger and generator for an autoinc field?
Using this as an example
Create table with firedac without SQL Script
I have tried the following:
Table := TFDTable.Create(nil);
try
  Table.Connection := MyConnection;
  Table.TableName := 'Vehicles';
  Table.FieldDefs.Add('VehIdx', ftAutoInc, 0, True);
  Table.FieldDefs.Add('PIN', ftString, 15, False);
  Table.FieldDefs.Add('VehID', ftString, 15, False);
  Table.FieldDefs.Add('VehName', ftString, 50, False);
  Table.AddIndex('pkVehiclesIdx', 'VehIdx', '', [soPrimary]);
  Table.CreateTable(True);
finally
  Table.Free;
end;

But I get "Generator GEN_VEHICLES not found".
I'm using Firebird.
I know that I can create the trigger and generator myself. But it seems that FireDAC should be able to do it. I'm wondering how to make it do that?
OK, I have found out how to do it. Here's the complete code:
  procedure CreateVehiclesTable;
  var
    Table: TFDTable;
  begin
    Table := TFDTable.Create(nil);
    try
      Table.Connection := FrmMain.ConLocal;
      Table.TableName := 'Vehicles';
      Table.FieldDefs.Add('VehIdx', ftAutoInc, 0, False);
      Table.FieldDefs.Add('PIN', ftString, 15, False);
      Table.FieldDefs.Add('VehID', ftString, 15, False);
      Table.FieldDefs.Add('VehName', ftString, 50, False);
      Table.OptionsIntf.UpdateOptions.GeneratorName := 'GEN_VEHICLES';
      Table.AddIndex('pkVehiclesIdx', 'VehIdx', '', [soPrimary]);
      Table.CreateTable(False, [tpTable, tpPrimaryKey, tpGenerators, tpTriggers]);
    finally
      Table.Free;
    end;

Manually setting the generator name makes everything work correctly. The trigger and generator are created and the VEHIDX field increments automatically as it should.


text:
Q: Factoring ln functions can anyone tell me how the following factoring ends in $\ln x - \frac{ln 2}{2}$
Original
$\frac{\ln x}{\ln 2} - \frac{\ln  2}{ln 2}$
Work shown from Professor
$\frac{1}{ln 2} (\ln x - \frac{ln 2}{2})$

A: It's not. Clearly, the original evaluated at $x=0$ is $-1$ while your professor's factored form evaluated at $x=0$ is $-\frac{1}{2}$


text:
Q: How to get CPU serial number on Windows using Python? I wrote a program in Python-3.6.2 on Windows 10. I want get the CPU serial number.
Here is my code:
def getserial():
    # Extract serial from cpuinfo file
    cpuserial = "0000000000000000"
    try:
        f = open('/proc/cpuinfo','r')
        for line in f:
            if line[0:6]=='Serial':
                cpuserial = line[10:26]
        f.close()
    except:
        cpuserial = "ERROR000000000"
  return cpuserial

print(getserial())

When I run the program, it prints: ERROR000000000.
How do I fix it?

A: Your code doesn't let any exception raised. So, you don't see the error: There is no '/proc/cpuinfo' file on Windows.
I have rewrite your code  like that:
def getserial():
    # Extract serial from cpuinfo file
    with open('/proc/cpuinfo','r') as f:
        for line in f:
            if line[0:6] == 'Serial':
                return line[10:26]
        return "0000000000000000"

First, I have a with statement to use the file context manager: whenever an exception is raised or not, your file will be closed.
And I simplify the loop: if it found a "Serial" entry, it returns the value.
EDIT
If you have python with a version >= 2.6 you can simply use
import multiprocessing

multiprocessing.cpu_count()

http://docs.python.org/library/multiprocessing.html#multiprocessing.cpu_count
EDIT2
The best solution I found to get the "cpuinfo" is with the py-cpuinfo library.
import cpuinfo
info = cpuinfo.get_cpu_info()
print(info)

But, I think that "Serial" entry is not standard. I can't see it on classic systems.


text:
Q: How to accurately measure HTML5 Browser Framerates (FPS)? What is the most accurate way to measure framerates, i.e. FPS, in modern HTML5 browsers?  I'm specifically interested in FPS for Canvas animations.
http://weblogs.mozillazine.org/roc/archives/2010/11/measuring_fps.html will tell you that trying to measure framerate by counting how often your setTimeout runs is not accurate.  The browser can run your Timeout callback multiple times between screen paints.
Turns out Mozilla has a window.mozPaintCount https://developer.mozilla.org/en/DOM/window.mozPaintCount available, which should provide an accurate FPS.  However, this only works for Mozilla.
There's an open issue for Chrome for something similar: http://code.google.com/p/chromium/issues/detail?id=65348
A manual way to check for hardware accelerated FPS in Chrome is to grab the Chrome Beta channel (as of posting date) and go to about:flags and turn on FPS Counter.  However, on a Mac, acceleration only turns on when using WebGL.  So, no way to check FPS for Canvas on Chrome for Mac.
What are other strategies for accurately measuring HTML5 FPS?
Thanks!

A: Please check:

*

*https://github.com/mrdoob/stats.js - it's the best FPS monitor I know. It also gives you some stats about mem/cpu usage (you have to run your browser with special parameter to expose that data), but may also suffer from the inaccuracy you described.

*https://github.com/pcwalton/firefox-framerate-monitor
Also, in new chrome builds (probably canary stream) there should be an option for displaying FPS in about:flags.


text:
Q: Trying to make a route in Angular on dropdown item, not working? I have a route /gallery and in routing module it has 2 children
    path: "gallery",
    component: GalleryComponent,
    children: [
      {
        path: "photoAlbums",
        component: AlbumsComponent,
        children: [{ path: "photos", component: PhotosComponent }],
      },
      {
        path: "videoAlbums",
        component: VideoAlbumComponent,
        children: [{ path: "videos", component: VideosComponent }],
      },
    ],
  },

Now I am trying to connect the routes on dropdown. Once u hover over gallery u can click on it to go to /galery or click on 1 of dropdown and go on them /photoAlbums or /videoAlbums.
This is what I have in my app.component.html:
      Gallery

        Photos
        Videos

Gallery works but photos and videos don't, in console I get this error:
ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'videoAlbums'
Error: Cannot match any routes. URL Segment: 'videoAlbums' ...

A: It should be,
routerLink: "gallery/photoAlbums" & routerLink="gallery/videoAlbums"

But in this case, it will render gallery component too.
Because the route  path: "photoAlbums" can be accessed through gallery route only as gallery is the parent of path: "photoAlbums".
It means you can't access phtoAlbums directly until you access gallery component(because child is accessible if parent is loaded).
Same is applicable to path="/videoAlbums".
So by default, first you have to load gallery path or component.

What can you do ?

*

*If these paths don't have parent/child scenario, you can change the routing as follow,
 {
     path: "gallery",
     component: GalleryComponent
 },
 {
     path: "photoAlbums",
     component: AlbumsComponent,
     children: [{ path: "photos", component: PhotosComponent }],
 },
 {
     path: "videoAlbums",
     component: VideoAlbumComponent,
     children: [{ path: "videos", component: VideosComponent }],
 },

all routes are at same level. now routerLink="/photoAlbums" && routerLink="/videoAlbums" will work.

*otherwise, you will have to write below piece of code in gallery.component.html

     Photos
     Videos

after putting it inside gallery's html, routerLink="/photoAlbums" && routerLink="/videoAlbums" will work.

A:
routerLink="/photoAlbums"

you need to link the full path -
 routerLink="/gallery/photoAlbums"


text:
Q: Why is it true that $\frac{\partial x}{\partial y}=-\frac{F'_y}{F'_x}$? Specifically why is it negative? The math below was written in a thread I needed help in.

Define $$F(x,y,z)=x^2y+xz^2-5.$$
Hence
$$\frac{\partial x}{\partial y}=-\frac{F'_y}{F'_x}=-\frac{x^2}{2xy+z^2}\,,$$$$\frac{\partial x}{\partial z}=-\frac{F'_z}{F'_x}=-\frac{2xz}{2xy+z^2}\,.$$

It seems more intuitive to me that $\frac{\partial x}{\partial y} = \frac{\frac{\partial F}{\partial y}}{\frac{\partial F}{\partial x}} = \frac{F'_y}{F'_x}$
I don't see where the negative sign comes from!


text:
Q: php forum outputs string of text, how to find source of said string? I'm working on a site which is a simple php forum, and every so often it'll insert an alert/error div on the page, e.g., "Error! You can't do that because of this," or whatever.
How do I search each of the files on my server for the string "Error! You can't do that because of this"? Asked differently, how do I find the source of the various errors when they arise, you know, without having to manually look at every single .php file on the server; thanks.

A: If you have access to the command console, use GREP.
To search for "Error! You can't do that because of this" in all PHP files in a directory,
$ grep "Error! You can't do that because of this" ~/*.php

To search all subdirectories recursively,
$ grep -R "Error! You can't do that because of this" /


text:
Q: Multiple font-weights, one @font-face query I have to import the Klavika font and I've received it in multiple shapes and sizes:
Klavika-Bold-Italic.otf
Klavika-Bold.otf
Klavika-Light-Italic.otf
Klavika-Light.otf
Klavika-Medium-Italic.otf
Klavika-Medium.otf
Klavika-Regular-Italic.otf
Klavika-Regular.otf

Now I would like to know if it's possible to import those into CSS with just one @font-face-query, where I'm defining the weight in the query. I want to avoid copy/pasting the query 8 times.
So something like:
@font-face {
  font-family: 'Klavika';
  src: url(../fonts/Klavika-Regular.otf), weight:normal;
  src: url(../fonts/Klavika-Bold.otf), weight:bold;
}

A: Update 2022: use variable fonts
Provided your font is available as a variable font you can actually combine multiple font-weights in a single @font-face rule like so:
@font-face {
  font-family: 'Roboto Flex';
  font-style: normal;
  font-weight: 100 1000;
  font-stretch: 0% 200%;
  src: url(https://fonts.gstatic.com/s/robotoflex/v9/NaNeepOXO_NexZs0b5QrzlOHb8wCikXpYqmZsWI-__OGfttPZktqc2VdZ80KvCLZaPcSBZtOx2MifRuWR28sPJtUMbsFEK6cRrleUx9Xgbm3WLHa_F4Ep4Fm0PN19Ik5Dntczx0wZGzhPlL1YNMYKbv9_1IQXOw7AiUJVXpRJ6cXW4O8TNGoXjC79QRyaLshNDUf9-EmFw.woff2) format('woff2');
}

We need to specify a font-weight range by adding 2 values:
font-weight: 100 1000;

slider_weight.addEventListener("input", function () {
  var axisValue = slider_weight.value;
  testarea.style.fontWeight = axisValue;
  value_weight.innerText = axisValue;
});

slider_width.addEventListener("input", function () {
  var axisValue2 = slider_width.value;
  testarea.style.fontStretch = axisValue2+'%';
  value_width.innerText = axisValue2;
});
body{
  font-family: 'Roboto Flex';
  font-size:5vw
}

@font-face {
  font-family: 'Roboto Flex';
  font-style: normal;
  font-weight: 100 1000;
  font-stretch: 0% 200%;
  src: url(https://fonts.gstatic.com/s/robotoflex/v9/NaNeepOXO_NexZs0b5QrzlOHb8wCikXpYqmZsWI-__OGfttPZktqc2VdZ80KvCLZaPcSBZtOx2MifRuWR28sPJtUMbsFEK6cRrleUx9Xgbm3WLHa_F4Ep4Fm0PN19Ik5Dntczx0wZGzhPlL1YNMYKbv9_1IQXOw7AiUJVXpRJ6cXW4O8TNGoXjC79QRyaLshNDUf9-EmFw.woff2) format('woff2');
}

#testarea {
  font-size: 2em;
  transition:0.5s;
  font-weight:100;
  font-stretch: 0%;
}

.regular{
font-weight:400
}

.bold{
font-weight:900
}

.condensed{
font-stretch:0%;
}

Roboto Flex bold

Roboto Flex regular condensed

  Weight
  <input type="range" id="slider_weight" name="slider" value="100" min="100" max="1000" step="10">
  100

  Width
  <input type="range" id="slider_width" name="slider" value="0" min="0" max="200" step="1">
  0

Type something ...

Retrieving google variable fonts ... tricky
I highly recommend this post, since the current google fonts UI isn't particularly helpful:
How To Get The Variable Font Links From Google Fonts?
Keep in mind the @font-face won't automatically apply font weights to emphasized elements like  or

 etc.
So make sure, you specify the desired font weights for a predictable rendering like so:
/* Variable fonts: we can apply intermediate weight values - yay! */
strong{
   font-weight: 623
}

Don't rely on keyword-based weights or styles (e.g semi-bold, medium, semi-condensed etc.)
For instance: what is the difference between "medium" and "semibold"?
... It depends on the font design, your font's weight range and actually on your design decision.
Some fonts are by default rather "bold" others rather "thin" or "light" (related post: Some Google font doesn't have Semibold font type)
/* Roboto 400 is too bold for me – map default/regular weight 400 to 300 */
body{
  font-family: "Roboto Flex";
  font-weight: 300;
}

/* Roboto 700 is not bold enough for me – map default/bold weight 700 to 1000*/
strong{
  font-weight: 1000
}

/* ... OK a medium weight might be handy – lets say 625  */
.medium{
  font-weight: 625
}

/* condensed or expanded styles: font-stretch < 100 = condensed;
font-stretch > 100 = expanded; */
.condensed{
  font-stretch:0%;
}
.semi-condensed{
  font-stretch:50%;
}

.semi-expanded{
  font-stretch:200%;
}

.expanded{
  font-stretch:200%;
}

A: Actually there is a special flavor of @font-face that will permit just what you're asking.
Here's an example using the same font-family name with different styles and weights associated with different fonts:
@font-face {
  font-family: "DroidSerif";
  src: url("DroidSerif-Regular-webfont.ttf") format("truetype");
  font-weight: normal;
  font-style: normal;
}

@font-face {
  font-family: "DroidSerif";
  src: url("DroidSerif-Italic-webfont.ttf") format("truetype");
  font-weight: normal;
  font-style: italic;
}

@font-face {
  font-family: "DroidSerif";
  src: url("DroidSerif-Bold-webfont.ttf") format("truetype");
  font-weight: bold;
  font-style: normal;
}

@font-face {
  font-family: "DroidSerif";
  src: url("DroidSerif-BoldItalic-webfont.ttf") format("truetype");
  font-weight: bold;
  font-style: italic;
}

You can now specify font-weight:bold or font-style:italic to any element you like without having to specify the font-family or overriding font-weight and font-style.
body { font-family:"DroidSerif", Georgia, serif; }

h1 { font-weight:bold; }

em { font-style:italic; }

strong em {
  font-weight:bold;
  font-style:italic;
}

For a full overview of this feature and the standard use take a look at this article.

EXAMPLE PEN

A: If like me you need to load Roboto fonts without hitting Google's servers it should look like:
/* Thin */
@font-face {
    font-family: 'Roboto';
    src: url(../fonts/Roboto-Thin.ttf) format('truetype');
    font-style: normal;
    font-weight: 100;
}

/* Light */
@font-face {
    font-family: 'Roboto';
    src: url(../fonts/Roboto-Light.ttf) format('truetype');
    font-style: normal;
    font-weight: 300;
}

/* Normal */
@font-face {
    font-family: 'Roboto';
    src: url(../fonts/Roboto-Regular.ttf) format('truetype');
    font-style: normal;
    font-weight: 400;
}

/* Medium */
@font-face {
    font-family: 'Roboto';
    src: url(../fonts/Roboto-Medium.ttf) format('truetype');
    font-style: normal;
    font-weight: 500;
}

/* Bold */
@font-face {
    font-family: 'Roboto';
    src: url(../fonts/Roboto-Bold.ttf) format('truetype');
    font-style: normal;
    font-weight: 700;
}

/* Black */
@font-face {
    font-family: 'Roboto';
    src: url(../fonts/Roboto-Black.ttf) format('truetype');
    font-style: normal;
    font-weight: 900;
}

Then do the same for the italic variants if needed.
See font-weight documentation for clues on mapping names to numerical weight. Here is Roboto font downlond link.

A: @font-face {
  font-family: 'Klavika';
  src: url(../fonts/Klavika-Regular.otf) format('truetype') font-weight-normal,
       url(../fonts/Klavika-Bold.otf) format('truetype') font-weight-bold,
       url(../fonts/Klavika-Bold-Italic.otf) format('truetype') font-italic font-weight-bold;
}

A: Use Tranfonter, saved me a ton of time: https://transfonter.org/


text:
Q: How to add a button in Jupyter Lab Launcher for a Voilà notebook? I'm using Jupyter Lab with Voilà to render a user interface.
When opening my dashboard, here is what I need to do.

The problem is that I'd like to have a button in the Jupyter Lab Launcher to open the dashboard directly.

*

*Is it possible to add a button in the Launcher?

*How to cable it with Voilà?

Thanks for your help!


text:
Q: Search words similarity in PostgreSQL? Lets say in PostgreSQL database I have table called questions. As you can see in that table I have records which similar for human but not similar for database. Is it possible to take all records similar to 90 percent of the list of questions?
| QUESTION_ID | QUESTION_TEXT                                    |
|-------------|--------------------------------------------------|
| 1           | What is your favorite movie, cartoon and series? |
| 2           | What is your favorite movie cartoon and series   |
| 3           | what is your favorite Movie, Cartoon and Series  |
| 4           | Do you like apple?                               |
| 5           | do you like Apple                                |

Right now I use next code which return only 2 record:
select
    *
from
    questions
where
    question_text in (
        'What is your favorite movie, cartoon and series?',
        'Do you like apple?'
    )

As I know PostgreSQL has pg_trgm module which help search similarity by word_similarity function. How to add this function to my request correctly?

A: You'd do it like this:
CREATE EXTENSION pg_trgm;
CREATE INDEX ON questions USING gin (question_text gin_trgm_ops).

Then you can efficiently search like this:
SELECT question_id
FROM questions
WHERE question_text % 'What is your favorite movie, cartoon and series?';

% is the "similarity operator", and the threshold when things are considered similar can be set with the parameter pg_trgm.similarity_threshold.
See the documentation for more.


text:
Q: Facebook Auth Error it will be great if someone can help me with this and I have researched for countless hours on stack overflow already
This is my login page
When I click on the facebook button, it takes me to /auth/facebook
Then after that, I get redirected to a
ECONNRESET: Request could not be proxied!
There was an error proxying the request error.
In the terminal, it says:
enter image description here

How do I fix this? PS.
Going off this tutorial
https://scotch.io/tutorials/easy-node-authentication-facebook
Also Im using node.js, MongoDB, express.js, and facebook
Much thanks and have an amazing day

A: From the error that I'm seeing when trying to authenticate your app via Facebook, it seems as if your domain URL has not been properly added to Facebook's Developer API.
Are the proper URL's entered for your Facebook App Domains (in Basic Settings) and Valid OAuth redirect URIs (in Facebook Login Settings)?
Also, regarding that Node error that you're receiving, what is on line 60 of your Passport.js file?


text:
Q: css preceded element and :focus I have to change background color after click on input and preceded
 element. It's not difficult with only input, but
 it is.
Code

    input[type="text"]:focus ~ .prefix{
       background-color:#e4ff00 !important;
    }

    input[type="text"]:focus + .prefix{
       background-color:#e4ff00 !important;
    }

NIP

       <input type="text" value="" name="nip">

But doesn't work

A: If you use p in donwards it will work

   <input type="text" value="" name="nip">

NIP

A: First, what you're asking is technically impossible: it is not possible – with the current selectors module – to select a previous element. Both the adjacent-sibling and general-sibling combinators (+ and ~ respectively) can only select elements that follow the current element.
Similarly, there is no parent-selector.
That said, though, this is possible if you can rearrange your HTML to place the
 element after the <input> element:

  input[type="text"]:focus + .prefix {
    background-color: #e4ff00;
  }

  <input type="text" value="" name="nip">

NIP

If, however, you need the
 element to precede the <input> that is also possible, albeit it's effectively a visual trick using CSS flex-boxes to reorder the visual flow of the page while the
 element remains a later-sibling of the <input> in the HTML:

.inputholder {
    display: flex;
    flex-direction: column;
    flex-wrap: nowrap;
    justify-content: flex-start;
    align-content: stretch;
    align-items: flex-start;
}

div.inputholder p.prefix {
  order: 1;
  flex: 0 1 auto;
  width: 100%;
  align-self: auto;
}

div.inputholder input {
  order: 2;
  flex: 0 1 auto;
  align-self: auto;
}

input:focus + p {
  background-color: #e4ff00;;
}

  <input type="text" value="" name="nip">

NIP

References:

*

*Adjacent-sibling (+) combinator.

*General-sibling (~) combinator.

*"Using CSS flexible boxes," (MDN).


text:
Q: How to add a column for percentage using stored procedure I am trying to add a column for percentage using a stored procedure. I got the column for total marks of a student but percentage is not being calculated. I have different subject marks in a table called tbl_Marks and then I wrote a stored procedure for adding a total column.
Here is my code for the stored procedure :
ALTER PROCEDURE [dbo].[Sp_TotalMarks]
AS
BEGIN
   DECLARE @t int
   DECLARE @p int

   SET @t = 300
   SET @p = 100

   SELECT
      Student_Id, Stu_Name, Maths, English, Hindi,
      (Maths + English + Hindi) AS 'Total',
      ((Maths + English + Hindi )/@t)* @p AS 'Percentage'
   FROM
      tbl_Marks
END

A: Try this:
ALTER PROCEDURE [dbo].[Sp_TotalMarks]

AS
BEGIN
DECLARE @t numeric(8,2)
DECLARE @p int

SET @t = 300
SET @p = 100
SELECT
Student_Id,
Stu_Name,
Maths,
English,
Hindi,
(Maths + English + Hindi) AS 'Total',
CAST(CAST((Maths + English + Hindi) AS NUMERIC(8,2)) / @t * 100 AS NUMERIC(8,2)) AS 'Percentage'

FROM tbl_Marks
END

If you want to persist percentage result, then add new column in table, which will be calculated, add a formula an check to persist result for better performance.


text:
Q: ADF: copy distinct values into lookup table, add FK column to dataset Tough to come up with a reasonable title for this one!
I am copying data from a source table (let's call it Books) that has an enum column (Category):
ID   Title      Category
----------------------------
1    Test1      Education
2    Blah       Leisure
3    Brown fox  Leisure
...

So in this example, there are two enum members, Education and Leisure.
The sink is SQL, and I'm getting the distinct set of enum values and putting them in a lookup table (Categories in this example). The Books table in the sink should have a foreign key column called CategoryId that refers to the PK in the Categories lookup table.
So I need to figure out how to use the text from the Category column to get the ID from the lookup table and use it as the value in the Books.CategoryId column. Anyone know how to do that? I'm just getting my feet wet with ADF so I'll really appreciate any assistance.
Thanks!

A: Add a data flow to your pipeline and that will allow you to build a pattern to dedupe and value lookups. If you need some guidance on building data flows, use our YouTube channel of helper videos: https://aka.ms/dataflowvids


text:
Q: $f:D \rightarrow \mathbb C$ holomorphic, $D$ a convex set, $Re(f'(z))>0$. Prove that $f$ is injective $f:D \rightarrow \mathbb C$ holomorphic, $D$ a convex set, $Re(f'(z))>0$. Prove that $f$ is injective.
What I tried: Assume that $f$ is not injective. So there are $a,b \in D$ so that $f(a)=f(b)$.
So we get that:
$\int_a^bf'(z)dz=f(a)-f(b)=0 $
How do I use the fact that $Re(f'(z))>0$? Or that's not the direction at all?
Thank you.

A: Almost done! The idea is there.. You need to fill in the details though;
Let $a, b$ such that $f(a) = f(b)$.
Let $\gamma(t) =  a(1-t) + tb$ ($\gamma$ is the straight line going from $a$ to $b$)
Since our set $D$ is convex, we know that $\gamma(t)$ lies in $D$.
Take $F(t) = f(\gamma(t))$. Then $F'(t) = f'(\gamma(t))(b-a)$
Now consider $\int_0^1 F'(t) \ dt = f(\gamma(1)) - f(\gamma(0)) = f(b) - f(a) = 0$
But $\int_0^1 F'(t) = \int_0^1 \Re(F'(t)) + i \int_0^1 \Im(F'(t)) = 0$ that would imply $\int_0^1 \Re(F'(t)) = 0$ but that is impossible as $\Re (F'(t)) > 0$ by hypothesis


text:
Q: Why is zero conductivity media called lossless? Doesn't zero conductivity mean infinite resistance which would lead to infinite loss.

A: It depends on the specific context. If we were talking about driving an electric current through metal, then the losses would be the energy dissipated by this electric current. This I think is the premise behind the question. However, if we talk about interaction with light, then a conducting media will incur losses, while a media with zero conductivity - i.e. an insulator, will allow lossless propagation of the light.

A: One can show that the attenuation of an E&M wave as it propagates in a material depends basically on the ratio $\sigma/\epsilon \omega$.
The attenuation factor, usually denoted by $\alpha$, has a somewhat complicated expression but, in the case for instance of a low-loss dielectric, $\alpha\approx \frac{\sigma}{2}\sqrt{\frac{\mu}{\epsilon}}$.  Thus, when $\sigma\to 0$, the attenuation factor $\alpha\to 0$ and the wave does not loose any of its energy in inducing currents (i.e. moving electrons) in the material: since $\sigma=0$, the resistivity $\rho$ is infinite and so it would take an infinite amount of energy to move electrons in that material.


text:
Q: Как исправить ошибку pytorch? Здраствуйте.
Делаю кликер для игры на нейронной сети yolo.
Обучил нейронку и не могу ее использовать в программе.
Вот код:
import torch

model = torch.hub.load('ultralytics/yolov5', 'custom', path='./model/best-m.pt', force_reload=True)

Выбивает ошибку:
Exception: 'Detect' object has no attribute 'grid'. Cache may be out of date, try force_reload=True or see https://github.com/ultralytics/yolov5/issues/36 for help.

A: а если так использовать:
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
(в кэш загружается предобученная модель)


text:
Q: Magento Custom Backend functionality ok i need some help with magento.  I have been using it for about 6 months now mainly using the built in functionality and have looked briefly at some of the more advanced features.  I am looking now at building in some custom features to the backend but dont know exactly where to start.
Basically, all of the documentation seems to be aimed at linking the front end etc but i want to write some custom scripts that will be interface with magentos backend upon certain events i.e. orders being placed etc.  I dont need any interface with the front end and these scripts are to run silently in the background but still integrate and use the magento database.
Where do i start? Help, please.

A: My 2 cents : everything start with a utility called "Module Creator" that Google will help you find.
This is a ready-to-use skeleton for building module with Magento that can help you understand the MVC model of Magento.
Take a closer look at the "Adminhtml" part of the basic module you will create with Module Creator.
Then, if you want to add functionnality to the system area of your backend and use those "system variables", please take a look at the etc/system.xml files of existing module.
Have fun

A: No need to create a full module for that. From the description it seems that event observers are really what you need. This wiki article should be enough to get you started. Come back when you get stuck with this tutorial and I am sure someone will be able to help.


text:
Q: Saving uploaded file to Pinata IPFS in NodeJS I've been trying to save uploaded image files to IPFS in NodeJs , while it seems Pinata saves them, the files are pretty much gibberish (after downloading the images are broken).
My code :
// Nodejs route.
exports.postImage = async (req, res, next) => {
    // Using multer to get the file.
    fileUploadMiddleware(req, res, async (err) => {
        // getting bunch of data from query string.
        let meta = {
            origin,
            originid,
            context,
            ownerid,
            format
        } = req.query;

        if(!meta.format || !req.files) {
            return next(new ErrorResponse("File format not specified", 404));
        }

        if(!meta.originid) {
            meta.originid = uuidv4();
        }

        // NOTE: is this the right way to get the data of the file ?
        const buffer = req.files[0].buffer;

 const filename = `${metadata.origin}_${metadata.originid}.${ metadata.format }`;

    let stream;
    try {
        stream = Readable.from(buffer);
        // HACK to make PINATA WORK.
        stream.path = filename;
    }
    catch(e) {
        logger.logError(e);
        return false;
    }

    const options = {
        pinataMetadata: {
            name: filename,
            keyvalues: {
                context: metadata.context,
                ownerid: metadata.ownerid
            }
        },
        pinataOptions: {
            cidVersion: 0
        }
    };

    try {
        var result = await pinata.pinFileToIPFS(stream, options);
        console.log("SUCCESS ", result);

        return result;
    }
    catch(e) {
        logger.logError(e);
        return null;
    }

        res.status(200).json({
            success: true,
            data: 'You got access'
        })
    });
}

So basically creating the stream based on the uploaded file buffer and sending it away to Pinata. Where do I go wrong?

A: const buffer = req.files[0].buffer;

If you used MemoryStorage. buffer property would be available. It is not available for diskStorage because it will save the file locally.:
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })

Also I think it not req.files[0]
const buffer = req.file.buffer;

after I get the buffer, I convert it to FormData using form-data npm package:
   import FormData from "form-data";

   const formData = new FormData();
      formData.append("file", buffer, {
         contentType,
        filename: fileName + "-" + uuidv4(),
      });

then you send a post request to pinata
  const url = `https://api.pinata.cloud/pinning/pinFileToIPFS`;
  const fileRes = await axios.post(url, formData, {
    maxBodyLength: Infinity,
    headers: {
      // formData.getBoundary() is specific to npm package. native javascript FormData does not have this method
      "Content-Type": `multipart/form-data: boundary=${formData.getBoundary()}`,
      pinata_api_key: pinataApiKey,
      pinata_secret_api_key: pinataSecretApiKey,
    },
  });


text:
Q: NoSuchElementException arises when asking user for input repeatedly in loop I am beginning to learn Java and am writing a Game of Pig for my introductory CS class. Knowing the details of this game is not necessary to respond to this question.
One of my methods has a loop that repeatedly prompts a user if they type a certain string. This string is "yes/n". For some reason, however, I can't get the loop to run past a single iteration. Sometimes, the program will proceed as a result, or the program will crash and throw a NoSuchElementException.
turnInfo[0] and turnInfo[1] are other variables within this method and represent the values of the rolls. The rolls can be seen in the image showing output (below).
Any and all help would sincerely be appreciated!
Here is the relevant piece of code:
        Scanner sc = new Scanner(System.in);
        System.out.print("Roll again? Type 'yes' or 'no' and hit <enter>: ");
        **String nextRoll = sc.next(); //THIS IS THE PROBLEM LINE: 72**

        while ((nextRoll.equals("yes/n")) && (turnInfo[0] != 6) && (turnInfo[1] != 6)); {
            turnInfo = diceInfo();
            System.out.println("Player rolled " + turnInfo[0] + " and " + turnInfo[1] + ".");
            int rollScore = rollScore(turnInfo[0], turnInfo[1]);
            turnScore = turnScoreAccumulator(rollScore, turnScore);

            //We create an exit out of the loop with the following conditionals.
            //If at least one of the dice is six, then the turn score is set to zero.
            if ((turnInfo[0] == 6) || (turnInfo[1] == 6)) {
                turnScore = 0;
            //If both dice turn out to be six, this situation is addressed in the main method.
            }
            else {
                potentialGameScore = potentialGameScore + rollScore;
                System.out.println("Player's turn sum is: " + turnScore + " and game sum would be: " + potentialGameScore + ".");
                System.out.print("Roll again? Type 'yes' or 'no' and hit <enter>: ");
                nextRoll = sc.next();
            }
        }

Here is the other set of code where the issue arises:
    public static void main(String[] args) {
        System.out.println("Hello, and welcome to the Game of Pig!\n\n");
        int[] humanTurnInfo;
        int [] computerTurnInfo;
        int humanGameScore = 0;
        int computerGameScore = 0;
        boolean gameVictory = false;
        int roundCounter = 0;

        while (gameVictory == false) {
            System.out.println("Player sum: " + humanGameScore + ", " + "Computer sum: " + computerGameScore + ".");
            roundCounter += 1;
            System.out.println("We now begin round " + roundCounter + ":");
            **humanTurnInfo = userInteraction(humanGameScore); //THIS IS ALSO A PROBLEM LINE: 185**
            humanGameScore = humanTurnInfo[2];
            if ((humanTurnInfo[0] == 6) && (humanTurnInfo[1] == 6)) {
                humanGameScore = 0;
            }

            if (humanGameScore >= 100) {
                System.out.println("Congratulations, you have won the game!");
                gameVictory = true;
            }
            else {
                computerTurnInfo = computerPlay(computerGameScore);
                if (computerTurnInfo[0] == 6 && computerTurnInfo[1] == 6) {
                    computerGameScore = 0;
                }
                if (computerGameScore >= 100) {
                    System.out.println("The computer has won the game. Better luck next time!");
                    gameVictory = true;
                }
            }

        }


text:
Q: Mock rest data with mockito and generate api doc I want to create JUnit test for Rest api and generate api doc. I want to test this code:
Rest controller
@RestController
@RequestMapping("/transactions")
public class PaymentTransactionsController {

@Autowired
private PaymentTransactionRepository transactionRepository;

@GetMapping("{id}")
    public ResponseEntity<?> get(@PathVariable String id) {
        return transactionRepository
                .findById(Integer.parseInt(id))
                .map(mapper::toDTO)
                .map(ResponseEntity::ok)
                .orElseGet(() -> notFound().build());
    }
}

Repository interface
public interface PaymentTransactionRepository extends CrudRepository<PaymentTransactions, Integer>, JpaSpecificationExecutor<PaymentTransactions> {

    Optional<PaymentTransactions> findById(Integer id);
}

Repository Impl:
@Service
@Qualifier("paymentTransactionService")
@Transactional
public class PaymentTransactionRepositoryImpl implements PaymentTransactionRepository {

@Override
    public Optional<PaymentTransactions> findById(Integer id) {
        String hql = "select e from " + PaymentTransactions.class.getName() + " e where e.id = :id";
        TypedQuery<PaymentTransactions> query = entityManager.createQuery(hql, PaymentTransactions.class).setParameter("id", id);
        List<PaymentTransactions> paymentTransactions = query.getResultList();
        return paymentTransactions.isEmpty() ? Optional.empty() : Optional.of(paymentTransactions.get(0));
    }
}

I tried to implement this JUnit5 test with mockito:
@ExtendWith({ RestDocumentationExtension.class, SpringExtension.class })
@SpringBootTest(classes = PaymentTransactionsController.class)
@WebAppConfiguration
public class PaymentTransactionRepositoryIntegrationTest {

    public final ManualRestDocumentation restDocumentation = new ManualRestDocumentation();

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    PaymentTransactionRepository target;

    @Autowired
    private ObjectMapper objectMapper;

    private MockMvc mockMvc;

    @MockBean
    private PaymentTransactionRepository transactionRepository;

    @BeforeEach
    void setUp() {

        Optional<PaymentTransactions> optional = Optional.of(new PaymentTransactions());

        when(transactionRepository.findById(Integer.parseInt("1"))).thenReturn(optional);

        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();

        PaymentTransactionRepository tnx = Mockito.mock(PaymentTransactionRepository.class);
        ReflectionTestUtils.setField(PaymentTransactionsController.class, "PaymentTransactionRepository", tnx);

      this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
              .apply(documentationConfiguration(restDocumentation)).build();
    }

    @Test
    public void testNotNull() {
        assertNotNull(target);
    }

    @Test
    public void testFindByIdFound() {
        Optional<PaymentTransactions> res = target.findById((int) 1);
        assertTrue(res.isPresent());
    }

    @Test
    public void uniqueTransactionIdLenght() {
        try {
            this.mockMvc.perform(RestDocumentationRequestBuilders.get("/transactions/1")).andExpect(status().isOk())
                    .andExpect(content().contentType("application/xml;charset=UTF-8"))
                    .andDo(document("persons/get-by-id"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I get error for when:
The method when(Optional<PaymentTransactions>) is undefined for the type PaymentTransactionRepositoryIntegrationTest

Do you know what is the proper way to implement mock test?


text:
Q: Show filter result size in footer of p:dataTable I am using a datatable of PrimeFaces with a global filter.
When I enter a filter, I want to refresh the number of rows in the filtered list displayed, but it does not work: update is triggered before filter()
Thanks for your help.
Here is my code:
<p:dataTable widgetVar="widgetColPlanCompteM61"
     filteredValue="#{planCompteM61ManagerBean.listeFiltre}" ...

<f:facet name="header">
    <h:outputLabel value="Plan de compte M61"/>
    <p:inputText id="globalFilter">
       <p:ajax event="keyup"
               oncomplete="PF('widgetColPlanCompteM61').filter()"
               update="idNbLignes"/>
    </p:inputText>
</f:facet>

<f:facet name="footer">
    <h:outputText id="idNbLignes" value="#{planCompteM61ManagerBean.listeFiltre.size()}"/>
</f:facet>


text:
Q: Riesz–Markov–Kakutani representation theorem for compact non-Hausdorff spaces Let $X$ be a compact Hausdorff topological space, and $\mathcal C^0 (X) = \{f:X\to\mathbb{R}; \ f \text{ is continuous }\}$. It is well known that for any bounded linear functional  $\phi: \mathcal C^0(X)\to\mathbb{R},$ such that $\phi(f)\geq 0$ if $f\geq 0$ ($\phi$ is called a positive linear functional), then there exists a unique regular Borel measure $\mu$, such that
$$\phi(g) = \int g\ \mathrm d\mu, \ \forall \ g\in \mathcal C^0(X).  $$
This result follows from a direct application of Riesz–Markov–Kakutani representation theorem.
If we drop the Hausdorff hypothesis (only assuming $X$ as compact topological space). Then we can lose the uniqueness of the measure that represents the linear functional. A famous example is the compact topological space "$[0,1]$ with to origins". In this case the functional $\phi: \mathcal C^0(X)\to\mathbb{R}$,   $\phi(f) = f(0)$ can be written as $\int f\ \mathrm{d}\delta_0$ or   $\int f\ \mathrm{d}\delta_{0'}.$
I would like to know if we still have the existence of a measure that represents the functional. In other words, I would like to know if the following theorem is true

Possible Theorem: Let $(X,\tau)$ be a compact non-Hausdorff space, and $\Lambda : \mathcal C^0(X)\to\mathbb{R}$ a positive bounded linear functional, then there exists a measure $\mu: \mathcal B(\tau)\to \mathbb{R}$ (where $\mathcal B(\tau)$ is the smallest $\sigma$-algebra such that $\tau\subset \mathcal B(\tau))$, such that
  $$\Lambda(f) = \int f\ \mathrm{d}\mu, \ \forall \ f\in \mathcal C^0(X).$$

Can anyone help me?
I have searched online but I was not able to find a result in the non-Hausdorff case.

A: The answer is yes.
First, it follows from the following result and the Riesz–Markov–Kakutani representation theorem that we can always find a suitable Baire measure representing a positive linear functional.

Theorem: Let $X$ be any topological space. Then there exists a completely regular Hausdorff space $Y$ and a continuous surjection
  $\tau:X\to Y$ such that the function $g\mapsto g\circ\tau$ is an
  isomorphism from $C_B(Y)$ onto $C_B(X)$.

This is Theorem 3.9 of "Rings of continuous functions" (1960) by Gillman and Jerison.
So the problem reduces to the question whether a Baire measure on a compact topological space can be extended to a Borel measure. We can do this using the following result, which specializes the very abstract Theorem 2.6.1 of "Convex Cones" (1981) by Fuchssteiner and Lusky.

Theorem: Let $X$ be a non-empty compact topological space and $L:\mathcal{C}^0_+(X)\to\mathbb{R}$ be an additive function on the
  cone of nonnegative continuous functions on $X$ such that
  $L(g)\leq\max g$ for all $g$. Then there exists a Borel probability
  measure $\nu$ on $X$ such that $$L(g)\leq\int g~\mathrm d\nu$$ for
  all $g\in \mathcal{C}^0_+(X)$.

For nonzero $\Lambda$, let $L=1/\Lambda(1)\cdot \Lambda$. Then the measure $\mu=\Lambda(1)\cdot\nu$ does the trick.
It should be noted that the resulting Borel measure need not be regular. For non-Hausdorff $X$, there is no point in going beyond Baire measures.


text:
Q: Can't open a dcom session with jinterop I'm trying to use jinterop to run wmi queries on remote PCs, but I can't even start a dcom session. I know wmi is working because I can access it with powershell\wmic\vbscript without issues. Also, our windows clients have file sharing disabled.
Here is what I am trying:
import static org.jinterop.dcom.impls.JIObjectFactory.narrowObject;
import static org.jinterop.dcom.impls.automation.IJIDispatch.IID;

import java.net.UnknownHostException;

import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.core.JIComServer;
import org.jinterop.dcom.core.JISession;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import static org.jinterop.dcom.core.JIProgId.valueOf;
import org.jinterop.dcom.core.JIVariant;
import org.jinterop.dcom.core.JIString;

public class SimpleServiceManager {

    public static void main(String[] args) {
        String domain = "mydom";
        String hostname = "remotepc";
        String username = "myusername";
        String password = "mypass";

        JISession dcomSession = JISession.createSession(domain, username, password);
        JIComServer comServer;
        try {
            comServer = new JIComServer(valueOf("WbemScripting.SWbemLocator"), hostname, dcomSession);

            IJIDispatch wbemLocator = (IJIDispatch) narrowObject(comServer.createInstance().queryInterface(IID));

            Object[] params = new Object[] {
                    new JIString(hostname),
                    new JIString("ROOT\\CIMV2"),
                    JIVariant.OPTIONAL_PARAM(),
                    JIVariant.OPTIONAL_PARAM(),
                    JIVariant.OPTIONAL_PARAM(),
                    JIVariant.OPTIONAL_PARAM(),
                    new Integer(0),
                    JIVariant.OPTIONAL_PARAM()
            };
            JIVariant results[] = wbemLocator.callMethodA("ConnectServer", params);
            IJIDispatch wbemServices = (IJIDispatch) narrowObject(results[0].getObjectAsComObject());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JIException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 }

Gives me this:
Apr 10, 2013 1:14:38 PM org.jinterop.dcom.common.JISystem logSystemPropertiesAndVersion
INFO: j-Interop Version = j-Interop 2.08

Apr 10, 2013 1:14:38 PM org.jinterop.dcom.common.JISystem logSystemPropertiesAndVersion
INFO: java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jre7\bin
java.vm.version = 23.7-b01
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/
path.separator = ;
java.vm.name = Java HotSpot(TM) Client VM
file.encoding.pkg = sun.io
user.country = US
user.script =
sun.java.launcher = SUN_STANDARD
sun.os.patch.level = Service Pack 1
java.vm.specification.name = Java Virtual Machine Specification
user.dir = C:\Users\myusername\Google Drive\code\Workspaces\Eclipse IDE for Java Developers 422\Jinterop
java.runtime.version = 1.7.0_17-b02
java.awt.graphicsenv = sun.awt.Win32GraphicsEnvironment
java.endorsed.dirs = C:\Program Files\Java\jre7\lib\endorsed
os.arch = x86
java.io.tmpdir = C:\Users\myusername\AppData\Local\Temp\
line.separator =

java.vm.specification.vendor = Oracle Corporation
user.variant =
os.name = Windows 7
sun.jnu.encoding = Cp1252
java.library.path = C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;...
java.specification.name = Java Platform API Specification
java.class.version = 51.0
sun.management.compiler = HotSpot Client Compiler
os.version = 6.1
user.home = C:\Users\myusername
user.timezone = America/New_York
java.awt.printerjob = sun.awt.windows.WPrinterJob
file.encoding = Cp1252
java.specification.version = 1.7
java.class.path = C:\Users\myusername\Google Drive\code\Workspaces\Eclipse IDE for Java Developers 422\Jinterop\bin;C:\Users\myusername\Google Drive\code\Workspaces\Eclipse IDE for Java Developers 422\Jinterop\libs\j-interop.jar;C:\Users\myusername\Google Drive\code\Workspaces\Eclipse IDE for Java Developers 422\Jinterop\libs\j-interopdeps.jar;C:\Users\myusername\Google Drive\code\Workspaces\Eclipse IDE for Java Developers 422\Jinterop\libs\jcifs-1.2.19.jar
user.name = myusername
java.vm.specification.version = 1.7
sun.java.command = SimpleServiceManager
java.home = C:\Program Files\Java\jre7
sun.arch.data.model = 32
user.language = en
java.specification.vendor = Oracle Corporation
awt.toolkit = sun.awt.windows.WToolkit
java.vm.info = mixed mode, sharing
java.version = 1.7.0_17
java.ext.dirs = C:\Program Files\Java\jre7\lib\ext;C:\Windows\Sun\Java\lib\ext
sun.boot.class.path = C:\Program Files\Java\jre7\lib\resources.jar;C:\Program Files\Java\jre7\lib\rt.jar;C:\Program Files\Java\jre7\lib\sunrsasign.jar;C:\Program Files\Java\jre7\lib\jsse.jar;C:\Program Files\Java\jre7\lib\jce.jar;C:\Program Files\Java\jre7\lib\charsets.jar;C:\Program Files\Java\jre7\lib\jfr.jar;C:\Program Files\Java\jre7\classes
java.vendor = Oracle Corporation
file.separator = \
java.vendor.url.bug = http://bugreport.sun.com/bugreport/
sun.io.unicode.encoding = UnicodeLittle
sun.cpu.endian = little
sun.desktop = windows
sun.cpu.isalist = pentium_pro+mmx pentium_pro pentium+mmx pentium i486 i386 i86

Apr 10, 2013 1:14:38 PM org.jinterop.dcom.core.JIComOxidRuntime$ClientPingTimerTask run
INFO: Running ClientPingTimerTask !
Apr 10, 2013 1:14:38 PM org.jinterop.dcom.core.JISession createSession
INFO: Created Session: -1745354837
Apr 10, 2013 1:14:38 PM org.jinterop.dcom.core.JIComOxidRuntime$ServerPingTimerTask run
INFO: Running ServerPingTimerTask !
Apr 10, 2013 1:14:38 PM org.jinterop.dcom.core.JISession$Release_References_TimerTask run
INFO: Release_References_TimerTask:[RUN] Session:  -1745354837 , listOfDeferencedIpids.size(): 0
Apr 10, 2013 1:14:38 PM org.jinterop.dcom.common.JISystem saveDBPathAndLoadFile
INFO: progIdVsClsidDB: {}
org.jinterop.dcom.common.JIException: Message not found for errorCode: 0xC0000034
    at org.jinterop.winreg.smb.JIWinRegStub.winreg_OpenHKLM(JIWinRegStub.java:115)
    at org.jinterop.dcom.core.JIProgId.getIdFromWinReg(JIProgId.java:130)
    at org.jinterop.dcom.core.JIProgId.getCorrespondingCLSID(JIProgId.java:162)
    at org.jinterop.dcom.core.JIComServer.<init>(JIComServer.java:413)
    at SimpleServiceManager.main(SimpleServiceManager.java:25)
Caused by: jcifs.smb.SmbException: The system cannot find the file specified.
    at jcifs.smb.SmbTransport.checkStatus(SmbTransport.java:522)
    at jcifs.smb.SmbTransport.send(SmbTransport.java:622)
    at jcifs.smb.SmbSession.send(SmbSession.java:239)
    at jcifs.smb.SmbTree.send(SmbTree.java:109)
    at jcifs.smb.SmbFile.send(SmbFile.java:718)
    at jcifs.smb.SmbFile.open0(SmbFile.java:923)
    at jcifs.smb.SmbFile.open(SmbFile.java:940)
    at jcifs.smb.SmbFileOutputStream.<init>(SmbFileOutputStream.java:142)
    at jcifs.smb.TransactNamedPipeOutputStream.<init>(TransactNamedPipeOutputStream.java:32)
    at jcifs.smb.SmbNamedPipe.getNamedPipeOutputStream(SmbNamedPipe.java:187)
    at rpc.ncacn_np.RpcTransport.attach(RpcTransport.java:92)
    at rpc.Stub.attach(Stub.java:106)
    at rpc.Stub.call(Stub.java:110)
    at org.jinterop.winreg.smb.JIWinRegStub.winreg_OpenHKLM(JIWinRegStub.java:113)
    ... 4 more

Why is a jcifs.smb.SmbException getting thrown? WMI does not use smb so why am I seeing this error? Does jinterop require clients to have windows file sharing enabled?

A: There is a discussion about this issue in this thread.
Quick summary:
First, make sure the Remote Registry service is enabled.
Second, make sure that no auto-registration is used by j-interop (otherwise you will run into Access Denied errors):
JISystem.setAutoRegisteration(false);

Third, be sure that the firewall is not interfering.

A: I am responding to your statement "I can't even start a dcom session" .Here is the code using j-interop to get the session.
try {
        args[0] = "x.y.z.w";
        String domain       = "";//i am using it as blank
        String username     = "username";//user who logs in to the system as admin
        String password     = "password";// used by admin to login to windows pc

        JISystem.getLogger().setLevel(Level.FINEST);
        JISystem.setInBuiltLogHandler(false);
        JISystem.setAutoRegisteration(true);
        JISession session3 = JISession.createSession(domain,username,password);
        session3.useSessionSecurity(true);
        System.out.println(" session3 "+session3);
    }catch(Exception e){
        e.printStackTrace();
    }

you will see the output
session3 org.jinterop.dcom.core.JISession@a46bc929


text:
Q: prevent default browser action but allow library code in meteor I converted my brewery's website to use meteor. In the conversion process I have run into a bug in the integration of some library code. The original site uses lightbox2 http://lokeshdhakar.com/projects/lightbox2/ to pop up a modal of a graphic we designed.
In the meteor version the modal looks like its about to load but then instead just navigates directly to the image asset the modal is supposed to display. Click 'View the Brew Diagram' at http://twbrewing.meteor.com/beers to see the problem in action.
To me it looks like the library code is working but for some reason does not prevent the default browser action. I tried using a preventDefault() on the click event for that, but then nothing happens at all. Ideas?

A: Wrap the HTML in {{#constant}}...{{/constant}} and run any lightbox code in a template render function, e.g.
Template.pictures.rendered = function() {
   lightBoxInit();
}

I don't actually know what the lightbox function is called... it's either something that they will tell you in the docs to run on pageload, or that is wrapped in a $(document).ready() call in the source.  Even better is if there's an API call to run on the elements directly (something like $('img').lightbox() or $('img').each(function(el) { lightbox(el) }).
Sorry I'm not so familiar with lightbox but this is the strategy you need and what you need to look for :)
Note that the rendered function is called on rerendering too.  This is fine for most libraries but if you notice any strange behaviour you'll need to add some logic to ensure that the relevant links are not processed twice (either by using a .data boolean or by destroying and recreating the wrapper).


text:
Q: Checking if a set of vectors spans a specific subspace
Is it possible that $\{(1,2,0),(2,0,3)\}$ can span the subspace $U={(r,s,0) | r}$ and $s\in\mathbb{R}$?

I'm trying to wrap my head around vector spaces, but I think yes.
My reasoning is that the span of $\{(x_1, x_2,x_3...x_n)\}=\{k_1x_1,k_2x_2,k_3x_3...k_nx_n\}$ for any set of scalars $k$. You can get $U$ with $1 (1,2,0) + 0(2,0,3)$, so it spans the subspace $U$. Am I correct? Additionally, does the set span $\mathbb{R}^2$ as well, since the matrix's rank is 2?

A: First question,  no.  For instance $(1,1,0)$ is not in the span.  One way to see this is to put the vectors in a matrix and compute the determinant.
Second question,  the vectors are linearly independent so span a $2$-dimensional subspace. Thus they span a space isomorphic to $\Bbb R^2$.

A: The span of $(1,2,0)$ and $(2,0,3)$ is $a(1,2,0)+b(2,0,3)=(a+2b, 2a, 3b)$ where $a,b\in\mathbb R$.
If we restrict the span to $U=(r,s,0)$ then $3b=0\implies b=0$.
Therefore, the span becomes $(a,2a,0)=a(1,2,0)$ which is a one dimensional subspace of $U$.
Therefore, $U$ is not spanned by the two vectors.

A: Vectors that span a space must perforce be elements of that space. The vector $(2,0,3)$ doesn't lie in $U$—its last coordinate isn't $0$—so we have to discard it. You could also reject $(2,0,3)$ by considering how you might form $(r,s,0)$ by combining the two vectors: you can't cancel out that final $3$ with a multiple of $(1,2,0)$, so $(2,0,3)$ can't be used in a linear combination that produces $(r,s,0)\ne0$.
That leaves multiples of $(1,2,0)$ to work with, but $(1,0,0)\in U$ isn't a multiple of this vector, so the answer is no.

A: This problem can be answered by thinking about $U$ geometrically.  Since $U$ is the set of all vectors $(r, s, 0): r,s\ \epsilon\ \mathbb{R}$, we can think about $U$ as being the set of all vectors in $\mathbb{R}^3$ that lie in the $xy$ plane.  Now consider your spanning set, $\{(1,2,0),\ (2,0,3)\}$.  $(1,2,0)$ and all of its scalar multiples definitely lie in the $xy$ plane, because its 3rd element is zero while its first and second elements are nonzero.  So far so good.  But look at the second vector in your spanning set: $(2,0,3)$ and its scalar multiples do not lie in the $xy$ plane, but rather in the $xz$ plane.
Most of the answers that you see here are based on this observation, and rely on selecting a point in the $xy$ plane that is not on the line parametrically defined by $x=t;\ y=2t, t\ \epsilon\ \mathbb{R}$.
We can come to this same conclusion in a more roundabout way by setting up an augmented matrix and taking it down to reduced row echelon form:
$$\begin{bmatrix}
1&2&r\\
2&0&s\\
0&3&0
\end{bmatrix} \sim
\begin{bmatrix}
1&0&r-\frac{2r-s}{2}\\
0&1&\frac{2r-s}{4}\\
0&0&\frac{s-2r}{4}
\end{bmatrix}$$
Since we only want to deal with consistent solutions (we are considering the span of two vectors, after all), then we need $\frac{s-2r}{4} = 0$.  This tells us that $s=2r$ for all of our consistent solutions.  If we subtitute in $2r$ for $s$, then we find that the only place where our two vectors actually generate solutions that lie in $U$ are when the coefficient of $(2,0,3)$ is $0$ and the coefficient of $(1,2,0)$ is some $r\ \epsilon\ \mathbb{R}$.  $U$ generates a plane, while the subspace generated by $(1,2,0)$ is a line.  You can't span a plane with a line, so your spanning set doesn't span $U$.
Your spanning set is linearly independent, however, and so it does generate a plane in $\mathbb{R}^3$, which we can treat like $\mathbb{R}^2$, but it is not $\mathbb{R}^2$ or $U$.


text:
Q: How to represent local significant differences between curves I want to compare some curves to a 'normality corridor', and I would like to show in what regions (x values) the difference is significant.Take the example below, where I want to compare the dashed lines with the green band:

Each curve represents the median of some values. The curves are not continuous: they only have values at integer x locations, therefore I compare them to the normality corridor at 1, 2, 3, etc.
For the "Width" group I want to show that the difference is significant between all curves and the green band between x=1 and x=3, then only two curves between 4 and 6, then only one curve between 7-8, then two curves etc etc etc...
The problem is that I have 12 groups, each with 3 curves and its own normality corridor, and each of them with 17 levels (integer values of x). That makes for a lot of p-values.
Here is what I came up with for the groups in the example, with the number of asterisks representing the p-value, but I think the message can be made clearer:

TL;DR: How to represent local significant differences between curves and a normality corridor, OR how to represent lots of p-values?


text:
Q: как внедрить содержимое в первый Таб Как засунуть контент в первый таб Видео ? и при нажатии на таб MATTRESSES контент первого таба исчезал и выводился контент второго таба ?

                 <input type="radio" name="nav" id="tab_1" checked="checked"/>
                     Videos
                 <input type="radio" name="nav" id="tab_2"/>
                     Mattresses
                <input type="radio" name="nav" id="tab_3"/>
                     Store Locator

        <video class="videoContent" id="video" autoplay poster="videos/one.png"></video>

        POST TO FACEBOOK

SHARE THE MOST IMPORTANT TECH REVEAL
 OF 2017 WITH YOUR FRIENDS

DISCOVER MORE

A: HTML:

some head

some head

            some content

            some content

JS:
(function($){
    $.fn.tabs=function(){
        var parent=$(this);
        $(parent).each(function(){
            var elem=$(this);
            $(elem).find(".tab-item").not(":first").hide();
            $(elem).find(".tabs-head .tab").show().click(function(){
                var ind=$(this).index();
                $(elem).find(".tabs-head .tab").removeClass("active").eq(ind).addClass("active");
                $(elem).find(".tab-item").hide().eq(ind).fadeIn();
                return false;
            }).eq(0).addClass("active");
        });
    };
})(jQuery);

Вызов:
$("div.tabs").tabs();


text:
Q: The kernel of the natural map $\pi_k(BU(r)) \to \pi_k (BU)$ Is this group known outside of the stable range? If so, what is it? If not, what is known about it?

A: For the homotopy groups of $U(r)$, hence also of $BU(r)$, you can look at the survey by M. Mimura, "Homotopy theory of Lie groups", which is chapter 19 in the "Handbook of Algebraic Topology", edited by I. M. James.  It gives $\pi_k(SU(n))$ for $k\le15$ and for $k\le 2n+6$, in section 3.  The survey also lists many further references.


text:
Q: How to use AdSense API to show saved raports to website users? It's been a long journey.
I've researched all over the place. And it has been painful to find a solution.
I intend to do something, supposedly, simple.
I need to show reports saved in AdSense and the user could search the results based on the time interval chosen.
It turns out that to obtain this information authorization is required. Of course users are not authorized to access AdSense.
I have tried these resources now: link, link
And I have followed the rules and guidelines.
My code is as follows:
require_once 'google-api-php-client-2.2.2/vendor/autoload.php';
putenv('GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json'); //WITH REAL PATH
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');

$httpClient = $client->authorize();

// make an HTTP request
$response = $httpClient->get('https://www.googleapis.com/adsense/v1.4/accounts/pub-00000000/reports/saved');

The result is "unauthorized", "Fatal error", etc.
I am no expert on the subject and I am completely lost.
I really need this to work!
Thank you for your attention and help.