text:
Q: Double jump in c# I am trying to make an 2D platformer were I want my character to be able to doublejump.
With this code my character can double jump but depending on how quick I press the jump button the second jump will make the character to jump more than twice as high compared to if I were to wait to press the jump button.
How do I make so the second jump can't be higher than the first one?
[SerializeField] float maxSpeed = 10f;              // The fastest the player can travel in the x axis.
[SerializeField] float jumpForce = 400f;            // Amount of force added when the player jumps.

[Range(0, 1)]
[SerializeField] float crouchSpeed = .36f;          // Amount of maxSpeed applied to crouching movement. 1 = 100%

[SerializeField] bool airControl = false;           // Whether or not a player can steer while jumping;
[SerializeField] LayerMask whatIsGround;            // A mask determining what is ground to the character

Transform groundCheck;                              // A position marking where to check if the player is grounded.
float groundedRadius = .2f;                         // Radius of the overlap circle to determine if grounded
bool grounded = false;                              // Whether or not the player is grounded.
Transform ceilingCheck;                             // A position marking where to check for ceilings
float ceilingRadius = .01f;                         // Radius of the overlap circle to determine if the player can stand up
Animator anim;                                      // Reference to the player's animator component.

int maxNumberOfAirJumps = 1;                        // Number of times the player can jump in the air
int numberOfAirJumpsLeft = 0;

void Awake()
{
    // Setting up references.
    groundCheck = transform.Find("GroundCheck");
    ceilingCheck = transform.Find("CeilingCheck");
    anim = GetComponent<Animator>();
}

void FixedUpdate()
{
    // The player is grounded if a circlecast to the groundcheck position hits anything designated as ground
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundedRadius, whatIsGround);
    anim.SetBool("Ground", grounded);

    // Set the vertical animation
    anim.SetFloat("vSpeed", rigidbody2D.velocity.y);
}

public void Move(float move, bool crouch, bool jump)
{
    // If crouching, check to see if the character can stand up
    if(!crouch && anim.GetBool("Crouch"))
    {
        // If the character has a ceiling preventing them from standing up, keep them crouching
        if( Physics2D.OverlapCircle(ceilingCheck.position, ceilingRadius, whatIsGround))
            crouch = true;
    }

    // Set whether or not the character is crouching in the animator
    anim.SetBool("Crouch", crouch);

    //only control the player if grounded or airControl is turned on
    if(grounded || airControl)
    {
        // Reduce the speed if crouching by the crouchSpeed multiplier
        move = (crouch ? move * crouchSpeed : move);

        // The Speed animator parameter is set to the absolute value of the horizontal input.
        anim.SetFloat("Speed", Mathf.Abs(move));

        // Move the character
        rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);

        // If the input is moving the player right and the player is facing left...
        if(move > 0 && !facingRight)
            // ... flip the player.
            Flip();
        // Otherwise if the input is moving the player left and the player is facing right...
        else if(move < 0 && facingRight)
            // ... flip the player.
            Flip();
    }

    // If the player should jump...
    if (grounded && jump) {
        // Add a vertical force to the player.
        anim.SetBool ("Ground", false);
        rigidbody2D.AddForce (new Vector2 (0f, jumpForce));
        numberOfAirJumpsLeft = maxNumberOfAirJumps; //Reset the air jumps when the player jumps
    }
    else if (!grounded && jump && numberOfAirJumpsLeft  > 0)
    {
        rigidbody2D.AddForce (new Vector2 (0f, jumpForce));
        numberOfAirJumpsLeft--; //One less jump
    }
}

void Flip ()
{
    // Switch the way the player is labelled as facing.
    facingRight = !facingRight;

    // Multiply the player's x local scale by -1.
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}
void OnTriggerEnter(Collider col)
{

    if (col.tag == "Player")
    {
        //money collected

        //destroy money object
        Destroy(gameObject);
    }
}

}

A: Is FixedUpdate called before each Move?  If so, it resets grounded based on the radius, so you could get in a second "grounded" jump if you are fast enough.  Then, you could do one more airjump.

A: I am not good at game development, so I will make a suggestion that I think should work.
You need to reduce jumpForce after the first jump or add less force after each air jump. It should be something like this:
//Declare int numberOfAirJumpsMade = 1;
if (grounded && jump) {
    // Add a vertical force to the player.
    anim.SetBool ("Ground", false);
    rigidbody2D.AddForce (new Vector2 (0f, jumpForce));
    numberOfAirJumpsLeft = maxNumberOfAirJumps; //Reset the air jumps when the player jumps
    numberOfAirJumpsMade = 1; //reset air jump counter
}
else if (!grounded && jump && numberOfAirJumpsLeft  > 0)
{
    rigidbody2D.AddForce (new Vector2 (0f, jumpForce / (numberOfAirJumpsMade * 2)));
    numberOfAirJumpsLeft--; //One less jump
    numberOfAirJumpsMade++;
}

Here you adding in the first air jump 2 times less force than you did in jump from ground. If you set maxNumberOfAirJumps = 2 then first air jump gets (400 /(1 * 2)) = 200 force and second gets (400 /(2 * 2)) = 100.
This is just to get you started. Later you may want to add gravity force in calculations because when your hero is landing you probably want to add far less force for air jumps.


text:
Q: Printing specific rows SAS I'm very new to SAS and I'm having trouble nailing some of its concepts down(I'll be using the native example table BASEBALL for this question).  So what I'm doing is making two new columns for the table which are the batavg86 and batavgcr shown below(I believe they work just fine) and then printing specific columns of the table(name, batavg86, team, and salary) if the value batavg86 is greater than or equal to .300.  What I have posted below does not work, it just prints the whole table.  Can someone explain this to me because I'm pretty lost(My professor started us on this language and then went out of town for two weeks).
data mybaseball;
    set sashelp.baseball;
    batavg86 = nHits/nAtBat;
    batavgcr = crHits/CrAtBat;
    proc print data = name,batavg86,team,salary;
    where batavg86 => .300;
run;

A: This should give you the results you're looking for:
data mybaseball;
    set sashelp.baseball;
    batavg86 = nHits/nAtBat;
    batavgcr = crHits/CrAtBat;
run;

proc print data = mybaseball;
  var name batavg86 team salary;
  where batavg86 >= .300;
run;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find all Accumulation points of semi-open interval This problem is from Apostol Mathematical Analysis.
Let there be a semi-open interval (a,b]. What are the accumulation points of this set?
Unfortunately I could not able to find how to approach this problem. Can someone please guide me?
Thanks!


text:
Q: zip does not work for big files What is the best way to compress a file if it is more than 4 GB in size?
I am using the following for last several months.
mysqldump --all-databases | zip > mybackup.zip

Today I am got an error:
zip error: Entry too big to split, read, or write (file exceeds Zip's 4GB uncompressed size limit)

I am considering using bzip2. Is my choice correct?

A: Why not use the industry standard for this kind of stuff: "gzip"?
mysqldump --all-databases | gzip > mybackup.gz

Size Comparison:
720K    mybackup.gz     (compressed)
2.6M    mybackup.sql    (same data, but uncompressed for comparison)

A: Use xz:
mysqldump --all-databases | xz -9 -c > mybackup.xz

The compression ratio is much higher than zip, just make sure to watch the memory usage.  If you are running xz in a memory-restricted environment you could use the following table to tune the command and avoid paging:
Preset DictSize   CompCPU   CompMem   DecMem
-0     256 KiB       0        3 MiB    1 MiB
-1       1 MiB       1        9 MiB    2 MiB
-2       2 MiB       2       17 MiB    3 MiB
-3       4 MiB       3       32 MiB    5 MiB
-4       4 MiB       4       48 MiB    5 MiB
-5       8 MiB       5       94 MiB    9 MiB
-6       8 MiB       6       94 MiB    9 MiB
-7      16 MiB       6      186 MiB   17 MiB
-8      32 MiB       6      370 MiB   33 MiB
-9      64 MiB       6      674 MiB   65 MiB

xz file size is unlimited (filesystem dependant).

A: Either upgrade zip to at least version 3.0 to support Zip64:
$ zip -v

This is Zip 3.0 (July 5th 2008), by Info-ZIP.

Zip special compilation options:
    LARGE_FILE_SUPPORT   (can read and write large files on file system)
    ZIP64_SUPPORT        (use Zip64 to store large files in archives)

or use the different tools such as: 7z, pbzip2, ...

You should be able to compress files larger than 4GB with pbzip2.


text:
Q: Java Android Como montar um banco de dados randômico? Na aplicação para Android, usando Java, recebo uma string em Json parecida com essa:
String teste = "{\n" + "  \"nometabela\":{\n" + "    \"id\":\"f83d6101cc\",\n" + "    \"coluna1\":\"codigo\",\n" + "    \"coluna2\":\"descricao\",\"coluna3\":\"quantidade\"\n" + "  }
Com esses dados, preciso criar o banco usando SQLite. Por exemplo, o dado "nometabela"dentro da string Json vai ter que ser o nome da tabela, o "id" será "f83d6101cc", a o nome da primeiro coluna será "codigo", a segunda "descricao" e a terceira "quantidade".
Com os dados fixos, consegui criar o banco.
Porém, os dados não serão sempre assim. Eu nunca vou saber como será esse arquivo Json. O banco criado terá que ser baseado nele, então poderão haver mais colunas, ou menos colunas, etc.
Como faço pra ler essa String Json e criar um banco de acordo com os valores passados por ela? Obrigado.

A: Você pode fazer seu código reconhecer que cada " : " passado pelo Json significa uma nova coluna. E o que estiver a esquerda desses pontos significa o nome da tabela, e a direita seu conteudo.


text:
Q: Android: Circular dependencies cannot exist in RelativeLayout A layout that used to work now does not. Its a relative layout with a horizontal scrollview, but when I created this activity I messed up the layout order completely and now it does not work. I cannot figure out why I get this error and my XML code is a complete mess and I do apologize for the chaos. If anyone could explain what the problem is and how I go about fixing it, I would appreciate it.
XML CODE:
    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_rear_gunner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.mr_br.ibcc_bomber_command.rear_gunner">

<HorizontalScrollView
    android:id="@+id/horizontalScrollView1"
    android:focusable="false"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:fillViewport="true"
>

    <ImageView
        android:id="@+id/scrollView"
        android:layout_width="wrap_content" android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_toEndOf="@+id/enemy2"

        android:layout_toRightOf="@+id/enemy2" android:scaleType="centerCrop"
        app:srcCompat="@drawable/nightsky3"/>
</HorizontalScrollView>
<RelativeLayout
    android:id="@+id/item_frame"
    android:layout_width="2000dp"
    android:layout_height="match_parent"
    android:focusable="true"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mr_br.ibcc_bomber_command.rear_gunner"
    android:layout_alignParentTop="true" android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_alignParentEnd="true" android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" android:text="TextView"
        android:textSize="36sp"/>
    <TextView
        android:id="@+id/score"
        android:layout_width="220dp"
        android:layout_height="wrap_content" android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" android:layout_alignParentTop="true"
        android:layout_marginLeft="43dp" android:layout_marginStart="43dp"
        android:layout_marginTop="14dp" android:focusable="false" android:text="Score:"
        android:textColor="@android:color/background_dark"
        android:textColorLink="?attr/colorPrimaryDark"
        android:textSize="46sp"/>
    <TextView
        android:id="@+id/Health"
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/score" android:layout_alignBottom="@+id/score"
        android:layout_toEndOf="@+id/enemy2" android:layout_toRightOf="@+id/enemy2"
        android:text="TextView" android:textColor="@android:color/background_dark"
        android:textColorLink="?attr/colorPrimaryDark"
        android:textSize="46sp"/>
    <Button
        android:id="@+id/btnPilot"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:onClick="pilotBonus"
        android:text="Call Pilot Maneuver (Right)" android:layout_below="@+id/powerUps"
        android:layout_alignLeft="@+id/btnPilotL" android:layout_alignStart="@+id/btnPilotL"/>
    <Button
        android:id="@+id/btnPilotL"
        android:layout_width="250dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="11dp"
        android:layout_marginStart="11dp" android:onClick="pilotBonus"
        android:text="Call Pilot Maneuver (Left)" android:layout_below="@+id/btnPilot"
        android:layout_alignParentLeft="true" android:layout_alignParentStart="true"/>
    <TextView
        android:id="@+id/ammo"
        android:layout_width="350dp"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:text="Ammunition:"
        android:textColor="@android:color/background_dark"
        android:textColorLink="?attr/colorPrimaryDark"
        android:textSize="46sp"
        android:layout_marginRight="49dp" android:layout_marginEnd="49dp"
        android:layout_alignTop="@+id/powerUps" android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"/>
    <ImageView
        android:id="@+id/reinforce3"
        android:layout_width="150dp" android:layout_height="150dp"
        android:scaleX="-1" android:visibility="invisible"
        app:srcCompat="@drawable/bomber_neutral_info" android:layout_above="@+id/powerUps"
        android:layout_alignParentLeft="true" android:layout_alignParentStart="true"/>
    <ImageView
        android:id="@+id/reinforce1"
        android:layout_width="150dp" android:layout_height="150dp"
        android:layout_marginTop="20dp" android:scaleX="-1"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_below="@+id/score" android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>
    <ImageView
        android:id="@+id/reinforce2"
        android:layout_width="150dp" android:layout_height="150dp"
        android:scaleX="-1"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_below="@+id/reinforce1" android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>
    <ImageView
        android:id="@+id/enemyblah"
        android:layout_width="150dp" android:layout_height="150dp"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_marginTop="22dp" android:layout_alignTop="@+id/reinforce1"
        android:layout_toRightOf="@+id/reinforce1" android:layout_toEndOf="@+id/reinforce1"/>
    <ImageView
        android:id="@+id/enemy4"
        android:layout_width="150dp" android:layout_height="150dp"
        android:layout_marginTop="30dp"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_below="@+id/enemy2" android:layout_toRightOf="@+id/enemy2"
        android:layout_toEndOf="@+id/enemy2" android:layout_marginLeft="26dp"
        android:layout_marginStart="26dp"/>
    <TextView
        android:id="@+id/powerUps"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:focusable="false"
        android:text="Support Calls Avaliable:"
        android:textColor="@android:color/background_dark" android:textColorLink="?attr/colorPrimaryDark"
        android:textSize="40sp"
        android:layout_marginTop="33dp" android:layout_below="@+id/enemy3"
        android:layout_alignLeft="@+id/btnPilot" android:layout_alignStart="@+id/btnPilot"/>
    <Button
        android:id="@+id/btnReinforce"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="opBonus" android:text="Operator Request Support"
        android:layout_marginTop="15dp" android:layout_below="@+id/ammo"
        android:layout_toRightOf="@+id/enemy2" android:layout_toEndOf="@+id/enemy2"/>
    <Button
        android:id="@+id/ammoR"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="Ammo" android:text="Ammo Request Support"
        android:layout_alignBaseline="@+id/btnReinforce"
        android:layout_alignBottom="@+id/btnReinforce" android:layout_alignLeft="@+id/enemy2"
        android:layout_alignStart="@+id/enemy2" android:layout_marginLeft="17dp"
        android:layout_marginStart="17dp"/>
    <ImageView
        android:id="@+id/enemy5"
        android:layout_width="150dp" android:layout_height="150dp"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_above="@+id/ammo" android:layout_alignRight="@+id/ammoR"
        android:layout_alignEnd="@+id/ammoR" android:layout_marginRight="19dp"
        android:layout_marginEnd="19dp"/>
    <ImageView
        android:id="@+id/enemy6"
        android:layout_width="150dp" android:layout_height="150dp"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_alignTop="@+id/enemy2" android:layout_alignRight="@+id/btnReinforce"
        android:layout_alignEnd="@+id/btnReinforce" android:layout_marginRight="23dp"
        android:layout_marginEnd="23dp"/>
    <ImageView
        android:id="@+id/enemy3"
        android:layout_width="150dp" android:layout_height="150dp"
        android:layout_marginTop="21dp" android:visibility="invisible"
        app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_below="@+id/enemy2" android:layout_toLeftOf="@+id/enemy6"
        android:layout_toStartOf="@+id/enemy6"/>
    <ImageView
        android:id="@+id/enemy2"
        android:layout_width="300dp" android:layout_height="200dp"
        android:layout_marginLeft="13dp" android:layout_marginStart="13dp"
        android:visibility="invisible" app:srcCompat="@drawable/bomber_neutral_info"
        android:layout_alignTop="@+id/enemyblah" android:layout_toRightOf="@+id/btnReinforce"
        android:layout_toEndOf="@+id/btnReinforce"/>
    <TextView
        android:id="@+id/warning"
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:text="TextView" android:textColor="@android:color/holo_red_dark"
        android:textColorLink="?attr/colorPrimaryDark"
        android:textSize="46sp" android:layout_above="@+id/reinforce3"
        android:layout_centerHorizontal="true" android:visibility="invisible"/>
</RelativeLayout>

Error:

A: You have your outer relativelayout's imageview depending on enemy2(which is inside inner relativelayout).  This is the problem

A: I see one point of concern where it looks like btnPilot relies on the position of btnPilotL which relies on btnPilot. This is probably one of possibly multiple circular references.

A: I took your advice and began taking out the views 1 by one, the problem was with the enemy1 view. For some reason, I believe this was enemy2 but another activity had changed this when I automatically updated XML references, I changed the ID to something different and the layout works again. Thank you for the advice, I also have a better understanding to what exactly a Circular dependency error is.


text:
Q: opencv c++ compare keypoint locations in different images When comparing 2 images via feature extraction, how do you compare keypoint distances so to disregard those that are obviously incorrect?
I've found when comparing similar images against each other, most of the time it can fairly accurate, but other times it can throws matches that are completely separate.
So I'm after a way of looking at the 2 sets of keypoints from both images and determining whether the matched keypoints are relatively in the same locations on both. As in it knows that keypoints 1, 2, and 3 are so far apart on image 1, so the corresponding keypoints matched on image 2 should be of a fairly similar distance away from each other again.
I've used RANSAC and minimum distance checks in the past but only to some effect, they don't seem to be as thorough as I'm after.
(Using ORB and BruteForce)
EDIT
Changed "x, y, and z" to "1, 2, and 3"
EDIT 2 -- I'll try to explain further with quick Paint made examples:
Say I have this as my image:

And I give it this image to compare against:

Its a cropped and squashed version of the original, but obviously similar.
Now, say you ran it through feature detection and it came back with these results for the keypoints for the two images:

The keypoints on both images are in roughly the same areas, and proportionately the same distance away from each other. Take the keypoint I've circled, lets call it "Image 1 Keypoint 1".

We can see that there are 5 keypoints around it. Its these distances between them and "Image 1 Keypoint 1" that I want to obtain so to compare them against "Image 2 Keypoint 1" and its 5 surround keypoints in the same area (see below) so as to not just compare a keypoint to another keypoint, but to compare "known shapes" based off of the locations of the keypoints.

--
Does that make sense?

A: Keypoint matching is a problem with several dimensions. These dimensions are:

*

*spatial distance, ie, the (x,y) distance as measured from the locations of two keypoints in different images

*feature distance, that is, a distance that describes how much two keypoints look alike.

Depending on your context, you do not want to compute the same distance, or you want to combine both. Here are some use cases:

*

*optical flow, as implemented by opencv's sparse Lucas-Kanade optical flow. In this case, keypoints called good features are computed in each frame, then matched on a spatial distance basis. This works because the image is supposed to change relatively slowly (the input frames have a video framerate);

*image stitching, as you can implement from opencv's features2d (free or non-free). In this case, the images change radically since you move your camera around. Then, your goal becomes to find stable points, ie, points that are present in two or more images whatever their location is. In this case you will use feature distance. This also holds when you have a template image of an object that you want to find in query images.

In order to compute feature distance, you need to compute a coded version of their appearance. This operation is performed by the DescriptorExtractor class.
Then, you can compute distances between the output of the descriptions: if the distance between two descriptions is small then the original keypoints are very likely to correspond to the same scene point.
Pay attention when you compute distances to use the correct distance function: ORB, FREAK, BRISK rely on Hamming distance, while SIFt and SURF use a more usual L2 distance.
Match filtering
When you have individual matches, you may want to perform match filtering in order to reject good individual matches that may arise from scene ambiguities. Think for example of a keypoint that originates from the corner of a window of a house. Then it is very likely to match with another window in another house, but this may not be the good house or the good window.
You have several ways of doing it:

*

*RANSAC performs a consistency check of the computed matches with the current solution estimate. Basically, it picks up some matches at random, computes a solution to the problem (usually a geometric transform between 2 images) and then counts how many of the matchings agree with this estimate. The estimate with the higher count of inliers wins;

*David Lowe performed another kind of filtering in the original SIFT paper.
He kept the two best candidates for a match with a given query keypoint, ie, points that had the lowest distance (or highest similarity). Then, he computed the ratio similarity(query, best)/similarity(query, 2nd best). If this ratio is too low then the second best is also a good candidate for a match, and the matching result is dubbed ambiguous and rejected.

Exactly how you should do it in your case is thus very likely to depend on your exact application.
Your specific case
In your case, you want to develop an alternate feature descriptor that is based on neighbouring keypoints.
The sky is obviously the limit here, but here are some steps that I would follow:

*

*make your descriptor rotation and scale invariant by computing the PCA of the keypoints :
// Form a matrix from KP locations in current image
cv::Mat allKeyPointsMatrix = gatherAllKeypoints(keypoints);

// Compute PCA basis
cv::PCA currentPCA(allKeyPointsMatrix, 2);

// Reproject keypoints in new basis
cv::Mat normalizedKeyPoints = currentPCA.project(allKeyPointsMatrix);

*(optional) sort the keypoints in a quadtree or kd-tree for faster spatial indexing

*Compute for each keypoint a descriptor that is (for example) the offsets in normalized coordinates of the 4 or 5 closest keypoints

*Do the same in your query image

*Match keypoints from both mages based on these new descriptors.

A: What is it you are trying to do exactly? More information is needed to give you a good answer. Otherwise it'll have to be very broad and most likely not useful to your needs.
And with your statement "determining whether the matched keypoints are relatively in the same locations on both" do you mean literally on the same x,y positions between 2 images?
I would try out the SURF algorithm. It works extremely well for what you described above (though I found it to be a bit slow unless you use gpu acceleration, 5fps vs 34fps).
Here is the tutorial for surf, I personally found it very useful, but the executables are for linux users only. However you can simply remove the OS specific bindings in the source code and keep only the opencv related bindings and have it compile + run on linux just the same.
https://code.google.com/p/find-object/#Tutorials
Hope this helped!

A: You can do a filter on the pixels distance between two keypoint.
Let's say matches is your vector of matches, kp_1 your vector of keypoints on the first picture and kp_2 on the second. You can use the code above to eliminate obviously incorrect matches. You just need to fix a threshold.
double threshold= YourValue;
vector<DMatch> good_matches;
for (int i = 0; i < matches.size(); i++)
{
    double dist_p = sqrt(pow(abs(kp_1[matches[i][0].queryIdx].pt.x - kp_2[matches[i][0].trainIdx].pt.x), 2) + pow(abs(kp_1[matches[i][0].queryIdx].pt.y - kp_2[matches[i][0].trainIdx].pt.y), 2));
    if (dist_p < threshold)
    {
        good_matches.push_back(matches[i][0]);
    }
}


text:
Q: Will using the positive end of an AA battery to touch my phone screen damage my phone? I'm playing a game where it will be helpful to hold down a button for an extended period of time. I didn't have a stylus, so I looked online for any ideas. Lots of people said to use the negative end of an AA battery. It works, but only when you're touching the battery. So I tried the positive end of the battery on my phone's touch screen, and it works (even when I'm not touching the battery). I haven't seen anything online about this, which I found very unusual.
So my question is, will it damage my phone if I use the positive end of an AA battery on my phone screen?

A: Capacitive touch screens works sensing the electric field being driven toward ground by a finger… or whatever has the electrical properties of a finger.
You are non making any current flow and except for the risks of scratching (and blunt damage) there are no issues. They also sell 'touch styli' which are more or less pieces of metal tube

A: Pressure = force/area = weight/area, hence more pressure when the + end is resting on screen.


text:
Q: github error on create release: tag could not be created, pre-receive hooks failed I am not by any means a sophisticated github user.  I have learned the minimum handful of commands needed to add, commit, and push my project code to the public github.com repository.  So far it's been working fairly well... until today when I tried to create a new release (my third).
For some reason, when I try to publish my new release, I get the message
Tag could not be created. Pre-receive hooks failed.
I have never seen this message before.
I have tried various different tag names;  I have tried logging out and back in again;  I have tried pre-tagging on my local disk copy of the repo;  I have pushed and pulled (both ends are up to date).  This about exhausts my repertoire of things to try :-(
As a relative n00b I find this message incredibly opaque (sigh).  I have tried googling for it, but quickly got in over my head -- most of the hits I found were discussions about people setting up their own networked repos and installing or tweaking their own custom "pre-receive hooks", whereas I am just a dumb user of github.com apparently struggling with whatever "pre-receive hooks" they have installed (?).  If anyone can at least point me in the right direction I'd be most grateful.

A: Make sure you select the tag version in the dropdown.  The GitHub form will let you submit when this field is blank, but it will always display the mentioned error message.  (You do not need a 'v' prefix.).
The latest Github form makes this more cryptic by having a dropdown titled 'Tag:Choose or Create" that hides the fact that this field is both required but not set.
Latest Github Form

Older Github Form

A: In a GitHub context, I have seen that error message in this issue
It could be a tag naming convention issue.
The GitHub release documentation recommends (enforces?) a tag following the semantic versioning naming scheme: vX.Y.Z.
As shown here, try vx.y.z.


text:
Q: URL in backbone.js single page app gets way too long (~98'000 characters) I have a JavaScript single page app (using backbone.js), where the app's state is stored as part of URL parameters. This webpage has a lot of checkboxes.
So if a user hits a URL like http://my-app.org/project/#app/load?checkboxID[4053]=1&checkboxID[4054]=1&checkboxID[4055]=1&checkboxID[4056]=1&checkboxID[4057]=1&checkboxID[4058]=1&checkboxID[4059]=1...goes on and on, various further params...
then the page configures itself (using Backbone.Router) with the given checkboxes selected. Notice the hash #app in the URL, meaning that the parameters are handled by the JavaScript app.
The problem is now that the app has now much more parameters than I previously thought of. Hence, with all checkboxes enabled, I get an URL that is about 98.000 characters long, whereas according to this answer it can only be 2.000 at most. Oops :-(
What's your advice to handle this? I thought maybe there is a smart way of "shortening"/"compressing" the URL string in JavaScript (like gzipping + base64 encoding the URL string), but even this does not shorten the URL enough to be under 2000 characters.

A: I don't think passing the state of App via URL is good practice.
You could have a properly namespaced object to store the state.
var myApp = myApp || {};
myApp.state = myApp.state || {};

And when you are using URL to carry the state, just fill this object and use this around.
PS: This answer may not please you as you are looking for compression like things and would not like to change your code too much. Still a suggestion for you.

A: Couldn't you reconfigure the url to read parameters as an array instead of individual items e.g.
checkboxId=[4053, 4054, 4054 ...]

That would save some characters and you can just loop through id's in said array.
If "40" is a common character, or if "4" is common you could even remove this from the value and prepend it when running the script?


text:
Q: first questions and answers is repeating when i set into the textview? I have a lot of questions and answers in my mysql database , i am creating quiz app  when I set them up, i am getting all questions and answer through mysql database using json then the first question  and answers I get it. How can I set the all Questions and answers how can i am using loop in my code please help?
    json_string=getIntent().getExtras().getString("j");
    try {
        jsonObject=new JSONObject(json_string);
        jsonArray=jsonObject.getJSONArray("server_response");
        if(jsonArray.length()!=0){
            JSONObject JO=jsonArray.getJSONObject(count);
            Ques = JO.getString("QuestionText");
            Options=JO.getString("Options").split("##");
            ans = Integer.parseInt(JO.getString("CorrectAnswer"));

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
        if (extras == null) {

        } else {

            Answers=extras.getString("urAnswers");
        }
    }
    l=(LinearLayout)findViewById(R.id.Review);
    ScrollView scrollView= new ScrollView(this);
    LinearLayout Lin =new LinearLayout(this);
    int i;
    for (i=0;i<jsonArray.length();i++){
        TextView Qus = new TextView(this);
        Qus.setTextSize(20);
        Qus.setTextColor(Color.WHITE);
        Qus.setPadding(0, 20, 0, 0);
        Qus.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        TextView OptA = new TextView(this);
        TextView OptB = new TextView(this);
        TextView OptC = new TextView(this);
        TextView OptD = new TextView(this);
        TextView urans = new TextView(this);
        TextView correctans = new TextView(this);
        Qus.setText (" Question. No.(" + (QuestionNo + 1) + ").\n " + Ques);
        OptA.setText("(a). " + Options[0].toString() + "\n");
        OptB.setText("(b). " + Options[1].toString() + "\n");
        OptC.setText("(c). " + Options[2].toString() + "\n");
        OptD.setText("(d). " + Options[3].toString() + "\n\n");

        String a = "";
        int color = 0;
        String Answers1 = Answers.substring(i, i + 1);
        String correct = String.valueOf(ans);
        if (Answers1.equals("5")) {
            a = "UnAnswered";
            color = Color.YELLOW;
        }
        if (Answers1.equals("1")) {
            a = "A";
            if (correct.equals("1"))
                color = Color.GREEN;
            else
                color = Color.RED;
        }
        if (Answers1.equals("2")) {
            a = "B";
            if (correct.equals("2"))
                color = Color.GREEN;
            else
                color = Color.RED;
        }
        if (Answers1.equals("3")) {
            a = "C";
            if (correct.equals("3"))
                color = Color.GREEN;
            else
                color = Color.RED;
        }
        if (Answers1.equals("4")) {
            a = "D";
            if (correct.equals("4"))
                color = Color.GREEN;
            else
                color = Color.RED;
        } else {
        }

        String b = "";

        if (correct.equals("1")) {
            b = "A";
        }
        if (correct.equals("2")) {
            b = "B";
        }
        if (correct.equals("3")) {
            b = "C";
        }
        if (correct.equals("4")) {
            b = "D";
        } else {

        }

        urans.setText("Your Answer :" + a.toString() + "\n");
        urans.setTextSize(18);
        urans.setTextColor(color);
        correctans.setText("Correct Answer :" + b.toString() + "\n\n");
        correctans.setTextSize(18);
        correctans.setTextColor(Color.GREEN);
        Lin.addView(Qus);
        Lin.addView(OptA);
        Lin.addView(OptB);
        Lin.addView(OptC);
        Lin.addView(OptD);
        Lin.addView(urans);
        Lin.addView(correctans);
        OptA.setTextSize(18);
        //OptA.setPadding(0,30,0,0);
        OptA.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams
                .WRAP_CONTENT));
        OptA.setTextColor(Color.WHITE);
        OptB.setTextSize(18);
        OptB.setTextColor(Color.WHITE);
        //OptA.setPadding(0,30,0,0);
        OptB.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams
                .WRAP_CONTENT));
        OptC.setTextSize(18);
        OptA.setPadding(0, 30, 0, 0);
        OptC.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams
                .WRAP_CONTENT));
        OptC.setTextColor(Color.WHITE);
        OptD.setTextSize(18);
        //OptA.setPadding(0,30,0,0);
        OptD.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams
                .WRAP_CONTENT));
        OptD.setTextColor(Color.WHITE);
    }

    scrollView.addView(Lin);
    scrollView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
            LinearLayout.LayoutParams.FILL_PARENT));
    scrollView.setPadding(20,10,10,20);
    Lin.setOrientation(LinearLayout.VERTICAL);
    getWindow().setBackgroundDrawableResource(R.drawable.back3);
    setContentView(scrollView);
}

}

A: First of learn to how to use RecyclerView here is the link RecyclerView tutorial and learn how to parse json json parsing tutorial Learning these 2 tutorial will sure help you for this problem as well as in future.


text:
Q: A generalization of coupon collector's problem: take an adjacent pair each time. We have $n$ distinct kinds of coupons (of unlimited supply), the categories are denoted $1\dots n$.Each time we could draw two coupons, but the two must be of adjacent kind (it could be any of $\{(1,2),(2,3)...,(n-1,n),(n,1)\}$, the probability of drawing any pair is equal). What is the expected number of draws before collecting all $n$ distinct coupons?
Some progress: This is different than just drawing two coupons with replacement randomly, where I already know a formula. And the "pattern" of selecting does not matter, this means drawing $\{(1,3),(2,4)...,(n-1,1),(n,2)\}$ yields the same result.

A: Here is a formula. My fault, I should have realized this problem being equivalent to Project Euler 645, which I have solved earlier.
$$E(n)=1-n\sum_{i=1}^{n-1}\frac{1}{i}\left((-1)^i\binom{n-1}{i}+\frac{\binom{n-i}{i}}{\binom{n-1}{i}}\right)$$
I am now working on the case when a draw includes more than 2 coupons.

A: (After the answer of @mayoi, this approach is surpassed, however I am putting it just to show a Markovian approach).
Suppose that, upon turn $t$, you have acquired $m$ coupon out the $n$ avalaible.
Suppose also, for the moment, that the acquired coupon are in succession $\{1,2, \cdots,m \}$.
Now,
 - if you get coupons $(m,m+1)$ or $(n,1)$ you increase by one the amount collected;
 - if you get coupons $(m+1,m+2), \cdots (n-1,n)$ you increase by two the amount collected;
 - in any other case you remain with the collected amount;
Case 1 corresponds to $2$ extractions, case 2 to $n-m-1$ extractions and case 3 gives the remaining $m-1$ extractions
of the total $n$.
When $m=0$ we have $0,n,0$, while if it were $m=1$ (but it cannot occur) we would have $2, n-2,0$, then when
$m=n-1$ we have $[2,0,n-2]$ and for $n=m$ it is $[0,0,n]$.
Because of symmetry, it is easy to deduce that the above counting holds whichever type are the $m$ coupon collected.
Therefore the transition matrix for the number of coupons collected, indexed $[0,n] \times [0,n]$,  is
$$
\eqalign{
  & T_{\,m,\,q} \quad \left| {\;0 \le m,q \le n} \right.\quad  =   \cr
  &  = \left[ {0 = n} \right] + {{\left[ {1 \le n} \right]} \over n}\left( {\left( {m - \left[ {m < n} \right]} \right)\left[ {1 \le m} \right]\left[ {q = m} \right]
 + 2\left[ {1 \le m} \right]\left[ {q = m + 1} \right] + \left( {n - m - \left[ {1 \le m} \right]} \right)\left[ {q = m + 2} \right]} \right) \cr}
$$
where $[P]$ denotes the Iverson bracket
$$
\left[ P \right] = \left\{ {\begin{array}{*{20}c}
   1 & {P = TRUE}  \\
   0 & {P = FALSE}  \\
 \end{array} } \right.
$$
For example, for $n=4,5$ the matrices are
$$
\eqalign{
  & {\bf T}_{\,4}  = \left( {\matrix{
   0 & 0 & 1 & 0 & 0  \cr
   0 & 0 & {1/2} & {1/2} & 0  \cr
   0 & 0 & {1/4} & {1/2} & {1/4}  \cr
   0 & 0 & 0 & {1/2} & {1/2}  \cr
   0 & 0 & 0 & 0 & 1  \cr
 } } \right)  \cr
  & {\bf T}_{\,5}  = \left( {\matrix{
   0 & 0 & 1 & 0 & 0 & 0  \cr
   0 & 0 & {2/5} & {3/5} & 0 & 0  \cr
   0 & 0 & {1/5} & {2/5} & {2/5} & 0  \cr
   0 & 0 & 0 & {2/5} & {2/5} & {1/5}  \cr
   0 & 0 & 0 & 0 & {3/5} & {2/5}  \cr
   0 & 0 & 0 & 0 & 0 & 1  \cr
 } } \right) \cr}
$$
The matrix exhibits an interesting symmetry.
Its eigenvalues follows a regular path $\left\{ {{k \over h}\quad \left| {\;0 \le k \ne h - 1 \le h} \right.} \right\}$ (for $2 \le h$), with the null value being double.
The matrix is diagonalizable, and we can apply the Markov theory to get various interesting parameters.


text:
Q: How does this kbd function work? Would someone please explain the below function? How does the kdb utilize x here?
I changed the original function to "func" I know it uses the queries assigned in que to query both functions. The problem is I don't know how those x 0 and and x 0 1 work here. I know 0 is the index 1 and 1 is the index 2 and x is the parameter.
svcs:`TEST:1`TEST:2
que: (`$"select count sym from trades";`$"select sum size from trades")

{func[x 0;string x 1],x 0 1}each svcs cross que

A: x is being passed in as a two element list "each" time the function is called.
Forget about the func description for now and just add in some logging to see things more clearly:
q)svcs cross que
TEST:1 select count sym from trades
TEST:1 select sum size from trades
TEST:2 select count sym from trades
TEST:2 select sum size from trades
q){show enlist "x 0 is ",string x 0;show enlist "x 1 is ",string x 1;show raze "
x 0 1 is ",(string x 0)," & ", (string x 1)}each svcs cross que;
"x 0 is TEST:1"
"x 1 is select count sym from trades"
"x 0 1 is TEST:1 & select count sym from trades"
"x 0 is TEST:1"
"x 1 is select sum size from trades"
"x 0 1 is TEST:1 & select sum size from trades"
"x 0 is TEST:2"
"x 1 is select count sym from trades"
"x 0 1 is TEST:2 & select count sym from trades"
"x 0 is TEST:2"
"x 1 is select sum size from trades"
"x 0 1 is TEST:2 & select sum size from trades"

Or an individual example:
q)x:(`TEST:1;`$"select count sym from trades")
q)x 0
`TEST:1
q)x 1
`select count sym from trades
q)x 0 1
`TEST:1`select count sym from trades

x 0 1 indexes and retrieves both the first and second element (returning

A: You're right and x 0 or x 1 is the same as x[0] or x[1] (see the link below on indexing lists), except perhaps the problem is that it isn't obvious what x is.
Because of the adverb each the function is executed four times, once for each item in svcs cross que
See;
q)count svcs cross que
4

And then each item in svcs cross que has two items.
q)count each svcs cross que
2 2 2 2

So in the first execution, x is the first item of svcs cross que and so on.
q)first svcs cross que
`TEST:1`select count sym from trades
q)(first svcs cross que) 0
`TEST:1
q)(first svcs cross que) 1
`select count sym from trades
q)(first svcs cross que) 0 1
`TEST:1`select count sym from trades

Reference
http://code.kx.com/q4m3/6_Functions/#671-monadic-each
http://code.kx.com/q4m3/3_Lists/#34-indexing


text:
Q: Facing an issue with using camera by intent in Android I want to take a picture and store it in a folder with the name Medit via my app. When my app starts, it should be able to pull all the pictures from this folder and display it directly. So the data storage path must be set and stored as part of the app. Here is what I have done so far
 public void CaptureImage(){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mediaStorageDir =new File(Environment.getExternalStorageDirectory(),"MyAppName");
        mUri =Uri.fromFile(mediaStorageDir+"IMG"+System.currentTimeMillis() + ".jpg");

        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);

    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            super.onActivityResult(requestCode, resultCode, data);
            Bitmap bm = BitmapFactory.decodeFile(mUri.getPath());
            imgVIew.setImageBitmap(bm);
           }else Log.d("capture", "FAILED");}

Issue is, irrespective what i change mUri to the picture is being stored in DCIM/ camera images with the default naming convention. In the onActivityResult I am capturing the image. Issue is Im not able to comtrol where it is being stored and as what name. I need to
1) Capture an image via intent, store it in a location with a custom name.
2) Everytime the app opens, it should go to that same storage location and pull out the pictures and display them one by one.

A:
irrespective what i change mUri to the picture is being stored in DCIM/ camera images with the default naming convention

Most likely, that is a bug in that camera app. Most camera apps will honor EXTRA_OUTPUT properly. However, there is no enforcement mechanism to ensure that a camera app will honor EXTRA_OUTPUT.
However, please do not use string concatenation to create a file path, and make sure that you create your directories. IOW, replace:
mediaStorageDir =new File(Environment.getExternalStorageDirectory(),"MyAppName");
mUri =Uri.fromFile(mediaStorageDir+"IMG"+System.currentTimeMillis() + ".jpg");

with:
mediaStorageDir=new File(Environment.getExternalStorageDirectory(),"MyAppName");
mediaStorageDir.mkdirs();
mUri=Uri.fromFile(new File(mediaStorageDir, "IMG"+System.currentTimeMillis() + ".jpg"));

It is possible that changing this code will make your app more compatible with this particular camera app, but there are no guarantees that all camera apps will behave as you wish.

I need to...

Your code is written to give you what you want. However, you are invoking a third-party app with the ACTION_IMAGE_CAPTURE Intent. There are thousands of camera apps, both pre-installed and available for download from the Play Store and elsewhere. Many will have properly-working ACTION_IMAGE_CAPTURE implementations. Some will not.
Either:

*

*Detect that the image is not at your desired path and let the user know that their camera app is broken. Then, suggest that they install some third-party camera app that you have tested. Or,

*Stop using ACTION_IMAGE_CAPTURE and work with the camera APIs directly, though this is rather difficult.

A: Your pictures are being save in default path because the path you are providing is wrong. Use the following code.
File mediaStorageDir =new File(Environment.getExternalStorageDirectory(),"MyAppName");

    if(!mediaStorageDir.exists())
        mediaStorageDir.mkdir();

    Uri mUri = Uri.fromFile(new File(mediaStorageDir.getAbsolutePath() + "/IMG" + System.currentTimeMillis() + ".jpg"));
    LogHelper.LogI("path", mUri.getPath());

A: Please try th following code it's working for me.
public class CaptureImage extends Activity {

private static final int PICK_CAMERA_IMAGE = 2;

ImageView img;
Button btn;

private Uri mImageCaptureUri;

public static String userPicPath;

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

    img = (ImageView) findViewById(R.id.activity_capture_image_img);
    btn = (Button) findViewById(R.id.button1);

    btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            SimpleDateFormat dateFormatter = new SimpleDateFormat(
                    "yyyyMMdd_HHmmss", Locale.US);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            File file = new File(Environment.getExternalStorageDirectory()
                    + "/" + Constants.IMAGE_DIRECTORY_NAME, "img_"
                    + dateFormatter.format(new Date()).toString() + ".png");
            userPicPath = file.getPath();
            mImageCaptureUri = Uri.fromFile(file);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
            startActivityForResult(intent, PICK_CAMERA_IMAGE);
        }
    });

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_CAMERA_IMAGE && resultCode == RESULT_OK) {

        Log.d("CaptureImage", mImageCaptureUri.toString());

        Bitmap bitmapProfile = getBitmap(userPicPath, this);
        img.setImageBitmap(bitmapProfile);

    }
}

public static Bitmap getBitmap(String path, Context context) {
    Uri uri = Uri.fromFile(new File(path));
    InputStream in = null;
    ContentResolver mContentResolver = context.getContentResolver();
    try {
        // final int IMAGE_MAX_SIZE = 2048;
        final int IMAGE_MAX_SIZE = 1024;
        in = mContentResolver.openInputStream(uri);

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(in, null, o);
        in.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(
                    2,
                    (int) Math.round(Math.log(IMAGE_MAX_SIZE
                            / (double) Math.max(o.outHeight, o.outWidth))
                            / Math.log(0.5)));
        }

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        in = mContentResolver.openInputStream(uri);
        Bitmap b = BitmapFactory.decodeStream(in, null, o2);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        b.compress(Bitmap.CompressFormat.JPEG, 25, stream);
        in.close();

        return b;
    } catch (FileNotFoundException e) {
        Log.e("CaptureImage", "file " + path + " not found");
    } catch (IOException e) {
        Log.e("CaptureImage", "file " + path + " not found");
    }
    return null;
}

}


text:
Q: determine solution for differential equation $$(1-t^2)x'-tx+t^2-1=0,\quad t\in(-1,1)$$
I have to determine the solution for this DE.
I've tried dividing the equation with $(1-t^2)$, so it'd look like:
$x'-\frac{t}{1-t^2}x=1$
I've tried to first solve it as a homogeneous DE:
$\frac{1}{x}dx-\frac{t}{1-t^2}dt=0$
$\ln|x|+\ln(1-t^2)^{\frac{1}{2}}=C_1$
$|x|\cdot(1-t^2)^{\frac{1}{2}}=e^{C_1}$
$x=e^{C_1}(1-t^2)^{-\frac 1{2}}=C(1-t^2)^{-\frac 1{2}}$
But then I'm stuck. I can't figure out what to use this to solve the non-homogeneous form.
Any help?

A: You solved the homogeneous ODE but you also found that an integrating factor of your first order linear ODE is $(1-t^2)^{1/2}$.
Now multiply both sides of $x'(t)-\frac{t}{1-t^2}x(t)=1$ for such factor:
$$(1-t^2)^{1/2}x'(t)-t(1-t^2)^{-1/2}x(t)=\frac{d}{dt}\left((1-t^2)^{1/2}x(t)\right)=(1-t^2)^{1/2}.$$
Hence, it remains to integrate
$$(1-t^2)^{1/2}x(t)=\int (1-t^2)^{1/2}\, dt=\frac{1}{2}\left(t(1-t^2)^{1/2}+\arcsin(t)\right)+C$$
Finally
$$x(t)=\frac{1}{2}\left(t+(1-t^2)^{-1/2}\arcsin(t)\right)+C(1-t^2)^{-1/2}.$$
Note that the term $C(1-t^2)^{-1/2}$ is the solution of the homogeneous ODE that you found in your work.

A: Try the following ansatz:
$$
x = x_{hom} f
$$
where $x_{hom}$ is the solution to the homogenious equation you found. Fom this you get:
$$
(x)^\prime-\frac{t}{1-t^2}x = f^\prime x_{hom} + f\left(x^\prime_{hom}-\frac{t}{1-t^2}x_{hom}\right) = f^\prime x_{hom} = 1
$$
since you know $x_{hom}$ you may now find $f$, and thus $x$, by integration.


text:
Q: Searching efficient way of calculating permutations of (13,3) np.array My inputs in this case are a (13,3) numpy array (where every row contains odds for a soccer game) and an integer working as a limit, for example 2 million.
The numpy array represents a betting system, where outcomes not involved in the system are 0. The other ones are representing odds.
system = np.array([[1.14,9.31,17.3],[2.48,3.75,2.67],[2.11,3.64,3.37],
               [3.15,3.83,2.15],[3.95,3.83,1.89],[0,3.54,3.8],
               [0,3.38,3.72],[0,3.74,1.93],[2.53,0,2.8],[0,0,1.38],
               [1.79,4.04,4.24],[4.41,3.33,1.85],[1.64,0,0]])
limit = int(2.5*10**6)

An "outcome-row" now in this system represents an outcome of the matches (remember, 0:s means not involved in the system). An example of a "outcome-row" for this system is
1.14,2.48,2.11,3.14,3.95,3.54,3.38,3.74,2.53,1.38,1.79,4.41,1.64.

Now to the question: How many "outcome-rows" in this system contains an odds product (every number/odds in the "outcome row" multiplied with each other, the above "outcome-row" example contain an odds product of 1.4966*10^5) that is GREATER than the given? The problem is for every possible "outcome-row" compare their odds product to the given limit.
I would be extremely thankful for any type of help.


text:
Q: as_json not calling as_json on associations I have a model with data that should never be included when it is rendered as json.  So I implemented the class' as_json method to behave appropriately.  The problem is when other models with associations with this model render json, my custom as_json is not being called.
class Owner < ActiveRecord::Base
  has_one :dog

  def as_json(options={})
    puts "Owner::as_json"
    super(options)
  end
end

class Dog < ActiveRecord::Base
  belongs_to :owner

  def as_json(options={})
    puts "Dog::as_json"
    options[:except] = :secret
    super(options)
  end
end

Loading development environment (Rails 3.0.3)
  ruby-1.9.2-p136 :001 > d = Dog.first
    => #<Dog id: 1, owner_id: 1, name: "Scooby", secret: "I enjoy crapping everwhere">
  ruby-1.9.2-p136 :002 > d.as_json
  Dog::as_json
   => {"dog"=>{"id"=>1, "name"=>"Scooby", "owner_id"=>1}}
  ruby-1.9.2-p136 :004 > d.owner.as_json(:include => :dog)
  Owner::as_json
   => {"owner"=>{"id"=>1, "name"=>"Shaggy", :dog=>{"id"=>1, "name"=>"Scooby", "owner_id"=>1, "secret"=>"I enjoy crapping everwhere"}}}

Thanks for the help

A: As acknowledged above, this is an issue with the Rails base. The rails patch here is not yet applied and seems at least slightly controversial, so I'm hesitant to apply it locally. Even if applied as a monkey patch it could potentially complicate future rails upgrades.
I'm still considering RABL suggested above, it looks useful. For the moment, I'd rather not add another view templating language into my app. My current needs are very small.
So here's a workaround which doesn't require a patch and work for most simple cases. This works where the association's as_json method you'd like to have called looks like
def as_json(options={})
  super( <... custom options ...> )
end

In my case I've got Schedule model which has many Events
class Event < ActiveRecord::Base

  # define json options as constant, or you could return them from a method
  EVENT_JSON_OPTS = { :include => { :locations => { :only => [:id], :methods => [:name] } } }

  def as_json(options={})
    super(EVENT_JSON_OPTS)
  end
end

class Schedule < ActiveRecord::Base
  has_many :events

  def as_json(options={})
    super(:include => { :events => { Event::EVENT_JSON_OPTS } })
  end
end

If you followed the guideline that anytime you :include an association in your as_json() methods, you define any options you need as a constant in the model to be referenced, this would work for arbitrary levels of associations. NOTE I only needed the first level of association customized in the above example.

A: I've found that serializable_hash works just as you'd expect as_json to work, and is always called:
  def serializable_hash(options = {})
    result = super(options)
    result[:url] = "http://.."
    result
  end

A: This is a known bug in Rails. (The issue is marked closed due to the migration to Github issues from the previous bug tracker, but it's still a problem as of Rails 3.1.)

A: I ran into the same issue. I wanted this to work:
render :json => @favorites.as_json(:include => :location)

But it didn't so I ended up adding an index.json.erb with the following:
<% favs = @favorites.as_json.each do |fav| %>
    <% fav["location"] = Location.find(fav["location_id"]).as_json %>
<% end %>
<%= favs.to_json.html_safe %>

Not a fix - just a work around.  I imagine you did the same thing.

A: Update @John pointed out this is a known bug in Rails. A patch to fix it appears to be: at https://github.com/rails/rails/pull/2200. Nevertheless, you might try RABL, because its sweet.
I've always been frustrated with passing a complex set of options to create the JSON views I want. Your problem, which I experienced with Mongoid in Rails 3.0.9, prompted me to write JSON templates. But actually, if you're dealing with relations or custom api properties, it turns out that templates are way nicer.
Besides, dealing with different outputs seems like the View layer to me, so I settled on using RABL, the API templating language. It makes it super easy to build valid JSON and include any associations or fields.
Not a solution to the problem, but a better solution for the use case.

A: This was reported as a bug: http://ternarylabs.com/2010/09/07/migrating-to-rails-3-0-gotchas-as_json-bug/


text:
Q: MVC 3 + REST return custom http error? In my application I am trying to get it so that when a REST api call is made, if there is an error that it return a proper status code then either Json or Xml in the body of the response.
So 400: { 'ErrorCode': '400', 'Reason' : 'You did something wrong..' }
or 400: <Error><ErrorCode>400</ErrorCode><Reason>You did something wrong</Reason></Error>
However I can't seem to find how to set the status and body to make this happen. Using fiddler inspect whats being passed back and fourth I've found that if I return a normal ActionResult then I can return the body message ok but the status is 200. If I use HttpException then I can set the status code but the body message is returned as a large html document. I've tried using HttpStatusCodeResult but that just seems to fail and return a 302.
I'm a bit stumped.

A: Try Response.StatusCode = (int)HttpStatusCode.BadRequest; in your action method. Check out this article at develoq for a short tutorial: http://develoq.net/2011/returning-a-body-content-with-400-http-status-code/

A: Web API can handle this in various ways, but if you want to stick to ASP.NET MVC then use the code below:
 Response.StatusCode = 500;
 Response.TrySkipIisCustomErrors = true;
 return Content("Error description goes here.", "text/plain");

A: Check out MVC 4 Beta, there is a new feature called Web API that will help you solve this issue.


text:
Q: Understanding digital MEMS microphone sensitivity and obtained bits for a given input SPL I'm trying to understand /simulate the communication between 2 smartphones by means of ultrasounds. As this is a general study I'm considering that the smartphones are equipped with the "typical" most common kind of transducers. One of them is broadcasting a sound and the other recording it. I would like to know under what conditions is the transmitted sound properly recorded. The first thing I did was trying to understand how directivity at this frequency affected the transmission. You can see that analysis here .
Now I'm trying to understand the technical parameters in the MEMS digital microphone and microspeaker (the kind of sound transducers most commonly used in smartphones). I'll assume that the transmitting smartphone is equipped with a speaker of  this type and that the receiver is equipped with a microphone of this type.
In the speaker specification I can see :
Rated Input Power : 0.5W(2.0Vrms)
S.P.L : 83±3dB/0.1m/0.1W at 0.8,1.0,1.2,1.5KHz average

The speaker frequency response is:

In the microphone specification I can see :
Sensitivity : 94 dB SPL at 1 kHz : -26 dBFS
The microphone frequency response is:

My questions are:

*

*Is the sensitivity the difference between maximum acoustic signal (maximum SPL) at the mic input (which causes full-scale digital word, 16 bits? ) and the 94 dB SPL reference? So, if the mic sensitivity is –26 dBFS at 94 dBSPL, is maximum SPL 120 dBSPL? (–26 dBFS  = 94 dBSPL – 120 dBSPL) Is it alright to mix dBFS and dBSPL ?

*This is a PDM smartphone so it's output is only 1 bit. But if we assume that after proper conversion we obtain a 16 bit when the maximum acoustic signal (120 dBSPL) is being received, at 94 dBSPL will its output be about 11 bits?

*Assuming that we are working at 1 kHz if the speaker generates 83±3 dBSPL at 10 cm and we place the microphone at this distance, how many useful bits will it output?

*What can I do to find out the speaker generated SPL when it is supplied with 0.5W (instead of 0.1 W which is the only data given)?

*What can I do to find out the speaker generated SPL and microphone sensitivity at, lets say, 18 kHz?

*If mic SNR is 64.5 dB. How many useful bits above the noise floor can it work with?

A: *

*The mems microphone produces a digital signal and when the incident RMS pressure is 94 dB SPL, the digital signal has an RMS level of -26 dBFS. If the positive full scale is (say) \$2^{15}\$ or 32,768 then the digital RMS level is 26 dB down on this at 1,642. This will be at 1 kHz.

*1,642 is an RMS number so the full peak-to peak value (for a sinewave) is 4644 LSbs. This cannot be represented by signed number less than 12 bits (13 bits including sign).

*83 dB SPL is 11 dB down on 94 dB SPL hence the RMS digital signal level will be 11 dB down on 1,642 i.e. 463. Because you are using a sine wave this translates to a peak-to-peak reading in digital counts of 2.828x higher or 1309 counts p-p.

*0.5 watts is 5 times more power than 0.1 watts or an increase of 3.16 dB and, accordingly, the SPL will be 3.16 dB higher and ditto the digital signal produced.

*I have no clue on this because I don't know the frequency responses of either speaker or microphone nor the ambient acoustics.

*This is tricky to predict because if the equivalent noise is 100 counts RMS (gaussian) then there will be a 99.9% probability it will be within a digital level of 660 digital counts p-p (see below). What is an acceptable level only you can decide.

Gaussian noise and probability: -

A: A communication link's success depends on SNR. Narrowband links can greatly improve the SNR. Simple on-off modulation needs SNR of 10dB for 0.1% bit error rate (depends on bandwidth, but good rule-of-thumb); thus 2 bits or 3 bits will suffice for OOK.
For 16_QAM, with 4 bits per symbol, where a settled-amplitude is needed, you need more accuracy and more time to settle to recognizable point in the constellation.
Regarding your question, if the receiver microphone digitizer has a fixed floor,
then dropping the power 6dB (2*2, at 3dB per power ratio of 2) produces 6dB worse SNR (lower SNR).
From your question, if 16 bits at 120dBSPL, then 26 dB lower at 94dB would cost 4+ bits.
Yes----dbFullScale are dB/dB comparable to dBSPL.


text:
Q: ${\displaystyle \int_0^1 \dfrac{1}{x} \cdot \dfrac{1}{1-x} \cdot \left(1-\dfrac{1}{x} \right) \mathrm dx}$
Evaluate
$$\displaystyle \int_0^1 \left\{\dfrac{1}{x}\right\} \cdot \left\{\dfrac{1}{1-x}\right\} \cdot \left\{1-\dfrac{1}{x} \right\} \mathrm dx$$
where $\{x\}$ denotes the fractional part of $x$.

A: This is one of those problems where it seems like there's only really one way we can start, but it ends up looking intractable. I'll offer what I can; maybe someone can spot how to evaluate this in closed form (or rigorously prove it's not doable), or efficiently do a numerical estimate.
Set $y=1/x,\,z=y-n$ for $n\in\Bbb N$ so the integral is$$\int_1^\infty\{y\}(1-\{y\})\{\tfrac{1}{y-1}\}\tfrac{dy}{y^2}=\sum_{n\ge1}I_n,\,I_n:=\int_0^1z(1-z)\{\tfrac{1}{z+n-1}\}\tfrac{dz}{(z+n)^2}.$$With $u=\tfrac1z$,$$I_1=\int_1^\infty\tfrac1u(1-\tfrac1u)\{u\}\tfrac{du}{(u+1)^2}=\sum_{m\ge1}J_m,\,J_m:=\int_m^{m+1}\tfrac1u(1-\tfrac1u)(u-m)\tfrac{du}{(u+1)^2}.$$In fact$$J_m=\int_m^{m+1}\tfrac{(1-u)(u+m)}{u^2(u+1)^2}du=\tfrac{6}{m+2}-\tfrac{3}{m+1}+(2-6m)\ln(m+1)+(3m-1)\ln(m(m+2)).$$For $n\ge2$,$$I_n=\int_0^1(\tfrac{n-n^2}{z+n-1}+\tfrac{n^2-n-1}{z+n}+\tfrac{n^2+n}{(z+n)^2})dz=(n-n^2)\ln\tfrac{n^2}{n^2-1}-\ln\tfrac{n+1}{n}+1.$$So the original integral is$$\begin{align}I&:=\sum_{m\ge1}(\tfrac{6}{m+2}-\tfrac{3}{m+1}+(2-6m)\ln(m+1)+(3m-1)\ln(m(m+2)))\\&+\sum_{n\ge2}((n-n^2)\ln\tfrac{n^2}{n^2-1}-\ln\tfrac{n+1}{n}+1).\end{align}$$You'll want to double-check I didn't make any mistakes in this, mind.

A: Since $\{1 - \frac{1}{x}\} = \{-\frac{1}{x}\} = 1 - \{\frac{1}{x}\}$, we have
\begin{align}
I &= \int_0^1 \{\tfrac{1}{x}\}\{\tfrac{1}{1-x}\} (1 - \{\tfrac{1}{x}\})\mathrm{d}x \\
&= \int_0^1 \{\tfrac{1}{x}\}\{\tfrac{1}{1-x}\} \mathrm{d}x
- \int_0^1 \{\tfrac{1}{x}\}^2\{\tfrac{1}{1-x}\} \mathrm{d}x.
\end{align}
From 2.10 and 2.12 (page 101) in [1], we have
$$\int_0^1 \{\tfrac{1}{x}\}\{\tfrac{1}{1-x}\} \mathrm{d}x = 2\gamma - 1$$
and
$$\int_0^1 \{\tfrac{1}{x}\}^2\{\tfrac{1}{1-x}\} \mathrm{d}x = \frac{5}{2} - \gamma - \ln (2\pi)$$
where $\gamma $ is Euler-Mascheroni constant.
Thus, we have $I = 3\gamma - \frac{7}{2} + \ln (2\pi) \approx 0.069524062$.
Also, I approximated the integral numerically in Maple which resembles the analytic result above.
Reference:
[1] Ovidiu Furdui, "Limits, Series, and Fractional Part Integrals: Problems in Mathematical Analysis".


text:
Q: Deoloy nuxt app to digitalocean vps server I've nuxt app and I want to deploy it to digitalocean
I've made a new folder on the server and call it control-panel
here's the folder sturcture I've
- control-panel
-- .nuxt
--- dist
---- client
---- server
-- node_modules
-- static
-- package.json
-- nuxt.config.js

but when I run npm run start and go to localhost:3000 it doesn't work
is there anything wrong in my folder structure ?


text:
Q: Angular Display alert inside *ngIf when  is empty in every table row must be checked When any td is empty in any row it should display alert but my problem is if altleast one td has data and other td is empty it considers the length<0
Alert:
this is alert which will be displayed when td is empty
<div *ngIf="isNotExissted">
    You will be required to add VAT on every address. If you are exempt,
</div>

TD:
<td class="col-md-2 supplier-address-types">
    <div *ngFor="let tNumber of item.taxNumber">
        {{ tNumber }}
    </div>
</td>

Typescript:
(item.taxNumber || []).forEach((checkNumber: any) => {
    if(checkNumber.taxNumber==null || typeof(checkNumber.taxNumber)=='undefined') {
        this.AllVatDataAvailable = false;
        this.taxArray1.push(this.AllVatDataAvailable);
    }
    console.log(this.taxArray1)
    if( this.taxArray1.length>0) {
        console.log("from seven four");
        this.isNotExissted = false;
    }
 });

A: you can directly use *ngIf to specific list to check below way
 <div *ngIf="item.taxNumber.length > 0">
    You will be required to add VAT on every address. If you are exempt,
 </div


text:
Q: Does ProjectCollection.GlobalProjectCollection only contains C# project? When I use ProjectCollection.GlobalProjectCollection to get a specified VC++ project in my VS extension development, it returns null. When I debug into the GlobalProjectCollection , I found it only contains C# projects(there are both C# and VC++ projects in my solution). Does ProjectCollection.GlobalProjectCollection only contain C# project? How can I get my VC++ projects?

A:
Does ProjectCollection.GlobalProjectCollection only contains C# project?

Not exactly. According to the ProjectCollection.GlobalProjectCollection Property:
It applies to .NET Framework 4.7.2~ 4.0, not only for C#:

To get all projects in the solution, you can try to check this thread and this thread for some more details.
Hope this helps.


text:
Q: Error LNK1561: entry point must be defined - making own library I am working with Visual Studio 2013 Pro.
My Solution has 3 projects
projectA

projectB

projectC

and the Hierarchy is like
projectB and projectC depend on projectA. There is a main function in projectA and no main in projectB and projectC. projectA is compiling as a library and contains a few functions as entry-points for projectB and C, and those are linking properly.
There is no main in projectB or projectC, projectA has an int main, and there are extern functions declared in projectA for the other two to define, and the linker accepts the defined extern functions.
I am getting this error:
error LNK1561: entry point must be defined

Any help would be appreciated

A: It compiles, but does not link, therefore you cannot run your application to begin debugging it
For a Win32, the entry point is WinMain().

*

*Right-click the Project (not the Solution) on the left side.

*Then click Properties -> Configuration Properties -> Linker -> System

If it says Subsystem Windows your entry point should be WinMain(), i.e.


text:
Q: simpler way to breakdown string sql server I have this function below I am breaking down a string like for example
string = '100001|125000,50001 - 75000' end result table below is there a simpler way to do this?
     low     high
     100001  125000
     50001   75000

ALTER FUNCTION [dbo].[GetRange] (@String varchar(max))
returns @temptable TABLE (low int, high int)
as
begin

declare @separated table(items varchar(max))

insert into @separated select * from dbo.Split(@String, '|')

update @separated
set items = items + ',2147483647'
where charindex(',', items) = 0

insert into @temptable
select left(items, charindex(',', items) - 1)
     , right(items, len(items) - charindex(',', items))
       from @separated
return
end

A: Well... you can remove the split function and replace it with a UNION and it may be faster. This would eliminate your function, and the nested function. I guess it depends on your use case. At a minimum it removes your dbo.Split function which hopefully is based off considerations from this article. but if it isn't, it could be real slow.
declare @table table (a varchar(4000))

insert into @table (a) values
('100001|125000,50001 - 75000'),
('101321320001|1250132100,52130001 - 755000')

select
    left(left(a,charindex(',',a) - 1),charindex('|',left(a,charindex(',',a) - 1)) - 1) as Low
    ,right(left(a,charindex(',',a) - 1),len(left(a,charindex(',',a) - 1)) - charindex('|',left(a,charindex(',',a) - 1))) as High
from @table
union all
select
    left(right(a,len(a) - charindex(',',a)),CHARINDEX('-',right(a,len(a) - charindex(',',a))) - 1)
    ,right(right(a,len(a) - charindex(',',a)),len(right(a,len(a) - charindex(',',a))) - charindex('-',right(a,len(a) - charindex(',',a))))
from @table

A: Note: this is assuming the Delimiter is a comma AND ranges may be split with a | or a dash.  You may notice that the dash is replaced with a | for consistency.
CREATE FUNCTION [dbo].[TestFunction] (@String varchar(max))
Returns Table
As
Return (
    Select Low  = try_convert(int,Left(RetVal,charindex('|',RetVal)-1))
          ,High = try_convert(int,Right(RetVal,charindex('|',reverse(RetVal))-1))
    From  (
            Select RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(500)')))
            From  (Select x = Cast('<x>' + replace((Select replace(replace(@String,'-','|'),',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
            Cross Apply x.nodes('x') AS B(i)
          ) B
)

Select * from [dbo].[TestFunction]('100001|125000,50001 - 75000')

Returns
Low     High
100001  125000
50001   75000


text:
Q: DisposeBag memory leak? I inherited a project that uses disposeBags everywhere, but disposeBag seems to be a massive memory leak. None of the view controllers utilizing the bag ever get deallocated, which leads to subscriptions piling up. I'm
class TestViewController: UIViewController
{

    @IBOutlet weak var testLabel: UILabel!
    var basePresenter: BasePresenter = BasePresenter()
    var disposeBag: DisposeBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        bindPresenter()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        //self.disposeBag = DisposeBag()                 <------------
    }

    func bindPresenter() {
        //super.bindPresenter()
        basePresenter.testVariable.asDriver().drive(onNext: { test in
            if !test.id.isEmpty {
                self.testLabel.text = "Test text"      //<------------
            }
        }).addDisposableTo(disposeBag)
    }

    deinit{
        print("TestView was dealloc'd")
    }
}

The key issue is the reference in the handler to "self."
My theory is that self is a strong reference, which is leading to a situation where even when the view controller gets popped and there are no other references to the view controller, it still doesn't get deallocated because the bag has a strong reference to it. Circular logic where the bag doesn't get disposed because the VC doesn't dealloc and the VC doesn't dealloc because the bag doesn't get disposed.
The commented out line
//self.disposeBag = DisposeBag()

when called allows for the view to properly dealloc.
On top of the memory leak, the issue that I'm facing is that I don't want to dispose the bag on viewWillDisappear, but rather when the view is popped. I need it to stick around if I add a view on top in case I pop back to this view.
Any help would be greatly appreciated!

A: Your theory is correct. You need to use a weak or unowned reference to self in your subscribe methods rather than a strong reference. And get rid of the assignment to disposeBag in the viewWillDissapear. The disposeBag will properly dispose of your subscribers when the object gets deinted.
You setup a weak reference to self like this:
   basePresenter.testVariable.asDriver().drive(onNext: { [weak self] test in
        if !test.id.isEmpty {
            self?.testLabel.text = "Test text" // no longer a strong reference
        }
    }).disposed(by: disposeBag)


text:
Q: How to get the actual type of primitive type parameter in Scala Seq[T] or Option[T]? For example if I have a class NewClass(val a: Seq[String]), I'm able to get the actual type of the type parameter by classOf[NewClass].getDeclaredFields.head.getGenericType.asInstanceOf[java.lang.reflect.ParameterizedType].getActualTypeArguments.head.asInstanceOf[Class[_]] which is a java.lang.String.
However, if the type parameter is a primitive type (which is not allowed in Java, but allowed in Scala), such as class NewClass(val a: Seq[Int]), using the same approach would only yield java.lang.Object. Is there any way for me to know that it's actually an Int instead of the general java.lang.Object?

A: Can you use the manifest?
scala> class NewClass[T](val a: Seq[T])(implicit m: Manifest[T])
defined class NewClass

scala> class NewClass[T](val a: Seq[T])(implicit m: Manifest[T]) {
     |   def typeOfA = m.erasure
     | }
defined class NewClass

scala> val newClass = new NewClass(Seq(1, 2, 3))
newClass: NewClass[Int] = NewClass@494e1df7

scala> newClass.typeOfA
res17: java.lang.Class[_] = int

A: If you define a version like below it will work for all classes that have one type parameter.
scala> def f[F[_],A](a: F[A])(implicit m:Manifest[A]) = m.erasure
f: [F[_], A](a: F[A])(implicit m: Manifest[A])java.lang.Class[_]

scala> f(Option(1))
res4: java.lang.Class[_] = int

scala> f(List(1,2,3))
res5: java.lang.Class[_] = int

scala> f(new NewClass(Seq(1, 2, 3)))
res6: java.lang.Class[_] = int

scala> f(new NewClass(Seq(1, 2, 3)).a)
res8: java.lang.Class[_] = int


text:
Q: Using pexpect to control kpcli I am trying to automate ssh connectivity using keepassdb and I am just starting out the script to interrogate the keypass kpcli shell. I want it to print out the result at the end.
# -*- coding: utf -*-
import os,sys
import pexpect
global str
db_kp='/media/sf_VM_shared/passwords.kdb'
pass_kp='KDBPASSWORD'
kp = pexpect.spawn('/usr/bin/kpcli')
kp.expect('>')
kp.sendline=('open /media/sf_VM_shared/passwords.kdb')
kp.expect=('Please provide the master password:')
kp.sendline=(pass_kp)
kp.expect('>')
kp.sendline=('cd General/Network/Firewalls/SSH/')
kp.expect=('kpcli:/General/Network/Firewalls/SSH>')
kp.sendline=("show -f 0")
print(kp.before)

I am getting the following when trying to run the file:
python3 ssh_firewall.py
Traceback (most recent call last):
File "ssh_firewall.py", line 12, in <module>
kp.expect('>')
TypeError: 'str' object is not callable

A: On this line:
kp.expect=('Please provide the master password:')

You're replacing the expect function, rather than calling it. Take the = out:
kp.expect('Please provide the master password:')

You're doing the same thing with kp.sendline, so you'll need to fix that as well.


text:
Q: Overlap or confusion in terminology describing predicates and complements?
[The source] is about the completers of thoughts, it is appropriate
  to include a brief description of complements. A complement
  (...) is any word or phrase that completes
  the sense of a subject, an object, or a verb. As you will see, the
  terminology describing predicates and complements can overlap and be a
  bit confusing. Students are probably wise to learn one set of terms,
  not both.
● A subject complement follows a linking
  verb; it is
  normally an adjective or a noun that renames or defines in some way
  the subject.
  ● Adjective complements = predicate adjectives.
  ● Noun complements = predicate nouns = predicate nominatives. See
  predicates,
  above.
  ● An object complement follows and modifies or refers
  to a direct object. It can be a noun or adjective or any word acting
  as a noun or adjective.
   ● A verb complement is a direct or
  indirect object of a verb. (See
  above.)

Comparing predicates vs complements, what else overlap[s] or is confusing? I simplified the exposition above and want to master both sets of terms (for predicates and complements).

A: The text in the link is titled "Predicates, Objects, Complements" and has three sections. When it gets to discuss complements, it simply states that predicates can sometimes be considered to be complements and vice versa. This means there is some overlapping in the definitions.
People who study grammar often want clear definitions that can lead to right/wrong decisions. With overlapping definitions, there may be more than one correct answer. This may lead to confusion.
Personally, I think natural languages (and English in particular) are too powerful to be covered by a finite set of rules (especially rules stated in a natural language...) Ambiguity is unavoidable; we should tolerate it.

A: A complement is "additional data" used by something.  If English was turned into a programmer's API, complements would be function or operator parameters.
There's a number of things in English that take complements or can be complements to other things.  For example, transitive verbs need objects, so the words and structures that express those objects are "object complements" to those verbs.
I think predicate is pretty much a fancy term that means "anything in the sentence that is not the subject or directly modifies the subject."

My big brother got lost in the park while he was wandering around like a dummy.  (Subject = "My big brother", predicate = "got lost in the park while he was wandering around like a dummy")

Note that sentences like these:

She is beautiful

"She" is the subject and "is beautiful" is the predicate.  To be and similar verbs don't "directly" modify the subject, that's why beautiful here is called a "subject complement" (and it's not an object or "object complement" either).


text:
Q: How to check for a value in array with Javascript with text input I would like to check for a value in an array using a text input. If the value is present in the array, I want to show the user a text.
My question:
Is there a way to don't use jQuery?
Here is what I got up to now:
http://jsfiddle.net/t8r5eLxb/
$(document).ready(function(){
    var recherche ="";
    var liste = ["Ariat", "Wrangler", "turtles"];
    var sorted = [];
    for (var i = 0; i < liste.length; i++) {
        sorted.push(liste[i].toLowerCase());
    }
    sorted.sort();

$("#filter").keyup(function(){
    var recherche = $(this).val();

// Résultat
var resultat = (sorted.indexOf(recherche.toLowerCase()) > -1);

    if( $(resultat).text().search(new RegExp(filter, "i")) < 0 ){
        $('#resultat').fadeIn();
    }
    else{
        $('#resultat').fadeOut();
    }

});
});

<form id="live-search" action="" method="post">
   <fieldset>
       <input type="text" class="text-input" id="filter" value="" />
   </fieldset>
</form>

Vrai

A: Sure you can avoid jQuery, which is also written in pure JavaScript.
Since you only need to check if input text matches any string in the predefined array, you can bypass the sort operation and go directly to comparison.
There are some event handler existed in pure JS, like onkeyup, which is pretty handy for input retrieval.
Fade in and out effect can be rendered with CSS transition and opacity, as shown in the

    <form id="live-search" action="" method="post">
        <fieldset>
            <input type="text" id="filter" value="">
        </fieldset>
    </form>

Vrai

The <form> tag in this demo, actually, is not necessary. You can just keep <input> and
 tags and get the same result.

A: I've re-written the jQuery lines of your code in vanilla JavaScript. Please see the comments for what is happening. // ... means I've skipped ahead
function node_show(node) { // $(node).fadeIn, without fade :(
    node.style.display = 'block';
}

function node_hide(node) { // $(node).fadeOut, without fade :(
    node.style.display = 'none';
}

window.addEventListener('load', function (e) { // $(document).ready
    document.getElementById('filter') // $("#filter")
        .addEventListener('keyup', function (e) { // .keyup
            var recherche = this.value; // $(this).val();
            // ...
                node_show(document.getElementById('resultat'));
            // ...
                node_hide(document.getElementById('resultat'));
            // ...
        });
});

A: Well I believe I got you right and this how I interpreted your question.
So I will just write few lines of codes how i would have gone about that.

window.addEventListerner("DOMContentLoaded", (e)=>{
 let itemsArr = ["subaru", "rangerover", "bmw", "voxwagen"];
 let userInput = document.querySelector("input[type=text]").value;
 if(itemsArr.includes(userInput)){
 console.log ("my text to user")
 }
});

<form>
 <input type="text">
</form>


text:
Q: PHP iterate each line but count them So currently I have a contact text area  which have an icon only in the second and third line.
I was trying to add a condition to each line but seems like this is not the way, could someone help me out in achieving the result?
$getc = $connect->query("SELECT * FROM contactos WHERE id = 1");
$contacto = $getc->fetch_array(MYSQLI_ASSOC);
$subject = $contacto['texto'];
foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    for ($x = 1; $x <= 5; $x++) {
        if($x == 1){
             echo '
'.$line.'
';
        }else if($x == 2){
            echo '
 '.$line.'
';
        }else if($x == 3){
            echo '
 '.$line.'
';
        }else{
             echo '
'.$line.'
';
        }
    }
}

A: So you want to print only third and fourth line. We need to change your code a little bit:

$getc = $connect->query("SELECT * FROM contactos WHERE id = 1");
$contacto = $getc->fetch_array(MYSQLI_ASSOC);
$subject = $contacto['texto'];

$x = 1;
foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    if($x == 1){
         echo '
'.$line.'
';
    }else if($x == 2){
        echo '
 '.$line.'
';
    }else if($x == 3){
        echo '
 '.$line.'
';
    }else{
         echo '
'.$line.'
';
    }
    $x++;
}

So as you see you need to count foreach iteration. Another loop inside it won't do anything good.


text:
Q: How to animate width using inline css I'm trying to animate a width of an element using data from an API upon page load and I'm using Vue js. What I've done is I used inlined css and apply width value (from API data). I'm able to add the element width but it has no animation.
Vue template edited:

            {{stats}}

Sass:
.bar {
    span {
        text-align: $l;
        right: 0;
        width: 0%;
        -webkit-transition: width 1s;
        -moz-transition: width 1s;
        -o-transition: width 1s;
        transition: width 1s;
    }
}

A: You'll probably need to use the JavaScript transition hooks. Here's an example.

new Vue({
  el: '#app',

  data: {
    stats: [],
  },

  created() {
    // Simulate loading data from server
    setTimeout(() => {
      this.stats = [0.1, 0.15, 0.32, 0.55, 0.88, 0.96];
    }, 500);
  },

  methods: {
    onEnter(el) {
      var stat = +el.dataset.stat;
      var index = +el.dataset.index;
      el.style.transitionDelay = index * 0.05 + 's';
      el.style.width = (stat * 100) + '%';
      el.style.backgroundColor = `hsl(${50 - 50 * stat | 0}, 100%, 50%)`;
    },
  },
});
.bars {
  width: 400px;
}

.bar {
  margin: 5px 0;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  color: white;
  font-family: sans-serif;
  font-weight: bold;
  padding: 5px;
  box-sizing: border-box;
  white-space: nowrap;
  overflow: hidden;
}

.bar.v-enter-active {
  transition: all 1s cubic-bezier(0, 1, 0.5, 1);
}

.bar.v-enter {
  /* Needs !important to override inline styles */
  opacity: 0;
  width: 0% !important;
  background-color: hsl(50, 100%, 50%) !important;
}

  <transition-group tag="div" class="bars" @enter="onEnter">

      {{ (stat * 100 | 0) }}%

  </transition-group>


text:
Q: Rebol 2 disable console echo I have a Rebol2 console app (Rebol Core) which I would like to disable the keyboard character echo to the console. The app is run from a minimal Linux kernel/initramfs, and is started by busybox inittab (not from terminal). It has a minimal console user interface using ansi codes for color, etc., and responds to menu selections via single key presses. To 'quiet' the console, I have the cursor turned off, and don't see the output of the key presses (until recently).
I previously thought I had the problem solved by calling 'stty -echo' within Rebol, but it actually does not work as I just discovered- there is one function that takes 5-10 seconds and can see the echoed key presses while waiting for the function to complete.
I'm not quite sure why I only see the echoed characters while this one function is running, but it is the only function which takes any amount of time. The keyboard is polled by opening the console:// in binary mode, waiting for a key press, then a switch statement to choose the function. The reading of the keys in binary/console seem to 'consume' the key echo-
minimal example, pressing 'a'-

    cons: open/binary console://
    first cons
    == 97

(the value is returned as I want, and the char is not echoed, which is good- I think in most functions my keys are 'consumed' in the get-key loop, but the longer function does not get a chance to 'consume' them, and end up echoing to the console)
Is there some way to disable the console character echo inside Rebol2? I have looked in system/console and system/ports/input,output, but don't see anything obvious. My current workaround is to simply change the text color to match the background so any key presses are not visible while the specific function runs.
here is a minimal example of what I'm doing-
get-key: func [ /local cons ch ][
    cons: open/binary console://
    ch: lowercase to-string to-char first cons
    all [ equal? ch "^["   append ch copy/part cons 2 ]
    close cons
    ch
]

forever [
    switch get-key [
        ;up arrow
        "^[[A" [ some-function1 ]
        ;down arrow
        "^[[B" [ some-function2 ]
        ;enter
        "^M" [ some-function3 ]
        ;quit
        "q" [ break ]
    ]
]

The forever loop seems to 'consume' the keyboard input (nothing echoed), but if one of the functions takes any amount of time, any keyboard input will get echoed to the screen wherever the cursor happens to be. In most cases I never see any echoed characters as the time between calling get-key is minimal. I would also note that the echoed characters do not also show up in the subsequent call to get-key.
update-
here is a better sample of code to see the problem-
get-key: has [ cons ch ][
  cons: open/binary console://
  ch: lowercase to-string to-char first cons
  prin rejoin [ "<" ch ">" ] ;show get-key chars
  ch
]
long-func: does [ call/wait {sleep 10} ]
reb-func: does [ wait 10 ]

forever [
  switch get-key [
   "f" [ long-func ]
   "r" [ reb-func ]
   "q" [ break ]
  ]
]

I figured out that my 'long' function is using call's which can take a few seconds, so the problem arises when a call is used.
The above code, when run will show that keys are echoed only because they are printed in the get-key function  (brackets), when the long-func is running, then keys are echoed outside of get-key (no brackets), and when done the get-key will process those keys also. Or simply run 'call/wait {sleep 10}' and you will get echoed keys while waiting, and also get the sames keys echoed by Rebol when the call returns. Keys are not echoed when reb-func runs, and get-key will process all buffered keys when reb-func is done. The keyboard input is being handled twice when call is used.
I have tried redirecting stdin/stdout in the call command (in the call string command, like at bash prompt), but have not found a combo that works. (My actual code runs call with /output/error to capture all output).

A: Without optimizing your code with waiting on the port and an awake function I guess your problem can be solved by placing opening and closing the console port outside your get-key function as in
get-key: func [ /local ch ][
    ch: lowercase to-string to-char first cons
    all [ equal? ch "^["   append ch copy/part cons 2 ]
    ch
]
cons: open/binary [scheme: 'console]
forever [
    switch get-key [
        ;up arrow
        "^[[A" [ some-function1 ]
        ;down arrow
        "^[[B" [ some-function2 ]
        ;enter
        "^M" [ some-function3 ]
        ;quit
        "q" [ break ]
    ]
]
close cons

ok, here is an optimized version including your second example
long-func: does [ call/wait {stty -echo ; sleep 10} ]
reb-func: does [ wait 10 ]

 cons: open/binary [scheme: 'console]
 cons/awake: func [port] [
    key: to-char first port
    print ["<" key ">"]
    switch key [
        #"f" [long-func]
        #"r" [reb-func]
        #"q" [break]
    ]
 ]
forever [
    wait [cons]
]

you can see, that all keys are catched without extra echo

A: The rearranged console code is not necessary (and all keys are cached no matter which arrangement is used), although the ability to add an awake function is nice to know. In my real code, the get-key has a '/timeout t' option where I can do a 'wait [ cons t ]' and return a string (for extended key codes like up arrow) or none, which means I can also flush the console input before my switch get-key (so any keys pressed while running functions get flushed).
forever [
  while [ get-key/timeout 0.1 ][] ;flush
  switch get-key [ ;wait for key
...

The 'stty -echo' works well in the example given, and would seem to solve my problem, but I still see a few characters echoed if I press a bunch of keys while the long functions are running (I inserted {stty -echo; } in all commands). Somehow, in the Rebol call creating of processes (fork/exec I assume), tty input/output can still 'leak' i/o characters. Or maybe one of the programs called is opening a tty even though it inherits the file descriptors of the parent.
Here is what I ended up doing- changing the way I call commands so they run in background, but still wait for them to complete.
;used by other funcs to parse output of commands
set 'cmd-output "" ;output from 'call' commands
set 'cmd-error "" ;error from 'call commands

set 'cmd func [ str [string!] /local ret ][
  --old--
  ;clear previous
  cmd-output: copy ""
  cmd-error: copy ""

  ;--new--
  write %out ""
  write %err ""
  attempt [ delete %ret ]

  ;--old--
  ;ret: call/wait/output/error str cmd-output cmd-error

  ;--new--  stdout->out stderr->err exitcode->ret
  call rejoin [ str { >out 2>err; echo -n $? > ret} ]
  ;wait for return code, (up to 20 seconds, should be plenty)
  loop 200 [ all [ exists? %ret  break ] wait 0.1 ]
  cmd-output: read %out
  cmd-error: read %err
  ret: to-integer read %ret

  --old--
  ;debug-cmd writes info to a logfile
  debug-cmd str ret
  ret
]

This works, as I cannot get any (unwanted) characters to show on the screen as before (and I guess it proves those characters were coming from the called processes).


text:
Q: Minimize VirtualBox Hard Drive disk I have Ubuntu Server 10.04 TLS installed on a Virtual Machine in a VirtualBox.
The size of the Hard Drive is dynamic growing hard drive and the maximum is 32GB.
At the beginning i had 4GB on the Hard Drive and the size of the .vdi was 4GB.
Lately the size of data on the disk is 15GB but the size of the .vdi is almost 32GB.
Why is that?
How can i pack / optimize / defrag the HD so it will be the same size of the data on the disk?
Thanks.

A: The reason is that the dynamic disk stores all data, even data that was just temporary and now unlinked. The VBoxManage executable has a command, modifyvhd, which can perform compaction of hard disk images:
VBoxManage modifyhd Ubuntu.vhd --compact

This should get you back down close to the 15GB file size, and might even give you a small performance boost (less data to read / search through). If you really want to optimize the disk you can start by writing zero to the free space, then compacting. This will force the filesystem to free up any blocks that might still be held.
cat /dev/zero > zero ; sync ; rm zero

Additional reference: http://www.virtualbox.org/manual/ch08.html - see the modifyvhd section, specifically the --compact option.

A: You could use Clonezilla to clone the disk to an new VDI.  I've used it successfully recently for Linux & WIndows volumes.  I can't say for certain that it will recoup the space but there is no garm in trying.

*

*Use VBox to create a new volume

*Attach volume to vm

*Boot to Clonezilla Live CD

*Clone current disk to new

*after verifying results, remove original, and new disk to same attachpoint

*Boot vm and test


text:
Q: Affiliations on single line with RevTeX-4.1 I wonder if there is an easy way to get all affiliations on one line with RevTeX-4.1.

A: There is no easy way.  You have to modify an internal macro.  Also it will look really ugly.  Don't do that.
\documentclass[superscriptaddress]{revtex4-1}

\makeatletter
\def\@affil@script#1#2#3#4{%
 \@ifnum{#1=\z@}{}{%
  %\par % <--- comment out
  \begingroup
   \frontmatter@affiliationfont
   \@ifnum{\c@affil<\affil@cutoff}{}{%
    \def\@thefnmark{#1}\@makefnmark
   }%
   \ignorespaces#3%
   \@if@empty{#4}{}{\frontmatter@footnote{#4}}%
   %\par % <--- comment out
  \endgroup
 }%
}%
\makeatother

\begin{document}

\author{John Doe}
\affiliation{University of Neverland, Road to Nowhere 123, 12345 Nevercounty}
\author{Jane Smith}
\affiliation{Bogus Institute of Something, Madeup Place 654, 65432 Anywhere}

\maketitle

\end{document}

A: I 'solved' this myself by adding my list of affiliations as a single author with linebreaks, \textit and \sciptsize

\documentclass[superscriptaddress]{revtex4-1}
\usepackage{lipsum}
\begin{document}
\title{A Potential Solution}
\author{A. Whoever\textsuperscript{1} and B. Wohever\textsuperscript{2}\endgraf
\scriptsize\itshape \textsuperscript{1}The University of Instant
Gratification, More address \quad \textsuperscript{2}The University of Instant
Gratification, More address\\ }
\maketitle\lipsum[1-20]
\end{document}


text:
Q: Lebesgue Integral of $\sin(x)/x$ using the Monotone convergence theorem How can I show using the monotone convergence theorem that the Lebesgue integral $$\int_{0}^\infty\frac{\sin(x)}x\,dx$$ does not exist?

A: Recall that $f$ is (Lebesgue) integrable if and only if $|f|$ is Lebesgue integrable. Now, we may write $$f_n(x) = \sum_{k=0}^n\frac{|\sin x |}{x}\chi_{[k \pi , (k+1)\pi]}$$ so that $f_{n} \leq f_{n+1}$ and $f_n \to f$ pointwise, where $f(x) = \frac{|\sin x |}{x}$. We may then estimate the integral of each term in the sum via:
$$\frac{2}{(k+1)\pi} = \int_{k \pi}^{(k+1)\pi} \frac{|\sin x|}{(k+1)\pi}dx \leq \int_{k \pi}^{(k+1)\pi} \frac{|\sin x|}{x}dx$$
So that by the monotone convergence theorem,
$$\begin{align*}
\int_0^\infty \frac{|\sin x|}{x}dx &= \lim_{n\to \infty} \int_0^\infty f_n dx \\
&\geq \sum_{k=0}^\infty \frac{2}{(k+1) \pi} \\
&= \infty
\end{align*}$$
Which implies that the Lebesgue integral of $\frac{\sin x}{x}$ does not exist.