text:
Q: Update Wordpress when using Github Wordpress skeleton This is mainly a clarification about dealing with public Repos for git beginners.
I have a local git repo with a clone of Wordpress skeleton (https://github.com/markjaquith/WordPress-Skeleton). This includes Wordpress as a submodule (https://github.com/WordPress/WordPress).
If I update Wordpress from the dashboard it will require me to update my git repo.
There is a note about making a pull request if the repo falls behind but I am working on my localhost so can't do that.

*

*If I had a hosted repo, should I send a pull request to the WP skeleton or WP repo?

*I have a fresh install at the moment but if I were to customise it I probably wont want to (or Shouldn't) push so what would I do in this case?

Note: This is using the Wordpress repo as an example but I am curious about the best/general practice.

A: I'm having some similar questions, mainly about what the best practice is when updating Wordpress. Should I use the Dashboard once on remote, or should I continue to update the Wordpress Submodule in WP-Skeleton.
I can tell you this, you can update Wordpress via the Submodule in WP-Skeleton by using the "Git Checkout" command on the submodule and choosing the latest release number (4.1 as of this writing). Its extremely simple in SourceTree if you're new to Git and need an interface to help.

A: This is a little late but I asked the author of the repo and he answered me in his QA repo on Github.
This is the answer Mark Jaquith gave there which worked:

For your personal sites, which have likely wildly diverged, the update
  process is as follows:
cd wp
git fetch
git fetch --tags
git checkout 3.9.1
cd ../
git add wp
git commit -m 'Update to WordPress 3.9.1'
git push origin master

Let me break that down:

*

*cd wp — move into the WordPress submodule directory.

*git fetch — Pull down the latest changes from tracked branches.

*git fetch --tags — Pull down the new tags. You do steps 2 and 3 in this order because otherwise you might have a tag that points to a commit that you don't yet have in your repo.

*git checkout 3.9.1 — Checkout the 3.9.1 tag.

*cd ../ — Move back into the main directory. At this point, the wp subdirectory will show as having changes, since it points to a different commit.

*git add wp — Tell your main repo to stage the WordPress submodule repointing.

*git commit -m 'Update to WordPress 3.9.1' — Commit that change git push origin master — Push your master branch (change if using a different branch) up to your origin remote (change if using a different remote).

You probably noticed that there
  is only one variable here — the version number. So You could wrap that
  up into a bash script that you check into your root directory. And
  then you could just do something like: ./wpupdate 3.9.1. Or you could
  write a script that iterates through a bunch of WordPress site
  checkouts and does this process on each of them (I've done exactly
  that).

I will also add that from the wp folder you can enter git tag to see a list of tags, this way you can make sure you get the latest one.


text:
Q: Unable to get Decoding Capabilities by cuvidGetDecoderCaps CUDA SDK I have a server with Tesla T4 GPU. I am trying to decode an H264 video on GPU. I am using Cuda SDK to get CUVIDDECODECAPS (decoding capabilities of GPU) but it is returning 0 to MinWidth, MinHeight, MaxWidth,   MaxHeight, and false to "bIsSupported". ie. This hardware doesn't support decoding on GPU. But according to this link T4 does support video decoding.
Below is the code snippet.
CUVIDDECODECAPS decodeCaps = {};
decodeCaps.eCodecType = _codec;
decodeCaps.eChromaFormat = _chromaFormat;
decodeCaps.nBitDepthMinus8 = videoFormat.nBitDepthMinus8;
cuSafeCall(cuCtxPushCurrent(ctx_));
cuSafeCall(cuvidGetDecoderCaps(&decodeCaps));

cuSafeCall(cuCtxPopCurrent(NULL));

Below is driver and cuda version
NVIDIA-SMI 440.118.02   Driver Version: 440.118.02   CUDA Version: 10.2 Nvidia Video codec SDK is 11.0.10
Does anyone have any idea what's wrong I am doing here?

A: Each Nvidia Video SDK has minimal requirements for CUDA SDK and graphics driver version. If you open the SDK web page you will find this info:
NVIDIA Windows display driver 456.71 or newer
NVIDIA Linux display driver 455.28 or newer
DirectX SDK (Windows only) CUDA 11.0 Toolkit
At least on Linux, the related  NVENC and NVDEC libraries are part of the driver distribution so the latest SDK headers cannot work with the old libs ( according to your driver version).  You can download the older version of the Video SDK if you must use that specific driver.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Point of Intersection of tangents Tangent are drawn to the circle $$x^2+y^2=1$$ at the point where it is met by the circles $$x^2+y^2-(\omega+6)x+(8-2\omega)y-3=0$$ where $$\omega$$  being the variable. Find the locus of point of intersection of these tangents.

A: The circles meet on the line $$-(\omega+6)x+(8-2\omega)y-2=0$$
which is obtained subtracting the equations of the two circles.
The normal vector to this line is $(-\omega-6,8-2\omega)$. Therefore the point on that line closer to the origin is $$\frac{2}{(\omega+6)^2+(8-2\omega)^2}(-\omega-6,8-2\omega)$$
By Pythagoras or by taking into account that this point and the intersection of the tangents are inverses of each other with respect to the unit circle, the point of intersection of the tangents is this point divided by the square of its norm.
$$\frac{1}{2}(-\omega-6,8-2\omega)=\frac{1}{2}(-1,-2)\omega+(-3,4)$$
As $\omega$ moves this travels a line pointing in the direction of $(-1,-2)$ and passing through $(-3,4)$.

A: This is a supplement to Marja's answer, following the same derivation but using projective geometry methods for the calculations.
Subtracting one circle equation from the other, we get the line $$(\omega+6)x+(2\omega-8)y+2=0,$$ which we represent by the homogeneous vector $\mathbf l=[\omega+6:2\omega-8:2]$. (We could also have found this by subtracting the matrices of the two circles and extracting the line from the resulting singular matrix, but this is quicker.) The pole of the line through a pair of points on a conic is the intersection of the tangents through those points. The unit circle's matrix is $C=\operatorname{diag}(1,1,-1)$, i.e., the equation of this circle can be written as $(x,y,1)C(x,y,1)^T=0$. This matrix is its own adjugate, so the intersection of the tangents at the points where $\mathbf l$ intersects $C$ is given by $$C^*\mathbf l=C\,\mathbf l=[\omega+6:2\omega-8:-2].$$ This line is the join of $[6:-8:-2]$ and $[1:2:0]$, which we can convert to non-parametric Cartesian form by taking their cross product, giving $[-4:2:-20]$, i.e., the line $$2x-y+10=0.$$


text:
Q: No puedo actualizar un estado con la pagina actual cuando Navigator ejecuta su método pop No puedo actualizar el estado de mi App.js con la pagina actual cuando Navigator ejecuta su método pop en React-Native (0.26).
Yo actualizo el estado con la function goto.
  _goto(currentPage, scene) {
    this.setState({currentPage});
    this._navigator.push({
      id: currentPage,
    });
  }

Este es la función que renderiza las escenas del Navigator.
  _renderScene(route, nav) {
    curPage = route.id;
    switch (route.id) {
       ...
   }

Teng ona funcion que se ejecuta cuando presiono el boton de atras en Android.
  _patras(){
    if(curPage != 'MainPage' && curPage != 'SplashPage'){
      this._navigator.pop();
      return true;
    }
  }

Y este es el método render de mi App.js donde tengo el TabBar.
var currentPage = this.state.currentPage;
if (currentPage != 'SplashPage'){
  if (this.isAndroid){
    TBar = (<TabBar goto={(page) => this._goto(page)} currentPage={currentPage}/>);
  } else {
    TBar = (<TabBarIOS goto={(page) => this._goto(page)} currentPage={currentPage}/>);
  }
}

Uso la página actual para cambiar el estilo y desabilitar el boton del TabBar que le correspone. Con este código me funciona bien si avanzo pero al momento de dar hacia atrás no se me actualiza dado que solo lo puedo coger a través del goto. Si pongo un this.setState en el metodo renderScene se bloquea la aplicación.
¿Cuál seria la mejor forma de hacerlo?

A: Lo que debe ocurrir es que tabbar crea un nuevo navigator lo cual hace que dentro de ese nuevo navegador la ruta anterior no exista, por eso no puede volver a una ruta que no existe dentro del navegador.
Mi recomendación es usar react-native-router-flux que permite usar el atributo clone que copia la ruta en el navegador permitiendo regresar desde cualquier view.


text:
Q: compare strings two files with awk I am trying to compare field 5 from file1 with field 2 from file2 and show lines when they are equal.
file1
"202005";"RS";"4301602";"CITY";"12651500714";"***.368.660-**";"TESTE TESTE";"-2";""
"202005";"RS";"4301602";"BAGE";"00000000000";"***.977.440-**";"XXXXX XXXEZ";"-2";""

file2
"93330090006";"12651500714";"TESTE XX";
"01168199018";"16108835006";"SOME NAME";

I searched and used a lot of codes, but it's not working.
My last code:
awk -F";"  'NR==FNR{a[$4,$2];next} ($0) in a' file1 file2

The expected result can be just entire line from file1:
"202005";"RS";"4301602";"CITY";"12651500714";"***.368.660-**";"TESTE TESTE";"-2";""

A: You may try this code:
awk 'BEGIN{FS=";"} FNR == NR {seen[$2]; next} $5 in seen' f2 f1

"202005";"RS";"4301602";"CITY";"12651500714";"***.368.660-**";"TESTE TESTE";"-2";""

This command will only print lines from file2 where 5th column from file1 is same as 2nd column from file2.

A: An alternate solution is to use the *nix utility join.
 join -t\; -1 5 -2 2 -o 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 f1.txt f2.txt

produces the output
"202005";"RS";"4301602";"CITY";"12651500714";"***.368.660-**";"TESTE TESTE";"-2";""

Note that both files need to be sorted by their key field. If your data needs sorting, this can be accomplished in-line using process substitution :
join -1 5 -2 2 -t\; <(sort -t\; -k5 f1.txt)  <(sort -t\; -l2 f2.txt)

Note also the flexibility of join in that you specify the key field number after the file number, ie, -1 5 in this case.
Finally, note that if you wanted the "joined" output of both files the command would be simpler, i.e.
join -t\; -1 5 -2 2 f1.txt f2.txt

producing the output of the first file and the second file on one line. Note that the key field is not including in the file 2 output.
"12651500714";"202005";"RS";"4301602";"CITY";"***.368.660-**";"TESTE TESTE";"-2";"";"93330090006";"TESTE XX";

For beginners, the man join is rather a terse description of the features. Look for online tutorials that match your learning style, or search here, as there are many Q/As on the subject (often as an answer to a similar Q).
IHTH


text:
Q: Issue with RestSharp installation in Visual-Studio 2013 I am trying to use RestSharp in my C# Visual-Studio 2013 project to POST data at a given URL. When i try to install the package via NuGet it gives me the following error:
Installing 'RestSharp 106.1.0'.
Successfully installed 'RestSharp 106.1.0'.
Adding 'RestSharp 106.1.0' to WebApplicationJson.
Uninstalling 'RestSharp 106.1.0'.
Successfully uninstalled 'RestSharp 106.1.0'.
Install failed. Rolling back...
Could not install package 'RestSharp 106.1.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.

As far as I have read in GitHub this is mostly an issue for .NetPortable framework so I am out of ideas. I have also tried to change my framework version to 3.5 but still the same error.
Has anyone encountered a similar issue?
If you need further information please comment.

A: The latest version, which supports old .NET Framework versions, is 105.2.3.
Install-Package RestSharp -Version 105.2.3

Since the lowest .NET Framework LTE, which supports async methods is 4.5.2, support of legacy framework has been removed in favour of supporting .NET Standard 2.0 (and .NET Framework 4.5.2).

A: This also happens if the name of your project is RestSharp.

A: If anyone encounters this kind of problem in the future. I solved it by installing it via Package Manager Console found in (Tools -> NuGet Package Manager -> Package Manager Console) and running the following command:
  Install-Package RestSharp -Version 103.1.0

Notice that the installation for RestSharp version 106.1.0 always kept failing, so I changed the version to 103.1.0. Hope this helps anyone with a similar issue.
EDIT
Thanks to phuzi in the comments, RestSharp version 106.1.0 requires .Net framework 4.5.2, as for version 103.1.0 no dependencies are listed.


text:
Q: How to drag and drop rows in NSTableView in Mac I have struck with one point i.e now I have got a list of data using NSTableView but what my requirement is, able to drag and drop that rows from one row position to another row position. please give any suggestion for get out this problem. Thanks in advance.
My sample code

A: Within your NSTableViewDataSource subclass implement WriteRows,  ValidateDrop and AcceptDrop and register which Drag/Drop targets your NSTableView accepts. In this case you are only accepting Drops from within your own NSTableView.
Assign a name that will be used for valid drag operations on this NSTableView:
// Any name can be registered, I find using the class name
// of the items in the datasource is cleaner than a const string
string DragDropType = typeof(Product).FullName;

Register the drag types for your NSTableView:
ProductTable.RegisterForDraggedTypes(new string[] { DragDropType });

Implement drag/drop methods on your NSTableViewDataSource:
public override bool WriteRows(NSTableView tableView, NSIndexSet rowIndexes, NSPasteboard pboard)
{
    var data = NSKeyedArchiver.ArchivedDataWithRootObject(rowIndexes);
    pboard.DeclareTypes(new string[] { DragDropType }, this);
    pboard.SetDataForType(data, DragDropType);
    return true;
}

public override NSDragOperation ValidateDrop(NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
    tableView.SetDropRowDropOperation(row, dropOperation);
    return NSDragOperation.Move;
}

public override bool AcceptDrop(NSTableView tableView, NSDraggingInfo info, nint row, NSTableViewDropOperation dropOperation)
{
    var rowData = info.DraggingPasteboard.GetDataForType(DragDropType);
    if (rowData == null)
        return false;
    var dataArray = NSKeyedUnarchiver.UnarchiveObject(rowData) as NSIndexSet;
    Console.WriteLine($"{dataArray}");
    // Move hack for this example... you need to handle the complete NSIndexSet
    tableView.BeginUpdates();
    var tmpProduct = Products[(int)dataArray.FirstIndex];
    Products.RemoveAt((int)dataArray.FirstIndex);
    if (Products.Count == row - 1)
        Products.Insert((int)row - 1 , tmpProduct);
    else
        Products.Insert((int)row, tmpProduct);
    tableView.ReloadData();
    tableView.EndUpdates();
    return true;
}


text:
Q: Calculate Triangle From Area And Angles I'm trying to calculate triangles base on the Area and the angles. If Angle-B is 90° then the formula works, but in my case, the angle can be from 0.1° to 179.8°. The formula assumes that the angle is 90, so I was thinking that there might be something that is hidden that could work for very angle. Here is the formula:

The formula in code would be:
Height = sqrt((2 * Area) / (tan(Angle-A)));

I'm looking for the second half of the formula. Would the next part of the formula be something like this:
cos(sin(AngleB))

A: Okay, new try: If my calculations are correct, side B equals sqrt(2*area*sin(angle-B)/(sin(angle-A)*sin(angle-C))
Since Area = 1/2 * A * B * sin(c) = 1/2 * C * B * sin(a) = 1/2 * A * C * sin(b) we get:
A = 2 * area / (B * sin(c)) and using this we get:
C = sin(c) * B / sin(b) and when we place that back into the equation of area, we get:
B = sqrt(2*area*sin(angle-B)/(sin(angle-A)*sin(angle-C))
When you know one side and all the angles, calculating the other sides should be easy using normal trigonometry.

A: tziki's answer is correct, but I'd like to elaborate on how it's derived.
We start with angles and area as knowns. I'm going to use the labels in the OP's diagram for this explanation.
First we have the basic truth that the area of a triangle is half the product of its base and height: Area = base * height / 2. We want to be able to determine the relationship between base and height so that we can reduce this equation to one unknown and solve for base.
Another important thing to know is that the height of the triangle is proportional to Side-A: height = Side-A * sin(Angle-B). So knowing Side-A will give us the height.
Now we need to establish a relationship between Side-A and Side-C (the base). The most appropriate rule here is the sine law: Side-A/sin(A) = Side-C/sin(C). We re-arrange this equation to find Side-A in terms of Side-C: Side-A = Side-C * sin(A)/sin(C).
We can now insert this result into the height equation to get the formula for height in terms of Side-C only: height = Side-C * sin(A) * sin(B) / sin(C)
Using Side-C as the base in the area equation, we can now find the area in terms of Side-C only: Area = Side-C^2 * sin(A) * sin(B) / 2sin(C)
Then re-arrange this equation to find Side-C in terms of Area:
Side-C = SQRT(2 * Area * sin(C) / (sin(B) * (sin(A)))

And that gives you one side. This can be repeated to find the other sides, or you can use a different approach to find the other sides knowing this one.

A: You already have your answer, but I had to solve this kind of exercise for a job interview some time ago. It's not hard, and it didn't took me much time to arrive to the following solution.
Read it through and it should be self explanatory.

Create a Python module that solves triangles by aplying the sin and cosin theorems.
The module receives as parameters some of a triangle's values and, if possible, returns the values of all it's angles and side lengths.
The parameters are received as a dict and it should be able to be called stand-alone from the command line.

from __future__ import division
import sys, logging
from math import radians, degrees, acos, cos, sin, sqrt, asin

class InconsistentDataError(TypeError):
    pass

class InsufficientDataError(TypeError):
    pass

class NonUpdatable(dict):
    """Dictionary whose items can be set only once."""
    def __setitem__(self, i, y):
        if self.get(i, None):
            raise InconsistentDataError()
        super(NonUpdatable, self).__setitem__(i, y)

def get_known_sides(**kwarg):
    """Filter from the input elements the Side elements."""
    return dict([i for i in kwarg.iteritems() if i[0].isupper()])

def get_known_angles(**kwarg):
    """Filter from the input elements the Angle elements."""
    return dict([i for i in kwarg.iteritems() if i[0].islower()])

def get_opposite_angle(C, B, A):
    """
    Get the angle corresponding to C.

    Keyword arguments:
    A -- right side of the angle (real number > 0)
    B -- left side of the angle (real number > 0)
    C -- side opposite to the angle (real number > 0)

    Returns:
    angle opposite to C
    """
    return degrees(acos((A**2 + B**2 - C**2) / (2 * A * B)))

def get_side(A, B, c):
    """
    Calculate the Side corresponding to the Angle c.

    Keyword arguments:
    A -- left side of C (real number > 0)
    B -- right side of C (real number > 0)
    c -- angle opposite to side C (real number)

    Returns:
    side C, opposite to c
    """
    return sqrt(A**2 + B**2 - 2*A*B*cos(radians(c)))

def get_overlapping_angle(known_angles, known_sides):
    """
    Calculate the Angle of a known side, knowing the angle to another known side.

    Keyword arguments:
    known_angles -- (dict of angles)
    known_sides -- (dict of sides)

    Returns:
    angle of the known side, to which there is no known angle
    """
    a = (set([i.lower() for i in known_sides.iterkeys()]) -
            set([i.lower() for i in known_angles.iterkeys()])).pop()

    b = (set([i.lower() for i in known_sides.iterkeys()]) &
            set([i.lower() for i in known_angles.iterkeys()])).pop()

    y = (known_sides[a.upper()]/known_sides[b.upper()]) * sin(radians(known_angles[b.lower()]))
    if y > 1: y = 1 #Rounding error fix --- y = 1.000000000001; asin(y) -> Exception
    return {a.lower(): degrees(asin(y))}

def get_angles(A, B, C):
    """
    Calculate all the angles, given the length of all the sides.

    Keyword arguments:
    A -- side A (real number > 0)
    B -- side B (real number > 0)
    C -- side C (real number > 0)

    Returns:
    dict of angles
    """
    sides = {"A":A,"B":B,"C":C}
    _sides = sides.keys()
    angles = {}

    for side in sides.keys():
        angles[side.lower()] = get_opposite_angle(
                                    sides[_sides[0]],
                                    sides[_sides[1]],
                                    sides[_sides[2]])
        _sides.append(_sides.pop(0))

    return angles

def get_triangle_values(**kwargs):
    """Calculate the missing values of a triangle based on the known values."""
    known_params = kwargs
    angles = NonUpdatable({
        "a":0,
        "b":0,
        "c":0,
    })
    sides = NonUpdatable({
        "A":0,
        "B":0,
        "C":0,
    })

    if len(known_params) < 3:
        raise InsufficientDataError("Three parameters are needed to calculate triangle's values.")

    if str(known_params.keys()).islower():
        raise TypeError("At least one length needed.")

    known_sides = NonUpdatable(get_known_sides(**known_params))
    sides.update(known_sides)
    known_angles = NonUpdatable(get_known_angles(**known_params))
    angles.update(known_angles)

    if len(known_angles) == 3 and sum(known_angles.itervalues()) != 180:
        raise InconsistentDataError("One of the sides is too long.")

    if len(known_sides) == 3:
        x=[side for side in known_sides.itervalues() if (sum(known_sides.itervalues()) - side) < side]
        if len(x):
            raise InconsistentDataError("One of the sides is too long.")

        for angle, value in get_angles(**known_sides).iteritems():
            # Done this way to force exception when overwriting a
            # user input angle, otherwise it would be a simple assignment.
            # >>> angles = get_angles(**known_sides)
            # This means inconsistent input data.
            angles[angle] = value

    else: # There are angles given and not enough sides.
        if len(known_angles) > 1:
            #2 angles given. Get last angle and calculate missing sides
            for angle, val in angles.iteritems():
                if val == 0:
                    angles[angle] = 180. - sum(angles.itervalues())

            known_sides = known_sides.items()
            for side, length in sides.iteritems():
                if length == 0:
                    sides[side] = known_sides[0][1] / \
                        sin(radians(angles[known_sides[0][0].lower()])) * \
                        sin(radians(angles[side.lower()]))

        else:
            unknown_side = (set(sides.keys()) - set(known_sides.keys())).pop()

            chars = [ord(i.lower()) for i in known_params.iterkeys()]
            chars.sort()

            if chars[0] < chars[1] < chars[2]:
                sides[unknown_side] = get_side(known_sides.values()[0], known_sides.values()[1], known_angles[unknown_side.lower()])
                angles = get_angles(**sides)

            else:
                known_angles.update(get_overlapping_angle(known_angles, known_sides))
                angles.update(known_angles)

                for angle, val in angles.iteritems():
                    if val == 0:
                        angles[angle] = 180. - sum(angles.itervalues())

                sides[unknown_side] = get_side(known_sides.values()[0], known_sides.values()[1], angles[unknown_side.lower()])

    angles.update(sides)
    return angles

if __name__ == "__main__":
    try:
        values = get_triangle_values( **eval(sys.argv[1], {}, {}) )
    except IndexError, e:
        values = get_triangle_values(A=10,B=10,C=10)
    except InsufficientDataError, e:
        print "Not enough data!"
        exit(1)
    except InconsistentDataError, e:
        print "Data is inconsistent!"
        exit(1)

    print values

A, B and C are the side lengths and a, b and c are the angles, so c is the angle opposite to the side C.
Tests

A: If I made no mistake the length of a side x between two angles a and b should be the following.
         ________________
        /  2A       2A
x =    / ------ + ------
     \/  tan(a)   tan(b)

So to calculate side-C you but in angle-A and angle-B.
(Now double checked it - seems to be correct.)

A: How about calculating the lengths of two of the sides of a triangle where the third size is assigned a length of 1 (using the law of sines on the angles, with that side assigned length 1), then scale the triangle until its area matches the area you have? Then you can calculate the height fairly easily. http://en.wikipedia.org/wiki/Triangle_area#Using_trigonometry

A: The formula you give for Side-A seems to be correct IF the triangle is isosceles, i.e., Angle-B = Angle-C (you get this using the law of sines and the sine formula for the area). If it is not isosceles, you seem to need to know the other angles; the general formula is:
Side-A = sqrt(2*Area*sin(Angle-A)/(sin(Angle-B)*sin(Angle-C)))

Of course, I did this in my head, so check the math ;)
Edit: Ok, fixed the formula after checkin on paper.


text:
Q: Treating missing values in sentiment analysis I have a medium-sized dataset of encrypted comments and their corresponding labels, which is either of positive or negative. I wonder what the best way is to treat the missing comments given that the missing comments rate is 1%. Below is a toy example of the dataset after applying an extensive data cleaning step.
df=pd.DataFrame({'comments':['xxy uuicz', '', 'jiko bhht'], 'label':['positive', 'negative', 'negative']})

I am using Gensim (preprocess_string) and removing stopwords through building a customized list of stopwords. The goal is to fit a classifier to predict the sentiment of any given encrypted comment.


text:
Q: Retrieve Index When Passing Object to Function I'm passing an Object from an array of objects to a function. Is it possible to still retrieve the index number somehow from the object in the function?
 I'm doing this in javaScript specifically within the controller of AngularJS.
For instance
var array= [
    {
        name: "name1"
    },
    {
        name: "name2"
    }
];

function( passedInObjectFromArray ) {
    return passedInObjectFromArray.indexVal;
}

A: Yes you can do,
$scope.retrieveIndex =  function(passedInObjectFromArray){
    return array.indexOf(passedInObjectFromArray);
 }


text:
Q: How decoupled should controllers and views really be in MVC? Views are, by definition, supposed to be logicless. When a user interacts with a view, it notifies its controller. When state changes in the app, the controller notifies the view. But I'm confused as to the nature of the communication between view and its controller when it's time to re-render some or all of the view.
Let's pretend I'm making a two player card game. The view is responsible for showing the deck, the discard pile, the cards in players' hands, and any other UI components. When a player plays a card, the view needs to reflect this change, and it's the controller's job to notify the view to do so. Which of these options is the best way to handle this event?

*

*The controller tells the view simply to re-draw. The view, through the controller, has access to all the parameters of the game state. It uses these parameters to re-draw everything including the deck, both player's hands, etc.

*The controller tells the view that a player played a card. The view knows that when a player plays a card, only that player's hand needs to be re-drawn. Like option 1, the view uses the parameters of the game state to determine how to re-draw the player's hand.

*(Similar but different from 2) The controller tells the view to re-draw that player's hand and passes it all the parameters needed to do so. The view has no access to game parameters.

*Any other approach I'm missing?
Option 1 seems to be the easiest two write because the view is stateless -- it just re-draws everything every time. But for that same reason, it is very wasteful. We don't need to draw both player's hands when just one player played a card. It's also difficult to do things like animation because every time we re-draw, we're essentially throwing away our old canvas and building a fresh one with all new view components.
On the other end of the spectrum, option 3 seems to be best in terms of removing logic from a view, but it comes with some issues. First, I've found it more difficult to write because it's imperative that all the proper messages are sent to the view. If any are missed, the view won't properly reflect the state of the app. Second, it seems like a full re-draw is still necessary at times for when, say, the user is restoring a saved game in progress.
In both options 1 and 2, the view "pulls" data about the game state whereas this data is "pushed" to it in option 3. Should views be able to request information like this, or does this imply that there's too much logic in the view?
Thanks in advance for any light you can shed on this topic!

A: MVC is not the best fit for all applications. It also depends on what kind of frameworks which are available.
By not taking the platforms/frameworks into account I'll say that HMVC (Hierarchical model–view–controller) or PAC (Presentation–abstraction–control) is a better fit for you since a page can be splitted up into several parts (three views: hands & deck).
When it comes to native applications (GUI) it seems like MVP is preferred over MVC.
Martin Fowler has a nice article about the different GUI patterns here: http://www.martinfowler.com/eaaDev/uiArchs.html


text:
Q: How can I make a multiple required select option in html5? How can I make a multiple required select option in html5? The user must select at least 2 options.
<select name='type' required multiple='multiple'>
    <option>...</option>
    ...
</select>

I tried this but it doesn't work and doesn't check if there are more then one selected.

A: <select id="choice" multiple="multiple">
  <option value="1">One</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<script type="text/javascript">

var optionsToSelect = ['One','two', 'three'];
var select = document.getElementById( 'choice' );

for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
  o = select.options[i];
  if ( optionsToSelect.indexOf( o.text ) <= 1 )
  {
    alert('Plz select at least 2 options')

  }
}

A: A bit late but for other users that came long internet search.
You can do that using HTML5 but be sure you are not disabling the default behavior.
$("#mybtnId").click(function() {

  var isValid = $("#MyForm")[0].checkValidity();
  if(false === isValid){
    //allow the browser's default submit event behavior
    return true;
  }
  event.preventDefault();  <-- disable default behavior after check validation

  //...
});


text:
Q: Duplicate row based on date difference help needed. I have a set of data from oracle import to tableau for calculation. But in order to do that, i need to duplicate charts as shown in table below. For example, if there is date diff between start and end, then i need to duplicate it and assign with code 0,1 depend on how many date differences. The purpose is i need to use this function in Tableau for time interval calculation. Thanks

A: Pregenerate codes up to max possible value and join original table to code series so that number of row duplications is determined by difference between dates on particular row:
with t (s,e) as (
  select timestamp '2020-08-16 18:30:00', timestamp '2020-08-16 20:00:00' from dual union all
  select timestamp '2020-08-17 08:00:00', timestamp '2020-08-18 08:00:00' from dual union all
  select timestamp '2020-08-19 08:00:00', timestamp '2020-08-19 00:00:00' from dual union all
  select timestamp '2020-08-20 10:00:00', timestamp '2020-08-22 03:00:00' from dual
), series (code) as (
  select level - 1 from dual connect by level <= (select count(*) from t)
)
select t.*, series.code
from t
join series on trunc(e) - trunc(s) >= series.code
order by s,code;


text:
Q: onFocus stops firing after modal popup I have where I use an onfocus event handler to do several things. It works great after initial page load. However, after I click on a link that opens a modal popup the onfocus event stops working. Focus still works fine... but the onfocus event is never fired again until the page is reloaded. How can focus happen without the onfocus event firing?
jQuery(":input").on("focus", function(e)
{
    console.log("Debug 1");
});

Before the modal popup this call fires the event handler above...
pTR.find("td:eq(13)").children(":first").focus();

After closing the popup that same call does give that element focus, but the event handler isnt fired.
How is this possible?

A: I didn't understand very well the question, but I think putting
e.preventDefault();

or
e.stopPropagation();

at the beginning of your onfocus event might help...
Try both depending of your situation.


text:
Q: Flutter iOS "replacing existing signature" "permission denied" error. Command PhaseScriptExecution failed with a nonzero exit code I was working on this flutter project mainly for ios deployment for about 4 months and we had to revisit the project to make some changes. It was working fine. I had to add firebase_crashlytics to the project. So when I added it, an error popped up saying:
The current Flutter SDK version is 1.9.1+hotfix.4.

Because vitalsmobile depends on firebase_crashlytics >=0.1.2 which requires Flutter SDK version >=1.9.1+hotfix.5 <2.0.0, version solving failed.

pub get failed

So I reverted and tried compiling for ios simulator to check if everything was working fine and iOS threw this error:
PhaseScriptExecution [CP]\ Embed\ Pods\ Frameworks /Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Runner.build/Script-62580339D8295FD31996B914.sh (in target 'Runner' from project 'Runner')
    cd /Users/ag32547/Documents/GitHub/vitalsmobileboilerplate/ios
    /bin/sh -c /Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Intermediates.noindex/Runner.build/Debug-iphonesimulator/Runner.build/Script-62580339D8295FD31996B914.sh

mkdir -p /Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks
rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/ag32547/Documents/GitHub/vitalsmobileboilerplate/ios/Pods/../Flutter/Flutter.framework" "/Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks"
building file list ... done
Flutter.framework/
Flutter.framework/Flutter
Flutter.framework/Info.plist
Flutter.framework/icudtl.dat
Flutter.framework/_CodeSignature/
Flutter.framework/_CodeSignature/CodeResources

sent 94440040 bytes  received 120 bytes  62960106.67 bytes/sec
total size is 94428117  speedup is 1.00
Stripped /Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework/Flutter of architectures: armv7 arm64
Code Signing /Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework with Identity -
/usr/bin/codesign --force --sign -  --preserve-metadata=identifier,entitlements '/Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework'
/Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework: replacing existing signature
/Users/ag32547/Library/Developer/Xcode/DerivedData/Runner-ehsppxamrnwyncckggzztyutcqwg/Build/Products/Debug-iphonesimulator/Runner.app/Frameworks/Flutter.framework: Permission denied
Command PhaseScriptExecution failed with a nonzero exit code

I have no idea where I went wrong.
All I modified after taking the old project were:

*

*Changed the team and bundle identifier to a developer certified license to distribute the app.

*Updated some dependencies in flutter pubspec.yaml

If more information is needed I'm ready to provide it.
Any insight into this will be really helpful. Thank you.

A: The problem occured when I was setting up the firebase in the app. I changed the app in xcode editor while that was not necessary. Flutter takes care of it for you. So when running the commands it is important to add the commands in fluter.
I also deleted the Podfile.lock, pod files and .xcworkspace and ran pod install and upgrade from the terminal. And I also ran "flutter clean" and recompiled.


text:
Q: :after : z-index doesn't work I'd like to put the black rectangle (:after) behind the h2, but z-index doesn't work.
I have this code in html

Ce que tu auras peut-être un jour ou l'autre...

and this in CSS :
#general .page h2 {
position: relative;
text-indent: -9999px;
width: 718px;
margin-bottom: 50px;
height: 116px;
z-index: 10;
background: url(img/banniere-hi-04.png);
}

#general .page h2:after {
display: block;
content: "";
position: absolute;
top: -15px;
left: 658px;
width: 544px;
height: 72px;
z-index: -1;
background: black;
}

Here's the problem (here with a black rectangle) :
http://www.robinmastromarino.be/dataviz04/
Thank you for your help !

A: You need to give
 a relative position and a positive z-index, then remove the z-index on the
 as the pseudo-element creates a new stacking context
More info as to why

Example:

A: You cannot give a child node a lower z-index than it's parent.


text:
Q: Structure of GNU/Linux I have some basic knowledge about Linux OS like it consist of Kernel.The kernel is core of Linux , It manages all processes, device drivers, and I/O.But My Question is what Linux consists of beside Kernel , Binaries , Device Files  and Libs ?
Linux Distro's are Open Source so how do I compile whole distro myself ? Like Compiling Whole Arch Linux or Ubuntu Linux on my own then installing it on my computer ?

A:
Linux Distro's are Open Source so how do I compile whole distro myself ?

Compiling your own is an excellent way to learn what it consists of.  Fortunately, there are linux distributions that are designed to be compiled by end-users and it would be easier to start with one of those.  There is a list of such distributions here.  Gentoo is probably the most popular among them.

A: If you want to learn something about linux and how to setup a system from scratch I would recommend you LSF (Linux From Scratch). It is nothing more than a manual on "How to build your own linux". Even Arch Linux was build from this manual, if you check the history.

A: Compiling the whole shebang by yourself will only teach you how to stare at the screen. A Linux distribution is some 30 million lines of code, getting to grasp that is a job for more than a lifetime. Better select some part of it that particularly interests you, and get involved in it's development.


text:
Q: VSTS Build: Replacing token with build number I'm trying to update a web.config app setting called 'AppVersion' with the build number when building my application in VSTS.
Here are my build steps:

The 'Replace tokens' step converts any variables you set for your build and replaces the tokens you've set in your config files. This part works but what it won't do is get an environment variable like the build number and do a replace. It will just replace whatever text has been specified. Here's my build variables:

So after the build step is completed, my app setting is...
<add key="AppVersion" value="$(BuildNumber)" />
when it should be something like...
<add key="AppVersion" value="20160520.1" />
Can anyone point me in the right direction?
Many thanks.

A: I did something similar using the "Replace Tokens in **/*config" task.
To update the value for the key "AppVersion" with the current build number, your line should look like the following,
<add key="AppVersion" value="#{Build.BuildNumber}#" />

A: You can add a PowerShell script task before "Replace Token" task to pass the "BuildNumber" to "AppVersion" variable as following.

A: In VSTS, use $(Build.BuildNumber) as specified in this doc.
Note that you cannot use $(Build.BuildNumber) to set a variable's value, because it is taken literally; it should be an argument to the task. If your task does not accept it, you can replace with a little Powershell script and the BUILD_BUILDNUMBER environment variable.
param (
    [Parameter(Mandatory = $true)]
    [String]$fileWithTokens,

    [Parameter(Mandatory = $false)]
    [String]$tokenRegex = "__(\w+)__"
)

$vars = Get-ChildItem -path env:*
$contents = Get-Content -Path $fileWithTokens
$newContents = "";
$contents | % {
    $line = $_
    if ($_ -match $tokenRegex) {
        $setting = Get-ChildItem -path env:* | ? { $_.Name -eq $Matches[1]  }
        if ($setting) {
            Write-Host ("Replacing key {0} with value from environment" -f $setting.Name)
            $line = $_ -replace $tokenRegex, $setting.Value
        }
    }
    $newContents += $line + [Environment]::NewLine
}
Set-Content $fileWithTokens -Value $newContents

```
Source https://github.com/colindembovsky/cols-agent-tasks/tree/master/Tasks/ReplaceTokens

A: After a day of research, finally found/created a better option than using any random app (Replace Token) from Marketplace.
The option I am talking is already available in VSTS, Azure CLI task.
Here are the stpes:

*

*Add setting BUILD_NUMBER with initial value of 1.0 in appsettings.json

*Read appsettings.json in your app and display it. I am sure you all are smart enough to figure out how to use appsettings to display Build Number on your WebApplication.

*In Azure Portal, similarly create an App Setting named BUILD_NUMBER with initial value of 1.0 in Azure Application settings section under App Services for your App.

*In VSTS, In your Release definition, add a task Azure CLI.

*Populate required fields such as Azure Subscription, Script Location with Inline script and last but most important Inline Script with following CLI command

az webapp config appsettings set -n iCoreTestApi -g ArchitectsSandbox -s Dev --settings BUILD_NUMBER=$(Build.BuildNumber)
Command explanation:

*

*iCoreTestApi should be replaced by your real WebApp or Api name in Azure

*ArchitectsSandbox should be replaced by your resource group in Azure

*Dev is the slot name, you may or may not have it.

*Rest of the command remains same.

Once you will queue new build, after successful completion of the deployment, you can see app settings section on Azure is updated with new BUILD_NUMBER.
Let me know if you still have any question.


text:
Q: using auto_incr_id sequence in eclipse for oracle db Hello im a beginner for Oracle and Java Eclipse
i created a table which named as persons.
i have a sequence(persons_auto_incr) for my oracle db and it works fine when i want to insert a new data i use for example
"INSERT INTO PERSONS(id,name,surname,telephone) VALUES(persons_auto_incr.nextval,'John','Wayne','11111');

and it works fine with id:1 name:John ..... etc
but in eclipse i dont know how to add that auto_incr statement my code is like that it works fine except id
query.executeUpdate("INSERT INTO persons (id,name,surname,telephone) VALUES('"
        +newRecord.getName()
        +"','"
        +newRecord.getSurname()
        +"','"
        + ""+newRecord.getTelephone()+"')");

what should i write there for id column?In this program u get datas(name,sur,tel) from user and i wanna get auto id too for them.

A: you can try this:
query.executeUpdate("INSERT INTO persons (id,name,surname,telephone) VALUES(persons_auto_incr.nextval,'"
        +newRecord.getName()
        +"','"
        +newRecord.getSurname()
        +"','"
        + ""+newRecord.getTelephone()+"')");


text:
Q: Is it ok to use count($arr) in loop conditions I am wondering which way is better to use and why?
    $arr = array(); // some array
    for($i = 0; $i < count($arr); ++$i) {
        //some code
    }

or
    $arr = array(); // some array
    $cnt = count($arr);
    for($i = 0; $i < $cnt; ++$i) {
        //some code
    }

Thanks for your answer!

A: I think the biggest difference what you have to be aware of is in the first example if you modify the array.
As an example:
first:
<?php

    $arr = [1,2,3];
     for($i = 0; $i < count($arr); ++$i) {
                    //^^^^^^^^^^^ See here
        echo "x". "
";
        array_pop($arr);
    }

?>

Output:
x
x

Condition: $i < count($arr)
1. Iteration: 0 < 3  -> TRUE
2. Iteration: 1 < 2  -> TRUE
3. Iteration: 2 < 1  -> FALSE

second:
<?php

    $arr = [1,2,3];
    $c = count($arr);
     for($i = 0; $i < $c; ++$i) {
                    //^^ See here
        echo "x". "
";
        array_pop($arr);
    }

?>

Output:
x
x
x

Condition: $i < $c
1. Iteration: 0 < 3  -> TRUE
2. Iteration: 1 < 3  -> TRUE
3. Iteration: 2 < 3  -> TRUE
4. Iteration: 3 < 3  -> FALSE

So as you can see in the first example the loop runs 1 iteration less than the other one! Why? Because it checks the condition in every iteration, so when you modify the source array now in the for loop the count will be different in every iteration opposed to that in the second example you count the array before the loop and the variable won't change in the for loop.
Besides this I think it's more a personal preference what you choose. (And if you want the most efficient one go for the second one where you only call count() once)
And if you want to take a look at the generated opcode of both examples, then the biggest difference is, that the second one makes 1 operation more than the first one where you don't assign the return of count().
first:
number of ops:  11
compiled vars:  !0 = $arr, !1 = $i
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   3     0  >   INIT_ARRAY                                       ~0
         1      ASSIGN                                                   !0, ~0
   4     2      ASSIGN                                                   !1, 0
         3  >   SEND_VAR                                                 !0
         4      DO_FCALL                                      1  $3      'count'
         5      IS_SMALLER                                       ~4      !1, $3
         6    > JMPZNZ                                        9          ~4, ->10
         7  >   PRE_INC                                                  !1
         8    > JMP                                                      ->3
   6     9  > > JMP                                                      ->7
        10  > > RETURN                                                   1

second:
number of ops:  12
compiled vars:  !0 = $arr, !1 = $cnt, !2 = $i
line     # *  op                           fetch          ext  return  operands
---------------------------------------------------------------------------------
   3     0  >   INIT_ARRAY                                       ~0
         1      ASSIGN                                                   !0, ~0
   4     2      SEND_VAR                                                 !0
         3      DO_FCALL                                      1  $2      'count'
         4      ASSIGN                                                   !1, $2
   5     5      ASSIGN                                                   !2, 0
         6  >   IS_SMALLER                                       ~5      !2, !1
         7    > JMPZNZ                                        A          ~5, ->11
         8  >   PRE_INC                                                  !2
         9    > JMP                                                      ->6
   7    10  > > JMP                                                      ->8
        11  > > RETURN                                                   1

A: If you are not hunting for the last millisec runtime, the first example is the more typical one. But it does check the size of the array with each iteration again, hence it is a little slower. But the code is nicer to read. So the first one is programmer book compatible, while the second one is already optimized (probably too early ;)

A: count is function which called to calculate the number of element in array and you should not call a function repeatedly. if space is not issue then you should call this function one time and store returned value and then use that variable where you want.

*

*Know about Count


text:
Q: Doesn't navigate the url to Youtube channel in ios Ionic cordova I am trying to navigate youtube channel when we click on button in ios, but it was not working, it is perfectly working in android …
Below are the my reference
HTML file
<ion-button class="youtube_btn" (click)="openYoutube()">Our youtube channel</ionic-button>

TS file
import { DomSanitizer } from '@angular/platform-browser';

constructor( private sanitizer: DomSanitizer) {
this.getSafeUrl("https://www.youtube.com/embed/FSFTBf7frUs");
}
openYoutube(){
window.open('https://www.youtube.com/channel/UCp7eM4-x4K4AeSkiRHfxDbQ', '_system', 'location=yes');
}

getSafeUrl(url) {
this.url = this.sanitizer.bypassSecurityTrustResourceUrl(url);
}

A: In App Browser
ionic cordova plugin add cordova-plugin-inappbrowser
npm install @ionic-native/in-app-browser

App Availability
ionic cordova plugin add cordova-plugin-appavailability
npm install @ionic-native/app-availability

After installing both the Ionic native plugin we should enlist the InAppBrowser and AppAvailability provider with the principle application module.
After that add below code in app.module.ts
import { AppAvailability } from '@ionic-native/app-availability/ngx';
import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
import { Platform } from '@ionic/angular';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [],
  providers: [
    AppAvailability,
    InAppBrowser
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

After that import those two modules in your component Typescript file
import { AppAvailability } from '@ionic-native/app-availability/ngx';
import { InAppBrowser, InAppBrowserObject } from '@ionic-native/in-app-browser/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(
    public platform: Platform,
    private appAvailability: AppAvailability,
    private inAppBrowser: InAppBrowser) { }

  openYoutube() {
    let app;
    let channel = 'paste Url of your channel'
    if (this.platform.is('ios')) {
      app = 'youtube://';
    } else if (this.platform.is('android')) {
      app = 'com.google.android.youtube';
    } else {
      const browser: InAppBrowserObject = this.inAppBrowser.create('https://www.youtube.com/channel/' + channel, '_system');
      return;
    }

    this.appAvailability.check(app)
      .then(
        (yes: boolean) => {
          console.log(app + ' is available')
          // Success
          // App exists
          const browser: InAppBrowserObject = this.inAppBrowser.create('youtube://channel?id=' + channel, '_system');
        },
        (no: boolean) => {
          // Error
          // App does not exist
          // Open Web URL
          const browser: InAppBrowserObject = this.inAppBrowser.create('https://www.youtube.com/channel/' + channel, '_system');
        }
      );
  }
}


text:
Q: How to create progressbars with name from string? As the name implies I'm trying to create progress bars (at runtime). I need this because I have to display in a graphical manner how much, out of 100%, some elements have reached. The elements are extracted from a database and may vary in number so I can't make a fix number, I need a loop that creates the progressbars... I think.
Any way possible?

A: First Extract all the elements from Database............and then set the Extracted elements count to Progress bar.

A: You can do st. like this:
progressBar.Step = 1;
progressBar.Minimum = 0;
progressBar.Maximum =  elements.Count;

...

for (int index = 0; index < progressBar.Maximum; index++)
{
  // Do your work here ...

  progressBar.PerformStep();
}


text:
Q: Creating histograms with specified mean and intervals I have a set of data that I want to create a histogram for. The thing is, I would like to set the center of the histogram to the mean of the dataset and the intervals to be the standard deviation. How would I go about specifying this in Mathematica?
Just for the sake of it, this is my dataset and all I have in Mathematica so far:
Histogram[{0, 0, 0, 0, 80, 100, 120, 130, 130, 140, 140, 150, 150, 160, 170, 200, 220, 240, 350}]

A: Perhaps:
data = {0, 0, 0, 0, 80, 100, 120, 130, 130, 140, 140, 150, 150, 160, 170, 200, 220, 240, 350};
{mean, std} = Through@{Mean, StandardDeviation}@data;

You can specify the bin delimiters as an explicit list:
bins = {Table[mean + k std, {k , -5/2, 5/2, 1}]};

Histogram[data, bins, Epilog -> {PointSize[Large], Red, Point@{mean, 0}}]

Alternatively, you can use the form {xmin,xmax, dx} for bin specification:
bins2 = {mean - 5/2 std, mean + 5/2 std, std};
Histogram[data, bins2, Epilog -> {PointSize[Large], Red, Point@{mean, 0}}]
(* same picture *)

A: You can use this binning function to avoid having to recalculate the mean and standard deviation if the data changes, or manually decide on how many standard deviations to include.
binFunction[l_List] :=
 Module[{μ = Mean[l], σ = StandardDeviation[l]},
  Mean[l] - σ/2 + σ Range[Floor[Min[(l - μ)/σ]],
     Ceiling[Max[(l - μ)/σ]]]]

Example of usage:
data = RandomVariate[StudentTDistribution[Pi], 1000];
Histogram[data, binFunction, Epilog -> {Red, Point[{Mean[data], 0}]}]

If you always want the plot to have equal range on either side of the mean, regardless of the distribution shape, use this function instead:
binFunctionSymmetric[l_List] :=
 Module[{μ = Mean[l], σ = StandardDeviation[l]},
  Mean[l] - σ/2 + σ Range[-#, +#] &@
   Ceiling[Max[Abs[(l - μ)/σ]]]]


text:
Q: having trouble scraping links with beautiful soup Python student here, learning the basics of web scraping. Trying to pull the links from this bs4 element that I've scraped from a webpage.
house = committee[0].find_all("li")
house

Result:
[
Agriculture
,

Appropriations
,

Armed Services
,

Budget
,

Education and ... ]

So when I try to pull out the links I'm using list comprehension:
links_h = [link.get(" href")for link in house]
links_h

But instead of returning the links, it's returning this:
[None,
None,
None,
None,
None]

Not sure if I need to do something different because these are internal links... I'm just kind of lost. Any help is appreciated.

A: You have a list of li tags which have no href attribute - the href attribute is of the a tags, which are wrapped as list items.
You can either get the hrefs like this:
links_h = [link.find('a').get("href")for link in house if link.find('a')]

OR you can try getting the a tags directly as
house = committee[0].select("li > a")

so that the [link.get("href")for link in house] part works.


text:
Q: How Do I Select all Objects via a Relationship Model Given the Model:
class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)

class Thingie(models.Model):
    children = models.ManyToManyField('self', blank=True, symmetrical=False)

class Relation(models.Model):
    profile = models.ForeignKey(Profile)
    thingie = models.ForeignKey(Thingie)

How would one return a QuerySet containing all Profile instances related to a given Thingie?  That is, every Profile that has a foreign key pointing to it from a Relation and to the given thingie.
I know all about select_related(), and how I could use it to do this by iterating but i find iterating irritating (badoop bah!).  Also, values_list() has been looked at, but it doesn't quite do the right thing.
Please help!  Thanks!

A: Do you definitely need it to be a queryset? If you only need it to be an iterable, a simple expression for your purposes is:
profiles = [r.profile for r in thingie.relation_set.all()]

I'm not sure if a list comprehension counts as irritating iterating, but to me this is a perfectly intuitive, pythonic approach. Of course if you need it to be a queryset, you're going to do something messier with two queries, eg:
relation_values = thingie.relation_set.all().values_list('pk', flat=True)
profiles = Profile.objects.filter(relation__in=relation_values)

See the "in" documentation for more. I prefer the first approach, if you don't need a queryset. Oh and if you only want distinct profiles you can just take set(profiles) in the first approach or use the distinct() queryset method in the second approach.

A: Did you read the Django doc on Making queries?  It has a simple example of achieving what you want, more specifically Lookups that span relationships.  Make sure you refer the code snippets in the latter link to the model code at the beginning of the page.

A: Without defining a direct relationship between Profile and Thingie, you can't.
The best way would be to add a ManyToMany to Thingie that points to Profile and use the through argument (django docs) on the ManyToMany to specify your Relation model/table.
That way you can do a direct filter operation on Thingie to get your profiles and still store your intermediate Relation data.


text:
Q: Finding Matrix of Projection
Let $P:R4→R4$ be the orthogonal projection onto the plane
$ W={−(y+2z+t)=0}$
(That is, the projection parallel to the normal vector $(0,−1,−2,−1)$.)
Find the matrix $M^{E}_{E} (P)$ of the projection $P$ relative to the standard
  basis of $R4$.
$M^{E}_{E} (P)$ = ...

So, I'm kinda new to the topic and confused about this and don't know how to do it. Can someone help me with this.

A: The simplest way to compute this matrix is to consider how you would normally compute this projection. Let $v$ denote the normal vector $v = (0,-1,-2,-1)$.  For a vector $x$, the projection onto the orthogonal complement $W^\perp$ of the hyperplane is given by
$$
\operatorname{proj}_{v}(x) = \frac{v^Tx}{v^Tv}\cdot v.
$$
So, the projection of $x$ onto $W$ is given by $x - \operatorname{proj}_{v}(x)$. Our goal is to produce a matrix $P$ for which
$$
Px = x - \operatorname{proj}_{v}(x) = x - \frac{v^Tx}{v^Tv}\cdot v.
$$
A nice way to find this matrix $P$ is to factor the right-hand side into the form $Mx$ for some matrix $M$. In particular, note that
$$
x - \frac{v^Tx}{v^Tv}\cdot v = x - \frac 1{v^Tv}v\cdot v^Tx = x - \frac 1{v^Tv}vv^T x = \left(I - \frac{vv^T}{v^Tv} \right)x,
$$
where $I$ dentoes the identity matrix. So, our matrix $P$ should be given by $P = I - \frac{vv^T}{v^Tv}.$ If you compute this correctly, you should end up with the answer
$$
P = \pmatrix{1 & 0 & 0 & 0\\ 0 & \frac{5}{6} & -\frac{1}{3} & -\frac{1}{6}\\ 0 & -\frac{1}{3} & \frac{1}{3} & -\frac{1}{3}\\ 0 & -\frac{1}{6} & -\frac{1}{3} & \frac{5}{6}}.
$$


text:
Q: Python IDLE 3.3.2 "expected an indent block" error My first Python code.
So, I just started coding about 45 minutes ago, and after trying to resolve this issue myself I decided to ask for some help. Please feel free to leave some constructive criticism about weather my code is sloppy, erratic, etc. I'm much better a Lua than I am at Python. The issue I've been having in the IDLE Python GUI is that when I hit F5 to run it in the Python Shell, It gives me an error saying "expected an indent block", but doesn't tell me where to place the indent block(s). I thought to start with something simple so I went with coding a working "Age calculator", Here's the code:
# Importing necessary modules #

import time
import math

# Start Application #

print ("The age calculator!")
time.sleep(1)
print ("May I collect some information about you?")
yn = (input("Yes or No: "))

# if-elif Based Decisions #

if yn != Yes or No:
    ynInvalid()

elif yn == No:
    exit()

elif yn == Yes:
    ynYes()

elif yn != Yes or No:
    ynInvalid()

#Defining Functions#

def PrintInfo():
    print ("Hello", name, "Nice to meet you!")

def AgeCheck():
    if age <= 0:
    print("Invalid Age!")
    elif age > 0:
    days = age * 365
    minutes = age * 525948
    seconds = age *  31556926
    print("Doing some math please wait...")
    time.sleep(4)
    print(name,"you been alive for", days,"days", minutes, "minutes and", seconds, "seconds, Wow you're really old!")

def ynYes():

    time.sleep(2)
    print (" Please enter your name below.")
    time.sleep(1)
    name = input("Name: ")
    time.sleep(1)
    PrintInfo()
    age = int(input("Age: "))
    AgeCheck()

def ynYesRetry():

    age = int(input("Age: "))
    AgeCheck()

def ynInvalid():
    print("Invalid Argument! Please try Again!")
    ynYesRetry()

A: IDLE never just gives you an error without showing you where the error occurred. If you post the complete traceback, people can figure out what it means, explain it to you, and hopefully explain how you can do it yourself next time.
Also, copying and pasting the actual error, instead of paraphrasing it, makes it much easier for people to debug your problem.
In this case, it's pretty obvious from a quick glance where you've got at least one indentation error:
def AgeCheck():
    if age <= 0:
    print("Invalid Age!")

The body of an if statement has to be indented further than the condition part.
More generally, anything that ends with a : is always followed by an indented block.
You may have additional indentation errors; this one may not even be the one that IDLE is telling you about. But hopefully this is enough information to find and fix them all yourself.

A: if age <= 0:
print("Invalid Age!")
elif age > 0:
days = age * 365

You did not indent this properly.
if age <= 0:
    print("Invalid Age!")
elif age > 0:
    days = age * 365

A: AgeCheck should be:
def AgeCheck():
    if age <= 0:
        print("Invalid Age!")
    elif age > 0:
        days = age * 365
        minutes = age * 525948
        seconds = age *  31556926
        print("Doing some math please wait...")
        time.sleep(4)
        print(name,"you been alive for", days,"days", minutes, "minutes and", seconds, "seconds, Wow you're really old!")

You need to indent after all if and elif statements. That is how Python knows what is included in the statement results.


text:
Q: Finite solvable subgroup in $GL_2(\mathbb{C})$ which is not contained in Borel subgroup What is the example of finite solvable subgroup in $GL_2(\mathbb{C})$ which is not contained in any Borel subgroup?

A: You have the standard embedding of $Q_8\to GL_2(\mathbb{C})$ given by the action of the standard basis on $\mathbb{H}=\mathbb{C}^2$. More expliticly, these are given by the Pauli matrices. These cannot be put into an upper triangular form. This is exactly what you want, since all Borel groups are conjugate, and the cannonical one is the upper triangular matrices, so we are asking if we can put all the Quaterions in diagonal form. I recall the presentation $\langle l, n_i; i\le 3|n_i^2=n_1n_2n_3=l, l^2=1\rangle$. The condition $l^2=1$, and $l\neq 1$, implies that $l=-I$ or $l_{11}=-l_{22}$, and $l_{ii}^2=1$. Regardless, this means that either $l_{11}=-1$ or $l_{22}=-1$, denoted $h$. The relations $n_i^2=l$ them implies $n_{i, h,h}^2=-1$. But $n_{1, h,h}n_{2, h,h}n_{3, h,h}=(n_1n_2n_3)_{h,h}=l_{h,h}=-1$. This is impossible, since $n_{i,h,h}=\pm i$. There is probably a better way to do this. Oh, and this is solvable by Burnside lemma or $0\to \mathbb{Z}/(2)\to Q_{8}\to \mathbb{Z}/(4)\to 0$.


text:
Q: Solving a system of 4 equations to 4 unknowns without working on a 4th degree polynomial in one of the unknowns May you solve this very interesting system of equations for me?
$d+a=-4$
$ad+b=0$
$bd+c=0$
$cd=3$
Simply replacing ends up in quartic equation, for example for $d^4+4d^3+3=0$.
But I want a more intelligent solution!!!
May you please find for me a trick to reduce the system's equation into a cubic equation, for example $x^3+ax^2+bx+c=0$ where $x$ is a new variable related to the starting system? ( please not $d^3+3d^2-3d+3=0$).
This solution is the solution I seek for.
Thank you a lot for your time!

A: It's not entirely clear what you want. However, it's fairly straightforward to eliminate variables in any way you like.
Eliminating $a$, then $b$, then $c$ gives your quartic in $d$, which factors as
$$(d + 1) (d^2 + 3 d^2 - 2 d + 3) = 0 \tag{1}$$
... but you don't want that. Well, eliminating $a$, $b$, $d$ gives
$$(c + 3) (c^3 - 3 c^2 + 9 c + 9) = 0 \tag{2}$$
Better? If not, then $a$, $c$, $d$ gives
$$(b + 3) (b^3 - 3 b^2 + 15 b + 3) = 0 \tag{3}$$
Or perhaps $d$, $b$, $c$, which yields
$$(a+3) (a^3+9a^2+21 a + 1) = 0 \tag{4}$$
As it happens,
$$a=b = c=-3 \qquad d = -1$$
is a solution to the system. Letting Mathematica solve the system, it looks like each of the roots of the cubics contributes to a solution; the exact expressions are messy, but the decimal forms are as follows:
$$a = -0.0486\ldots \quad b = -0.1921\ldots \quad c = -0.7592\ldots \quad d = -3.9513\ldots \\[8pt]
a = -4.4756\ldots \pm i\;0.7300\ldots \quad b = 1.5960\ldots \mp i\;3.6146\ldots \\ c = \phantom{-}1.8796\ldots \pm i\;2.8846\ldots  \quad d = 0.4756\ldots \mp i\;0.7300\ldots $$


text:
Q: Alarm Manager using Broadcast receiver I am creating an android app to set alarm using broadcast receiver. Its working fine when the app is open but when I closed the app completely then there is no notification generated. How to resolve this issue?
Broadcast Receiver class
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {

    System.out.println("Alarm Fired");
    MediaPlayer mediaPlayer = MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
    mediaPlayer.start();
    Toast.makeText(context,"ALarm fired",Toast.LENGTH_SHORT).show();
} }

Main Activity class
public class MainActivity extends AppCompatActivity {

//the timepicker object
TimePicker timePicker;

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

    //getting the timepicker object
    timePicker = (TimePicker) findViewById(R.id.alarmTimePicker);

    //attaching clicklistener on button
    findViewById(R.id.buttonAlarm).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //We need a calendar object to get the specified time in millis
            //as the alarm manager method takes time in millis to setup the alarm
            Calendar calendar = Calendar.getInstance();

            if (android.os.Build.VERSION.SDK_INT >= 23) {
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH),
                        timePicker.getHour(), timePicker.getMinute(), 0);
            } else {
                calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH),
                        timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
            }

            setAlarm(calendar.getTimeInMillis());
        }
    });
}

private void setAlarm(long time) {
    //getting the alarm manager
    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //creating a new intent specifying the broadcast receiver
    Intent i = new Intent(this, MyBroadcastReceiver.class);

    //creating a pending intent using the intent
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

    //setting the repeating alarm that will be fired every day
    am.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pi);
    Toast.makeText(this, "Alarm is set", Toast.LENGTH_SHORT).show();
}  }

AndroidManifest.xml
    <receiver
        android:name=".MyBroadcastReceiver"
        android:enabled="true">

    </receiver>


text:
Q: c curses loop is stuck I'm working on a snake game in c curses and this part of code will be the foundation of the game, but it seems somehow stuck, the box shows up and there is only a single # in it when realistically there should be a lot more since I commented the delay.
    WINDOW *game_win = newwin(height, width, ym/4 - height/4, xm/4 - width/4);
    box(game_win, 0, 0);
    mvwprintw(game_win, height/2, width/2, "#");
    wrefresh(game_win);
    noecho();
    nodelay(game_win, TRUE);

    int position[] = {height / 2, width / 2};
    int direction = KEY_RIGHT;
    //clock_t delay;
    while(1){
        //delay = clock();
        //while(clock() < delay + 100000){
            direction = wgetch(game_win);
        //}

        if(direction == KEY_UP) position[0]++;
        if(direction == KEY_DOWN) position[0]--;
        if(direction == KEY_RIGHT) position[1]++;
        if(direction == KEY_LEFT) position[1]--;

        mvwprintw(game_win, position[0], position[1], "#");
        wrefresh(game_win);
    }

I thought that the wgetch() was pausing the program so I added nodelay, also tried some clearing and redrawing the whole thing but that didn't help either. At this point I really only need this to cycle infinitely with the user having one second to pick a direction until the snake moves (in this case im not erasing the previous position so instead of moving it just get's longer in the given direction).


text:
Q: Will hql give you compile time errors? Will hql give you compile time errors like criteria query?
I remember hearing that one of the methods doesn't (besides raw SQL).

A: The short answer is no.  Since HQL is essentially a string, you need an IDE to parse it and figure out if you're doing something wrong.

A: No query build in Hibernate, neither HQLs nor Critieras, will produce compile time errors. Nevertheless you can use the NamedQuery annotation to declare your static HQL queries in a static way. This will provide caching and validity checks when starting your application because hibernate's session factory will read all NamedQueries on first startup.

A: HQL wil not give you compile time errors, as it is only treated as a string at compile time.
What do you mean with 'like criteria query'?

A: Criteria queries may not give you compile time errors, something like this will error
ICriteria crit = sess.CreateCriteria(typeof(Cat));
crit.SetMaxResults("50"); /* wrong parameter type */
List cats = crit.List();

Something like this will not
IList cats = sess.CreateCriteria(typeof(Cat))
.Add( Expression.Like("Naem", "Fritz%") ) /* misspelled property */
.Add( Expression.Between("Weight", minWeight, maxWeight) )
.List();


text:
Q: SSRS saved data source prompting for credentials I have a shared data source in SSRS (SQL 2016) that has Windows credentials saved. I can click on that data source, test connection, and it works fine. However, when I attempt to use that data source in a new report it prompts me for credentials anyway.
If you look at the image below, you'll see the prompt window I'm referring to. If I click Test Connection on that screen it works too so I don't understand the issue!
SSRS prompting for credentials during report creation / modify

A: This behavior is correct. The stored credentials are for use by the server, not Report Designer.


text:
Q: jquery adding and subtracting values while clicking on radio buttons I am trying to add and subtract values when the user clicks on the radio button. All the radio buttons are dynamically created from database values.
There maybe multiple categories inside one heading but user will be able to choose only one. I am stuck in subtracting the value when the user selects another option.
If you are kind enough ;), you can check this pasting in your editor (oh yeah.. I am a total newbie when it comes to programming.)
Any solution or different approach will be much much much appreciated.
Thanks...
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

  You can select or deselect the radio button

Heading1

      Name
      Location
      #days
      Price

      <input name=cat1 value=3 id=3 type='radio' class='v'/>
      categeory 1
      location1
      5
      100

Heading2

      Name
      Location
      #days
      Price

      <input name=cat2 value=1 id=1 type='radio' class='v'/>
      category2
      location2
      4
      200

      <input name=cat2 value=2 id=2 type='radio' class='v'/>
      category2
      location3
      8
      150

1800

A: You were pretty close! I modified your code slightly and cleaned some things up, but you were almost there:
$(document).ready(function() {
    $("input[type='radio']").mousedown(function(e) {
        var self = this;
        /* Use 'checked' property instead of wrapping in jQuery object */
        if (self.checked) {
            /* Use setTimeout with a function instead of JS string */
            setTimeout(function() {
                self.checked = false;
            }, 200);
        }
        else {
            return true;
        }
    });
    /* Assign click handler inside document.ready: */
    $(".v").click(function() {
        /* Cache selectors that are used over and over: */
        var $this = $(this);
        var $grandTotalContainer = $(".grandTotal");

        /* Call parseInt with radix parameter: */
        var grandTotal = parseInt($grandTotalContainer.text(), 10);
        var price =
            parseInt($this.closest('tr').find(".price1").text(), 10);
        var siblingAmounts = 0;
        var name = $this.attr("name");

        /* Find prices of items in the same "group": */
        $("input[name='" + name + "'].active")
            .not($this)
            .each(function() {
                siblingAmounts +=
                    parseInt($(this).closest("tr").find(".price1").text(), 10);
            });

        $this.toggleClass("active");
        $("input[name='" + name + "']").not($this).removeClass("active");

        if ($this.hasClass("active")) {
            grandTotal -= siblingAmounts;
            grandTotal += price;
        }
        else {
            grandTotal -= price;
        }
        $grandTotalContainer.html(grandTotal);
    });
});

Notes:

*

*Calling setInterval with a JavaScript string instead of a function is considered bad practice because it calls eval() which can cause problems.

*Directly accessing DOM element properties where it works is preferrable to wrapping this in a jQuery object and using jQuery methods to access those properties.

*Calling parseInt with the radix parameter is highly recommended because otherwise JavaScript tries to assume the radix.

*I removed the code that worked with a default grand total and just parsed out the value inside the grand total div.

*I select siblings of the clicked input using the attribute equals selector

*Make sure and cache jQuery results that you use over and over.  There's overhead to executing jQuery functions that you can avoid if you cache the results of queries.

*You shouldn't use integers as ids for HTML elements, as they're invalid under the HTML 4.01 specification.

Here's a working example: http://jsfiddle.net/andrewwhitaker/8Atf8/1/
Hope that helps!


text:
Q: limit of a function with competing terms I am trying to solve the following problem:
$\lim_{a \to \infty} y(a)$, where $ y(a)=\int_{0}^{\theta(a)} \dfrac{f(\lambda)}{(a-\lambda)^2}d\lambda$, and $\theta(a)$ is a linearly increasing function which is less than $a$.
By plotting it, I can see that $y(a)$ converges to zero as $a$ increases, however, I do not know how to show it analytically.
Can I say that as $a$ increases the upper limit of integral increases linearly and at the same time the denominator of the integrant increases quadratically. So, when $a$ is large enough, $O(\frac{1}{a^2})$ overtakes $O(a)$ and $y$ approaches to zero?
Thank you for your help.


text:
Q: App not printing text after connecting to bluetooth device (Swift) I'm currently trying to make an app that connects to a bluetooth device and once done prints out the
I'm having the problem once it connects it doesn't print out the services and instead prints out "while delegate is either nil or does not implement peripheral:didDiscoverServices:". But the problem is that I do have didDiscoverServices.
Here is my viewcontroller
import UIKit
import CoreBluetooth

let rowerServiceCBUUID = CBUUID(string: "CE060000-43E5-11E4-916C-0800200C9A66")

class HRMViewController: UIViewController {

  @IBOutlet weak var heartRateLabel: UILabel!
  @IBOutlet weak var bodySensorLocationLabel: UILabel!
  var centralManager: CBCentralManager!
  var pmPeripheral: CBPeripheral!
  override func viewDidLoad() {
    super.viewDidLoad()
    centralManager = CBCentralManager(delegate: self, queue: nil)
    // Make the digits monospaces to avoid shifting when the numbers change
    heartRateLabel.font = UIFont.monospacedDigitSystemFont(ofSize: heartRateLabel.font!.pointSize, weight: .regular)
  }

  func onHeartRateReceived(_ heartRate: Int) {
    heartRateLabel.text = String(heartRate)
    print("BPM: \(heartRate)")
  }
}
extension HRMViewController: CBCentralManagerDelegate {
  func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .unknown:
      print("central.state is .unknown")
    case .resetting:
      print("central.state is .resetting")
    case .unsupported:
      print("central.state is .unsupported")
    case .unauthorized:
      print("central.state is .unauthorized")
    case .poweredOff:
      print("central.state is .poweredOff")
    case .poweredOn:
      print("central.state is .poweredOn")
      centralManager.scanForPeripherals(withServices: [rowerServiceCBUUID])
    @unknown default: break

    }
  }

  func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    print(peripheral)
    pmPeripheral = peripheral
    centralManager.stopScan()
    centralManager.connect(pmPeripheral!)
  }
  func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    print("Connected!")
    pmPeripheral.discoverServices(nil)
  }
}
extension HRMViewController: CBPeripheralDelegate {
  func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    guard let services = peripheral.services else { return }

    for service in services {
      print(service)
      pmPeripheral.delegate = self
    }
  }
}

Does anyone know what I should do? Thanks.

A: Although you set your central manager's delegate, you have not set the peripheral's delegate. In centralManager(_,didDiscover,advertisementData), add:
pmPeripheral.delegate = self

That should resolve your warning and the delegate method will be called.


text:
Q: What are some potential issues to updating Java 7 to Unlimited Strength Jurisdiction Policy? I am implementing a cloud solution for an extension to my companies automated call system. To do so, I need to encrypt the user data that is communicated between our on premises database and Amazon Web Service. I have implemented AES encryption on both sides but found that our Cisco JRE is running Java 7 and requires that I update our JRE to allow Unlimited Strength Cryptography.
My solution was found here: Java Security: Illegal key size or default parameters?
Based off of my research, I do not foresee any problems updating this policy as this is essentially removing a "MAX_LENGTH" global variable. But as this is my first time delving into this type of java development I want to double check. Are there any considerations or potential issues that I may encounter when updating our Java 7 JRE security policy to Unlimited Strength Cryptography?

A: Andreas @https://stackoverflow.com/users/5221149/andreas is correct.
It is only a legal issue in the first part. Not all encryption methods/chipers are legal worldwide. Some countries do not allow the distribution of software with strong-encryption because of reasons. (most times a political decision between: security and control v.s. privacy)
Please make sure you don't distribute strong-encryption software to these countries and violate their law.
I would say: Unless you are developing cryptographic algorithms yourself or debug these you won't see any difference in your programm's behaviour.
In my experience the JCE Unlimited Strength Cryptography is needed most times if you have server-client communications with a webserver that supports only "strong" TLS/SSL ciphers. (a webserver admin can define the supported SSL/TLS ciphers, it is good practice to keep multiple options to get nearly 99% of the clients, however it depends on the provided webservice and how secure and up-to-date you want your SSL/TLS connections)
The JCE Unlimited Strength Cryptography policy files for java8 oracle can be found here: https://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
for java7 oracle use this one instead: https://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
PS: from java9 oracle the JCE Unlimited Strength Cryptography policy files will be shipped and enabled by default.
For all openJDK java versions they are enabled by default as well. See here https://github.com/open-eid/cdoc4j/wiki/Enabling-Unlimited-Strength-Jurisdiction-Policy


text:
Q: Insert non-breaking space in [R]Markdown math expression for HTML output I am writing scientific reports in bookdown and I would like to use non-breaking spaces as thousands separators follwoing the SI/ISO 31-0 standard.
Actually, I would prefer the non-breaking thin space (U+202F/ ) but for simplicty let's consider U+00A0/  for here.
I setup a knitr hook to do this on the fly:
knitr::knit_hooks$set(inline=function(output)
                               ifelse(is.numeric(output),
                                      prettyNum(round(output, 1),
                                                big.mark=' '),
                                      output))

This works as intended as long as I don't use any inline R-expressions returning numerical output > 999 within math expressions.
The following bookdown MWE illustrates the problem:
---
output:
  bookdown::html_document2: default
---
```{r set-output-hook, include=FALSE}
knitr::knit_hooks$set(inline=function(output)
                               ifelse(is.numeric(output),
                                      prettyNum(round(output, 1),
                                                big.mark=' '),
                                      output))
```

This works:
The product of $\pi$ and `r 1000` is `r pi*1000`.

This fails to render:
$\pi\cdot`r 1000`=`r pi*1000`$

This renders but is cumbersome as it requires me to know *a priori* which
values might exceed 999:
$\pi\cdot1000=`r as.character(round(pi*1000, 1))`$

I tried to track it down and came up with the following rmarkdown MWE:
---
output:
  rmarkdown::html_document:
    keep_md: true
---

| Rmarkdown    | Render     | HTML                                                | Markdown     |
|--------------|------------|-----------------------------------------------------|--------------|
| `1000`       | 1000       |`1000`                                               | `1000`       |
|`$1000$`      |$1000$      |`<span class="math inline">\(1000\)</span>`          |`$1000$`      |
|              |            |                                                     |              |
|  `100,0`     | 100,0      |`100,0`                                              | `100,0`      |
|`$100,0$`     |$100,0$     |`<span class="math inline">\(100,0\)</span>`         |`$100,0$`     |
|              |            |                                                     |              |
|  `100 0`     | 100 0      |`100 0`                                              | `100 0`      |
|`$100 0$`     |$100 0$     |`<span class="math inline">\(100 0\)</span>`         |`$100 0$`     |
|              |            |                                                     |              |
|  `100 0`| 100 0 |`100 0`                                              | `100 0` |
|`$100 0$`|$100 0$|`<span class="math inline">\(100&nbsp;0\)</span>`|`$100 0$`|

The first two columns of the table are sufficient to see the problem:
Each pair of rows shows the number 1000 1 000) in text and math context; without any space, with a comma, with a simple space, and with a non-breaking space as thousands separator.
The latter fails to render in math context.
To track down the problem, I inspected the resulting HTML and Markdown (keep_md: true) output and added the corresponding code as columns three and four for a better overview what's going on.
For clarity, here is an adjusted version of the above rmarkdown MWE replacing simple spaces by _ and non-breaking spaces by - in the HTML and Markdown output columns:
---
output:
  rmarkdown::html_document:
    keep_md: true
---

| Rmarkdown    | Render     | HTML                                                | Markdown     |
|--------------|------------|-----------------------------------------------------|--------------|
| `1000`       | 1000       |`1000`                                               | `1000`       |
|`$1000$`      |$1000$      |`<span_class="math_inline">\(1000\)</span>`          |`$1000$`      |
|              |            |                                                     |              |
|  `100,0`     | 100,0      |`100,0`                                              | `100,0`      |
|`$100,0$`     |$100,0$     |`<span_class="math_inline">\(100,0\)</span>`         |`$100,0$`     |
|              |            |                                                     |              |
|  `100 0`     | 100 0      |`100_0`                                              | `100_0`      |
|`$100 0$`     |$100 0$     |`<span_class="math_inline">\(100_0\)</span>`         |`$100_0$`     |
|              |            |                                                     |              |
|  `100 0`| 100 0 |`100-0`                                              | `100 0` |
|`$100 0$`|$100 0$|`<span_class="math_inline">\(100&nbsp;0\)</span>`|`$100 0$`|

So from what I can tell

*

*This is not a bookdown issue as it can be reproduced by plain rmarkdown.

*

*I'm just mentioning bookdown as I would be happy with a bookdown-specific work-around.

*This is not an rmarkdown issue, as the generated Markdown looks exactly as I would expect it to look like.

*

*I'm just mentioning rmarkdown as I would be happy with an rmarkdown-specific work-around.

*This is not a MathJax issue, as the HTML code has the plain & replaced by & and I would not expect that to render properly.

*

*Anyways,I would be happy with an MathJax-related work-around.

*I suspect it's pandoc that replaces & by & in code and math context but not in text context.

*

*I'm sure if there is a way to convince pandoc not to do this, it will be easy to configure this through the rmarkdown YAML header.

Any idea on how to get the   transferred literally from Markdown to HTML in math context would probably help me to figure out the rest.

Addendum:
As pointed out by @tarleb, $100 0$ is not valid Latex.
However, modifiying the HTML manually to contain \(100 0\) works just fine as MathJax treats non-breaking spaces as spaces.
As I am not concerned about PDF output via LaTex, this means simply not converting $100 0$ to \(100&nbsp;0\) but to \(100 0\) (just as 100 0 is not converted to 100&nbsp;0 either) when converting the Markdown to HTML would be all that I need.

A: Pandoc expects math environments to contain LaTeX math markup, not HTML. Conversion fails as pandoc tries to output $100 000$ as LaTeX, but that gives \(100&nbsp;000\) instead of what you intended.
As a solution, you could try to use the literal narrow no-break space unicode character " " in your hook.
Alternatively, one could use a pandoc lua filter (or possibly a R pandoc-filter) to force pandoc to pass-through math content unaltered:
-- filename: force plain math
function Math (el)
  if el.mathtype == 'DisplayMath' then
    return pandoc.RawInline('html', '\\[' .. el.text .. '\\]')
  else -- InlineMath
    return pandoc.RawInline('html', '\\(' .. el.text .. '\\)')
  end
end

Save to a file and use it by adding
output:
  bookdown::html_document2:
    pandoc_args: --lua-filter=force-plain-math.lua

to your document.


text:
Q: Visual Studio VB Update requires a valid UpdateCommand when passed DataRow collection with modified rows I have button update and the code
Private Sub txtSave_Click(sender As Object, e As EventArgs) Handles txtSave.Click
        Me.Validate()
        Me.TrackingBindingSource.EndEdit()
        Me.TableAdapterManager.UpdateAll(Me.InventoryDataSet)
        MsgBox("Record Update")
End Sub

When run, I got error
System.InvalidOperationException: 'Update requires a valid UpdateCommand when passed DataRow collection with modified rows.'

Not sure do I miss something for update records. Thank you

A: When you create a typed DataSet from a database, the wizard generates a DataTable and a table adapter for each database table. The DataTable schema is based on the table schema, as is the SQL in the commands of the table adapter.
The SelectCommand contains a SELECT statement that will retrieve all columns of all rows and is executed when you call Fill. The InsertCommand, UpdateCommand and DeleteCommand contain INSERT, UPDATE and DELETE statements respectively and are executed as required when you call Update.
The SelectCommand and InsertCommand can always be generated because all they need to know is the name and data type of each column. UPDATE and DELETE statements need to be able to identify the specific record to update or delete and they do that by specifying the primary key value in the WHERE clause. If your database table has no primary key then that SQL cannot be generated and your table adapter will have no UpdateCommand or DeleteCommand.
What you need to do is to make sure that all your database tables have a primary key. It can be valid to have a table without a PK but it is very rare. Once your table has a PK, you can re-run the Data Source wizard to update your typed DataSet. There is a button on the toolbar in the Data Sources window to do that.


text:
Q: Laravel Beanstalkd job cannot connect to remote server via ssh I've got a workflow in my web application that looks like this (Built in Laravel 4):
1) User uploads a file (up to 50mb or so)
2) File is moved to temp directory
3) Queued job created that does the following:
 - Uploads file to amazon s3
 - SSH into another file processing server and transfers the file to a folder there.
 - Delete the temporary file
To connect to the remote server and upload the file within the queued job, I'm using:
SSH::into('processing')->put($localPath, $remotePath);

Everything works fine when I queue this job using the 'sync' driver, so I know the environment and permissions are correct.  The problem is, when I switch over to beanstalkd as my queue driver, the job fails with the following:
[2015-01-09 14:15:40] production.ERROR: exception 'RuntimeException' with message 'Unable to connect to remote server.'

Beanstalkd jobs run fine elsewhere in the application (none of the others have ssh commands).
I'm using a username and password for the connection, so it's not a key permissions or passphrase issue.  Any ideas?

A: If you know the file has uploaded OK to S3, why not generate a new job, that will then be run on the other file processing server (step 3b), to have it download the file from S3, if it needs it?
Other than that - you would need more debugging on the SSH upload.


text:
Q: Virtualisation management: should Vcenter, Veeam etc be on a physical machine or VM? I've noticed that a lot of people run vCenter Server on a VM hosted on Vsphere / ESXi.  This seems odd to me, because if there is an issue with the host then you will lose both the host and the management capabilities to switch hosts etc.
Should I provision a physical machine (eg. Microserver) to run VM management tools such as vCenter and Veeam or run them from a VM?  What is best practice here?
EDIT: - I work in a SMB environment and almost exclusively use the VMware Essentials packs, so no more than 5 or so hosts, so setting up some sort of redundant or clustered vcenter setup is pretty much unrealistic

A: We have over 100 separate vCenters and every one of them is a VM, it means we get all the usual virtualisation benefits and because we run them on a specific management cluster in the event of one crashing or whatever we can just connect directly to the host they're running on and restart or whatever as needed. We're something like the 4th or 5th biggest VMWare customer and we wouldn't consider using a physical for this, especially a bottom-end box like you've suggested.

A: VMware best practice now is to install vCenter on a VM with HA. That's from a VMware training class when 5 originally came out. HA doesn't require vCenter to actually be working once set up, as the hosts know what to do.
I have Essentials Plus, use this setup, and can attest that it works well for us. Just make sure that you have enough capacity on your hosts to accommodate HA.

A: actually,
most of the time, management tools are also virtualised,
basically because they don't need enough resources that would advise to use a physical server.
virtualized these tools can also benefit from HA/FT/DRS (in vmware environment) .
so my answer would be no, you don't have to provide a physical server for these management tools.

A: We use Essentials Plus and also run our vCenter in a VM.  Your concerns about clustering the thing that sets up the clustering have been covered in other answers and comments.  We take a couple of additional precautions to ensure recoverability of the environment:

*

*Run an out-of-band path to the same management VLAN so that we have alternative access to the cluster hosts if the primary path becomes unavailable.  In our case we run fully virtualised routing (quick plug for VyOS), so we just run an ESXi free or essentials host (depending on the licenses available) with just enough virtual routers to allow us to get into the other ESXi servers.
We use OSPF as our IGP, so the routers on the out-of-band host are set with slightly higher interface costs (lower bandwidth) than their production counterparts so that they can be kept running all the time but do not serve production traffic unless there is a cluster outage.

*Keep an old laptop (whose battery lasts longer than 10 minutes!) in the server room or data centre kit with vSphere console installed and ready to go so that we can plug into the management VLAN and manage the individual servers of need be.  This rarely gets used because of the aforementioned out-of-band host.


text:
Q: Snort pcap_inject not located I try to experiment the Intrusion Detection System(IDS) using Snort,I installed Snort and WinPcap packages after that I copy the Rules file and paste it to "C:\Snort\rules" next I try to copy the "snort.conf" to "C:\Snort\etc" but it already exists, then I start to execute using snort -dev i 3 it shows a alert message The procedure entry point pcap_inject could not be located in the dynamic link library C:\Snort\bin\snort.exe.
Picture of this problem:

A: On Windows 10, winpcap is no longer supported. There is a compatible alternative npcap: https://nmap.org/npcap/#download
When installing npcap, use the latest version (now it's 1.5) and make sure you install npcap with the compatible API option in the installer enabled.
It works fine with Snort 2.9.18.

A: You should use snortrules_snapshort version same with installed version
Example: Snort_2_9_8_3_Installer.exe with snortrules-snapshot-2983.tar.gz

A: If you are using winpcap then try it using npcap , which you can download from nmap.org

A: Libpcap originally had no functions that could transmit packets.
WinPcap added the pcap_sendpacket() function.
OpenBSD added the pcap_inject() function.
At some point, both of those were added to libpcap, for compatibility with both WinPcap and OpenBSD's libpcap.  They're both supported on Linux/*BSD/Solaris/Windows at minimum.
WinPcap picked up a version of libpcap that had pcap_inject(), but this is Windows, where functions in a DLL are not made available to users of the DLL by default; they have to be explicitly marked as available (exported).  The WinPcap developers did not mark pcap_inject() as available, so programs that use it won't work with WinPcap.
Snort apparently chose to use pcap_inject() rather than pcap_sendpacket(); there's no good reason to choose one or the other.
Libpcap later went with a different scheme for indicating whether a function is available or not; it defaults to "only functions explicitly marked as available are" on both UN*X and windows, and both pcap_inject() and pcap_sendpacket() are marked as available.
Npcap is based on a recent version of libpcap, and thus it makes both pcap_inject() and pcap_sendpacket() available, so it should work with Snort.