Q:

How we can show this: $\sqrt{3+\sqrt{3}}-\sqrt{3-\sqrt{3}}=\sqrt{6-2\sqrt{6}}$

Only way in my mind to show that : $$\sqrt{3+\sqrt{3}}-\sqrt{3-\sqrt{3}}=\sqrt{6-2\sqrt{6}}$$   is to multiply $\sqrt{3+\sqrt{3}}-\sqrt{3-\sqrt{3}}$ by the conjugate factor which is $\sqrt{3+\sqrt{3}}+\sqrt{3-\sqrt{3}}$ such that we can get :$\frac{2\sqrt{3}}{\sqrt{3+\sqrt{3}}+\sqrt{3-\sqrt{3}}}$ then no simplification I can do after that , any way ?

A:

Note that $3 + \sqrt{3} > 0$ obviously and thus $\sqrt{3+\sqrt{3}} >0$. Again, obviously $\sqrt{3-\sqrt{3}} < \sqrt{3+\sqrt{3}}$ and thus the LHS is positive.
Also, $6-2\sqrt{6} >0 \Leftrightarrow 3 > \sqrt{6}$ which holds, as $3 = \sqrt{9} > \sqrt{6}$ as $f(x) = \sqrt{x}$ is a strictly increasing function.
This is important to show for a rigorous proof, as proceeding by squaring in another case would be wrong.
Now :
$$\sqrt{3+\sqrt{3}}-\sqrt{3-\sqrt{3}}=\sqrt{6-2\sqrt{6}} \implies \bigg(\sqrt{3+\sqrt{3}}-\sqrt{3-\sqrt{3}}\bigg)^2=\bigg(\sqrt{6-2\sqrt{6}}\bigg)^2$$
Can you now apply the standard formula $(a+b)^2 = a^2 + 2ab + b^2$ to show that the desired equality formula indeed holds ?


Q:

Is there a way to media-query if the window is taller than it is wide in css? (portrait vs landscape for any devices)

Is there a way to media-query if the window is taller than it is wide in CSS?
A sorta portrait vs landscape for any devices.
I know this is easy enough with javascript but I'm searching for a CSS only solution.

A:

This will select the devices which has width more than 320 and less than 767 and orientation will be landscape only.
@media screen and (min-width: 320px)and (max-width: 767px)and (orientation: landscape) {}

another example of you want to select by height and width combination:
@media (max-width: 320px) and (min-height: 400px) and (max-height: 812px) {}

althoug better use is using orientation in your case, as per the question


Q:

Access parts of Constructor that is in a vector

So lets say I have a vector of a type which contains an int, and 2 strings.
What would be the best way to pull ints or strings from my vector of my custom type, so I could compare them other objects?
I tried pushing back one vector into another of just an STL type, but I know that
vector<sometype> v;
vector<string> v2;
for(int i = 0; i<v.size(); ++i;)
{
    v2.push_back(v[i]);
}

won't work, and I'm not really sure how else to do it.

A:

Since you didn't provide sometype code I wrote example code on my own.
class sometype {
  int a;
  std::string b;
  std::string c;

public:
  friend bool operator==(const sometype& lhs, const sometype& rhs);
};

bool operator==(const sometype& lhs, const sometype& rhs) {
  if (lhs.a == rhs.a &&
      lhs.b.compare(rhs.b) == 0 &&
      lhs.c.compare(rhs.c) == 0) {

    return true;
  }

  return false;
}


Q:

jQuery checkbox select all and change background color on select

I have a table with checkboxes in the first column, and a "select all" checkbox in the header. When I check a checkbox, I need the row color to change.
var $tbl = $('#tbl');
var $bodychk = $tbl.find('tbody input:checkbox');

$(function () {
    $bodychk.on('change', function () {
        $(this).closest('tr').toggleClass('hilite');
    });

    $tbl.find('thead input:checkbox').change(function () {
        var c = this.checked;
        $bodychk.prop('checked', c);
    });
});

If you select the individual boxes, the row changes color
If you click the "select all" box, it'll toggle the other checkboxes.

But I can't get both working together. See here
These questions come close but don't fully answer what might be wrong...
Change class of tr if checkbox is selected
Jquery "select all" checkbox

A:

something like this?  http://jsfiddle.net/hb6cx0tn/9/
var $tbl = $('#tbl');
var $bodychk = $tbl.find('tbody input:checkbox');

$(function () {
    $bodychk.on('change', function () {
        if($(this).is(':checked')) {
            $(this).closest('tr').addClass('hilite');
        }
        else {
            $(this).closest('tr').removeClass('hilite');
        }
    });

    $tbl.find('thead input:checkbox').change(function () {
        var c = this.checked;
        $bodychk.prop('checked', c);
        $bodychk.trigger('change');
    });
});

i chose not to use toggle because it doesnt ensure that the checkbox is checked in order for the item to be highlighted.
the line $bodychk.trigger('change'); causes the .change() event to trigger so that you're just not adding a class to the element, you're actually triggering the checking of the element.


Q:

Particle System not working on Play()

I have a particle effect that I would like to trigger to play, and then stop. I'm sure this is an easy fix that I am over looking.
The particle can instantiate and play, but this obviously leaves overhead and particles that are active in the hierarchy when they don't need to be.
public void EmitFX(ParticleSystem particle)
{
   Instantiate(particle, particlePos, Qauternion.identity)
}

I would like to use methods within ParticleSystem but am running into some problems. I have been using the manual and am still running into a block. I've googled this up and down, based on problems others had I changed my code to the following. It still does not work and is now a monster based on hacks other people found useful :/
public void EmitFX(ParticleSystem particle)
    {
        particle = particle.GetComponent<ParticleSystem>();
        particle.transform.position = ballPos;

        var em = particle.emission;
        em.enabled = true;

        particle.Play();
    }

Here is a s/c of a particle in the Inspector.

A:

First of all, not sure what the particle = particle.GetComponent<ParticleSystem>(); line is supposed to do? The particle variable is the ParticleSystem provide to your EmitFX() method so no need to call for this.
My guess is you have some references problems in your script (some variables referring to your prefab, then what you instantiate overrides this reference, ...) so I wrote you a "cleaner" version of your code (by merging your two scripts):
#region Attributes
[SerializeField]
private ParticleSystem particle;

private ParticleSystem generatedParticle;
#endregion

#region MonoBehaviour
protected void Start()
{
    generatedParticle = null;
}

protected void Update()
{
    if(Input.GetKeyDown(KeyCode.Space))
    {
        EmitFX(particle);
    }
}
#endregion

public void EmitFX(ParticleSystem a_Particle)
{
    if(generatedParticle == null)
    {
        generatedParticle = Instantiate(particle, particlePos, Qauternion.identity);
    }

    generatedParticle.transform.position = ballPos;
    generatedParticle.Play();

    // You can set a fixed duration here if your particle system is looping
    // (I assumed it was not so I used the duration of the particle system to detect the end of it)
    StartCoroutine(StopFXAfterDelay(generatedParticle.main.duration));
}

private IEnumerator StopFXAfterDelay(float a_Delay)
{
    yield return new WaitForSeconds(a_Delay);
    generatedParticle.Stop();
}

What it does is it store the instantiated particle in a variable so it can access it later and remember it has been generated. Also I added a coroutine to deactivate it at the end of the effect.
Hope this helps,


Q:

Regular Expressions in AWK

I am trying to parse the following input using awk patterns:
Smith, Jim 12.34
12.34 Jim Smith
I have a pattern checking to see if the first field contains an alpha character the second field contains an alpha character and the third contains a number and a second pattern checking for the second case like so:
$1 ~ /[A-Za-z]/ && $2 ~ /[A-Za-z]/ && $3 ~ /[0-9]/{
do fun things with record
}
$3 ~ /[A-Za-z]/ && $2 ~ /[A-Za-z]/ && $1 ~ /[0-9]/
{
this is the second form of the record
}

however, my program appears to be passing both checks and executing both actions. I have been trying to figure out where I am messing up but the same thing keeps happening. Any points in the right direction is much appreciated. I know there are tons of ways to do this. A few of which I have found, but I would like to know specifically what I am doing wrong here.
I'm running CentOS 7 with awk:
gawk --version
GNU Awk 4.0.2

A:

The problem is the newline before the opening braces after the second pattern. This will work as expected:
$1 ~ /[A-Za-z]/ && $2 ~ /[A-Za-z]/ && $3 ~ /[0-9]/{
 print "do fun things with record"
}
$3 ~ /[A-Za-z]/ && $2 ~ /[A-Za-z]/ && $1 ~ /[0-9]/{ # NO newline here
 print "this is the second form of the record"
}

Explanation: An AWK program consists of a sequence of pairs pattern { action }, where either the pattern or the action can be omitted. Adding a newline between pattern and action will make awk parse that as a pattern with no action, followed by an action without pattern (i.e, an action that is executed unconditionally).
Bottomline: stick to  Egyptian Brackets in AWK.


Q:

Testing a variable against a set of other variables, one of which is NULL, returns false

I have this:
DECLARE @First INT, @Second INT, @Third INT

SET @First = 1
SET @Second = 2
SET @Third = NULL -- just for clarity

IF(@First NOT IN (@Second, @Third))
    BEGIN
        PRINT 'Here' -- expected this line to print...
    END
ELSE
    BEGIN
        PRINT 'There' -- but this line prints instead.
    END

Why does it enter the "else" block?  If I try it this way, I get the expected results:
IF(@First IN (@First, @Second, @Third))
    BEGIN
        PRINT 'Here' -- this line prints, as expected.
    END
ELSE
    BEGIN
        PRINT 'There'
    END

Why does a check to see if one value DOES NOT exist in a set of other values using IN, where one of those values is NULL, return false?
I'm sure someone is going to tell me that this is expected behavior for some esoteric, SQL-y reason, but I think we can all agree that this is a dangerous "default" likely to trip up the unwary.

A:

Classic example of NOT IN trap with NULL value. This is no esoteric just simple as:
@First IN (@Second, @Third)
<=>
@First = @Second OR @First = @Third

Now based on De Morgan's laws:

"not (A or B)" is the same as "(not A) and (not B)".

@First NOT IN (@Second, @Third)
<=>
@First <> @Second AND @First <> @Third

1 <> 2 AND            1 <> NULL => NULL
true AND NULL => NULL  -- go to the else branch

Mystery solved.


Q:

Load balancing with ASP.NET and ADFS

We're using ASP.NET MVC 5 with external authentication based on ADFS. Wea are using Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.
Now we want to use a second instance. The load balancer uses an own cookie to identify a user and to enable sticky sessions.
The problem now is, that the user is not authenticated when a second instance is attached to the load balancer.
I think it is a configuration issue of ADFS. Is there any option which could occurs this error here? Or any other help?

A:

Solution: Microsoft.IdentityModel uses Windows Data Protection API. This stored the token key inside the Windows DPAPI.
Problem: this cannot be synced with other machines because the encryption key is different on every machine.
You have to switch your provider to Security.IdentiyModel.


Q:

Linq add missing distinct values

I have some linq query that does the following:
...
CarsCategories = new ObservableCollection<CarsCategory>(y
                                        .GroupBy(x1 => new { a = x1.Field<string>("CategoryName") })
                                        .Select(z => new CarCategory
                                        {
                                            CategoryName = z.Key.a,
                                            CarGroups =  new ObservableCollection<CarGroup>(z
                                                .GroupBy(x1 => new { a = x1.Field<string>("GroupName") })
                                                .Select(z1 => new CarGroup
                                                    {
                                                        GroupName = z1.Key.a,
                                                        CarTests = new ObservableCollection<CarTest>(z1
                                                            .GroupBy(x2 => new { a = x2.Field<string>("TestName") })
                                                            .Select(z2 => new CarTest
                                                            {
                                                                TestName = z2.Key.a,
                                                                CarTestNumbers = new ObservableCollection<CarTestNumber>(z2
                                                                    .Select(z3 => new CarTestNumber
                                                                    {
                                                                       TestNumber = z3.Field<String>("TestNumber"),
                                                                       TestVisitCode = z3.Field<String>("TestVisitCode")
                                                                    }))

                                                            }))
                                                    }

                                        ))}))
...

Basically I have a big table which is grouped by CarCategory, and then by CarGroup, and then by CarTest and each CarTest has multiple TestNumber and TestVisitCode params.
Everything is working as expected, but I would like to do the following:
All the tests inside this table have different TestVisitCode values. I would like that for each test inside my grouped category CarTestNumbers, to have all of the distinct TestVisitCode present in the table, and where I have a value to show it, otherwise show an empty string.
My CarTestNumber model looks like this:
public class CarTestNumber
    {
        public string TestNumber { get; set; }

        public string TestVisitCode { get; set; }

        public string VisitCodeAndTestNumber
        {
            get { return TestVisitCode +" - " +  TestNumber; }
        }

    }

For now I only show existing TestVisitCode and TestNumber.
For example:
Row1: CategoryName - FirstCategory GroupName - FirstGroup TestName - "FirstTest" TestNumber - "12" TestVisitCode - "W1"
Row2: CategoryName - FirstCategory GroupName - FirstGroup TestName - "FirstTest" TestNumber - "13" TestVisitCode - "W2"
Row3: CategoryName - FirstCategory GroupName - FirstGroup TestName - "SecondTest" TestNumber - "14" TestVisitCode - "W1"
Row4: CategoryName - FirstCategory GroupName - FirstGroup TestName - "SecondTest" TestNumber - "15" TestVisitCode - "W2"
Row5: CategoryName - FirstCategory GroupName - FirstGroup TestName - "SecondTest" TestNumber - "16" TestVisitCode - "W3"

After executing linq the data will look like this

FirstCategory
    FirstGroup
        FirstTest - {(W1,12), (W2,13)}
        SecondTest - {(W1,14), (W2,15),(W3, 16)}

What I would like to have

FirstCategory
    FirstGroup
        FirstTest - {(W1,12), (W2,13),(W3, "")}
        SecondTest - {(W1,14), (W2,15),(W3, 16)}

A:

You can first select all TestVisitCodes.
In your linq query you can make an union with all this VisitCodes which are not in your current CarTestNumber.
It is a little bit confusing.
I create a DataTable and fill that with your testdata:
DataTable loDt = new DataTable();
loDt.Columns.Add("CategoryName", typeof(string));
loDt.Columns.Add("GroupName", typeof(string));
loDt.Columns.Add("TestName", typeof(string));
loDt.Columns.Add("TestNumber", typeof(string));
loDt.Columns.Add("TestVisitCode", typeof(string));

var loRow = loDt.NewRow();
loRow["CategoryName"] = "FirstCategory";
loRow["GroupName"] = "FirstGroup";
loRow["TestName"] = "FirstTest";
loRow["TestNumber"] = "12";
loRow["TestVisitCode"] = "W1";
loDt.Rows.Add(loRow);

loRow = loDt.NewRow();
loRow["CategoryName"] = "FirstCategory";
loRow["GroupName"] = "FirstGroup";
loRow["TestName"] = "FirstTest";
loRow["TestNumber"] = "13";
loRow["TestVisitCode"] = "W2";
loDt.Rows.Add(loRow);

...

Then I make a list with all TestVisitCodes:
var loTestVisitCodes = loDt.AsEnumerable().Select(item => item.Field<string>("TestVisitCode")).Distinct();

And finally here is the linq query (look at the union statement):
var loCarsCategories = loDt.AsEnumerable()
    .GroupBy(row => new { CategoryName = row.Field<string>("CategoryName") })
    .Select(catGroup => new CarCategory
    {
        CategoryName = catGroup.Key.CategoryName,
        CarGroups = new List<CarGroup>(catGroup
            .GroupBy(row => new { GroupName = row.Field<string>("GroupName") })
            .Select(groupGroup => new CarGroup
            {
                GroupName = groupGroup.Key.GroupName,
                CarTests = new List<CarTest>(groupGroup
                    .GroupBy(row => new { TestName = row.Field<string>("TestName") })
                    .Select(groupTest => new CarTest
                    {
                        TestName = groupTest.Key.TestName,
                        CarTestNumbers = new List<CarTestNumber>(groupTest
                            .Select(row => new CarTestNumber
                            {
                                TestNumber = row.Field<String>("TestNumber"),
                                TestVisitCode = row.Field<String>("TestVisitCode")
                            })
                            .Union(new List<CarTestNumber>(loTestVisitCodes
                                .Except(groupTest.Select(row => row.Field<string>("TestVisitCode")))
                                .Select(VisitCode => new CarTestNumber
                                {
                                    TestNumber = string.Empty,
                                    TestVisitCode = VisitCode
                                }))))
                    }))
            }))
    });


Q:

ANDENGINE Old [Splash Screen Error]

I'm a beginner with Andengine, so I take GLSE1 to practise my first game code. I tried to display a splash screen, but it always show errors in "Texture"(cannot instantiate the type texture), "createFromAsset".
My complete code for the splash screen below:
package com.example.first.aq2;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.ui.activity.BaseGameActivity;

public class AQ2 extends BaseGameActivity {

    // ===========================================================
    // Constants
    // ===========================================================
    private static final int CAMERA_WIDTH = 480;
    private static final int CAMERA_HEIGHT = 320;
    // ===========================================================
    // Fields
    // ===========================================================
    private Camera mCamera;
    private Texture mTexture;
    private TextureRegion mSplashTextureRegion;
    // ===========================================================
    // Methods for/from SuperClass/Interfaces
    // ===========================================================
    @Override
    public Engine onLoadEngine() {
    this.mCamera = new Camera(0, 0, CAMERA_WIDTH,CAMERA_HEIGHT);
    return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH,  CAMERA_HEIGHT), this.mCamera));
    }
    @Override
    public void onLoadResources() {
    this.mTexture = new Texture(512, 512,TextureOptions.BILINEAR_PREMULTIPLYALPHA);
    this.mSplashTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture,this, "gfx/Splashscreen.png", 0, 0);
    this.mEngine.getTextureManager().loadTexture(this.mTexture);
    }
    @Override
    public Scene onLoadScene() {
    this.mEngine.registerUpdateHandler(new FPSLogger());
    final Scene scene = new Scene(1);
    /* Center the splash on the camera. */
    final int centerX = (CAMERA_WIDTH - this.mSplashTextureRegion.getWidth()) / 2;
    final int centerY = (CAMERA_HEIGHT - this.mSplashTextureRegion.getHeight()) / 2;
    /* Create the sprite and add it to the scene. */
    final Sprite splash = new Sprite(centerX, centerY, this.mSplashTextureRegion);
    scene.getLastChild().attachChild(splash);
    return scene;
    }
    @Override
    public void onLoadComplete() {
    }
    }
    enter code here

help me to do the first step

A:

May be you are using the image with the size greater than the width and height mentioned in the texture. Check the width and height of the image and Try increasing the width and height of the texture and check if it works
OR
Try change your texture to BitmapTextureAtlas and try this
private BitmapTextureAtlas mtexture;
    private TextureRegion mregion;
mtexture = new BitmapTextureAtlas(1024, 512, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
mregion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(mtexture, getApplicationContext(), "Splashscreen.png",0,0);
getEngine().getTextureManager().loadTexture(mtexture);


Q:

how to handles if-else in groovy?

Here I'm passing the skipfolders variable in input if the skipfolders is true then it prints all files from Parent path and skip the sub folders.
otherwise it returns all files from all folders include sub folders as well. Here I wrote if-else conditions. When I execute this code in FileMaker
it executes without any errors and displayed result.but the if-else conditions does't working here.
Problem :
If-else conditions doesn't working here.it prints all files from FTP include subfolders.skipfolders condition doesn't working.
                       at this return allFiles.join('\n') + '\n'+ allFolderFiles.join('\n')+ '\n' prints directly and skipfolders condition doesn't working.
                       Please help how to use if-else conditions properly in fileMaker groovy.
start()
def start(){

        boolean skipfolders = false
        def store;
        def ftpClient = new FTPClient()
        ftpClient.connect(server)
        // println(ftpClient.replyString)
        ftpClient.login(user,pass)
        ftpClient.enterLocalPassiveMode()
        FTPFile[] fileslist = ftpClient.listFiles("/")
        FTPFile[] folderfileslist = ftpClient.listFiles("/sample")

  if(skipfolders == false){

       def allFiles = [];
       for(int i=0; i<fileslist.length; i++){
       String file_name = fileslist[i].getName()
       String file_timestamp = fileslist[i].getTimestamp().getTime()
       String s = '|' + file_name+ '|' + '/' +file_name+'|'  +file_timestamp
       allFiles << s
   }
      def allFolderFiles = [];
      for(int i=0; i<folderfileslist.length; i++){
      String folderfile_name = folderfileslist[i].getName()
      String folderfile_timestamp = folderfileslist[i].getTimestamp().getTime()
      String s1 = '|' +folderfile_name+ '|' + '/sample' +'|'+folderfile_name+'|'  +folderfile_timestamp
      allFolderFiles << s1
 }
  ftpClient.disconnect()
  return allFiles.join('\n') + '\n'+ allFolderFiles.join('\n')+ '\n'

}
else{
       def allFiles = [];
       for(int i=0; i<fileslist.length; i++){
       String file_name = fileslist[i].getName()
       String file_timestamp = fileslist[i].getTimestamp().getTime()
       String s = '|' + file_name+ '|' + '/' +file_name+'|'  +file_timestamp
       allFiles << s
   }
   ftpClient.disconnect()
   return allFiles.enter code herejoin('\n')
  }
}

    enter code here

if anybody having idea please let me know thanks.

A:

If i am understanding the question correctly, you want to set the skipfolders variable as a parameter.
As it is you have declared:
boolean skipfolders = false;

So the else is never reached as mentioned by user daggett in the question comment.
If you do something like this instead:
start(true) or start(false)
def start(boolean input){
    boolean skipfolders = input;
    ...
}

Then you can reach the else statement depending on your input.


Q:

If $f$ and $g$ are paths with $g$ constant, then $f'\simeq g'$ rel$\{1\}$ if an only if there exist a free homotopy $f'\simeq g'.$

Using Theorem 1.6 (http://www.ugr.es/~acegarra/Rotman.pdf page 17), show (using the notation of exercise 3.2 (page 40)) that if $f$ and $g$ are paths with $g$ constant, then $f'\simeq g'$ rel$\{1\}$ if an only if there exist a free homotopy $f'\simeq g'.$
Attempt to the proof
$\implies$ direction
Follows immediately.
$\Longleftarrow$ direction
Suppose we have an homotopy $H:I\times I\to X$ such that $$H(t,0)=f'(t)$$ $$H(t,1)=g'(t)$$
We only need to find $H$ such that $H(1,t)=f'(1)=g'(1).$
Applying exercise 3.2 i) to $f$ and $g$, I have $f'\simeq g'.$ Since $g'$ is now constant, then $f'$ is nullhomotopic.
Now I am not sure if I can use iii) from Theorem 1.6 because I have $f':S^1\to X$ and I need $f':S^n\to X$. I am wrong in the previous line, in fact I can use the Theorem 1.6 with $n=1.$
I think now I can conclude that there exist an homotopy $H:f'\simeq g'$ such that $H(cte,t)=f'(cte),$ for all $t\in I.$
That is $H(1,t)=f'(1)$ for all $t\in I$.
I can have  $H(1,t)=f'(1)=g'(1)$ only if $H(t=1,1).$ How can I correct this?
Am I on the right track?
If someone could help me, thank you.

A:

You confuse $f,g : I \to X$ which are closed paths and $f',g' : S^1 \to X$. Thus your homotopy $H : I \times I \to X$ cannot  be a homotopy from $f'$ to $g'$. So take a (free) homotopy $H : S^1 \times I \to X$ such that $H(z,0) = f'(z), H(z,1) = g'(z) = x_0$.
In Example 1.7 Rotman shows that if $f : S^n \to X$ is map and $F : S^n \times I \to X$ a homotopy such that $F(z,0) = f(z), F(z,1) = \xi$ for all $x$, then $f$ has a continuous extension $F' : D^{n+1} \to X$.
So let $H': D^2 \to X$ be a continuous extension of $f'$. Define
$$R : S^1 \times I \to D^2, R(z,t) = t \cdot 1 + (1-t)\cdot z$$
where we regard $D^2$ as a subset of the complex plane. The map $R$ is continuous. Define
$$H'' = H' \circ R : S^1 \times I \to X .$$
Then $H''(z,0) = H'(z) = f'(z)$, $H''(z,1) = H'(1) = f'(1) = x_0 = g'(z)$  and $H''(1,t) = H'(1) = x_0$. Thus $H''$ is the desired basepoint-preserving homotopy.


Q:

Bashing a programming language, a framework or other technology

As far as I understand, bashing a particular programming language, framework, operating system, or technology is off topic on this site.
By "bashing" (I am not an English native speaker, so I hope this is the appropriate term), I mean ironic comments such as "Oh, you meant X?" where X is the name of a programming language (with 6 upvotes, and I consider upvoting such comments to be bashing as well). The content of such comments sounds to me
we all know that X sucks, hahaha (followed by n upvotes)

I find it pretty irritating and, because of this, I have considered leaving this site more than once already (of course, there are also lots of constructive questions and answers on this site, which is a good reason for me to be a member).
Summarizing, by bashing I mean picking on some (real or perceived) shortcomings of some technology X, e.g. for

lacking some modern feature
having an awkward syntax
being old-fashioned (more than 10 years old)
being too academic and not useful for real applications
being inferior in some unspecified way

I personally have technologies I like a lot, some that I find OK, and some that I dislike with a passion (for many reasons, sometimes not only technical), but I try to keep these feelings out of the discussion in questions, answers, and comments because I think it is not professional to start childish "My favourite language is better than yours" flame wars. Other developers may prefer to use other technologies and they probably have good reasons for that.
I have also tried to identify any objective shortcomings in technologies that are more often the target of bashing on this site, and the only idea I could come up with was that these technologies are not inherently worse than others that get less bashing, rather they are simply less popular among the members of the site. So, bashing what we do not know and we do not consider cool is IMHO childish and very little professional.
Of course, everyone who is enthusiastic about some technology X will propose X to others, and maybe they will point out certain problems in other technologies that X tries to solve. But I think a professional programmer should try to express their opinion in a controlled way and, if any criticism is expressed, it should be written in a balanced way.
Bottom line (my questions):

Do other members of programmers share this view? Do you think that some bad jokes and unmotivated, vague criticism is part of the game, or do they just lower the level of the discussion and therefore the quality of the site?
If bashing is out of place on this site, is there any measure that can be taken to discourage it? E.g. the moderators could flag certain comments as spam and this could have consequences for the spammer account.

A:

I'm surprised that although you appear to be genuinely annoyed by this you haven't been flagging the comments. We (the moderators) can't read every comment on the site, and unless the community notify us through flags, we'll probably be the last to know that something bad is happening.
Comments are, by their nature, ephemeral. They aren't supposed to stay around for ever, once they've served their purpose they should go away. If a comment is little more than a joke (or worse) you should feel free to flag it. Your comment flag options are:

rude or offensive
Please only use when a user is being rude towards another user. Language bashing that doesn't include very strong language doesn't count.
not constructive / off-topic
This would be the preferable comment flag for comments that serve no other purpose but to bash a language / technology / platform / product.
obsolete
This would be the preferable comment flag for comments that aren't useful anymore.
too chatty
This is a softer version of the "not constructive / off-topic". It would also be a good choice for comments that serve no other purpose but to bash a language / technology / platform / product.
other...
Moderators have the ability to edit comments, and this flag would be the one to use when editing is what you want to ask us to do. However keep in mind that comment edits do not generate a (publicly visible) revision history, and asking us to edit comments puts us in a very uncomfortable position. We would most certainly remove (for example) a four letter word from an otherwise helpful comment, or fix a broken link, but if it's anything more than that, we'll probably opt to delete the comment.
Another reason to use this flag would be when a whole comment thread has taken an unconstructive turn, and you want us to purge it. If you find yourself reading a comment thread and thinking that all comments have outlive their purpose, feel free to cast a single custom flag notifying us of the situation, instead of flagging each comment individually.

Moving on to the core issue, yes I agree there is a problem with language bashing, however it's a minor one and, from what I've seen, it's mostly limited to certain tags. We both happen to hang around the programming-languages tag, where general commentary on a language's design is to be expected, so we've probably seen a lot more language / technology / platform bashing comments than people who are focused on non language tags. The only equivalent behaviour I've noticed in non language tags, is "git/svn/hg bashing" on our version control related tags.
That said, some light hearted comments here and there are really not a big deal. Yes, we do strive to be as professional as we can be, but we are only human and some light fun is certainly part of the game. This doesn't mean that we aren't going to remove comments that aren't bringing anything actually useful to the discussion (even the best jokes get old eventually), but more that if there isn't a persistent pattern of trollish comment from a specific user there won't really be any consequences (other than removing the comments).
If, on the other hand, we do notice a persistent pattern, we'll deal with it as we typically do with behaviours that lower the overall quality of the site. Which, in extremely broad terms, means a (private) warning first, and a suspension if the behaviour persists after the warning.
PS. Our lovely chat room, The Whiteboard, is the perfect place for idle commentary and fun discussions, including language / technology / platform / product bashing (the recent starred messages are revealing ;). If you absolutely must rant, do it in chat please, not in comments.

A:

Bashing specific languages, tools or technologies is absolutely off topic here and we have closed many questions and quite some answers for doing so (or even trying to start a civilized discussion on advatages vs. disadvantages).
Actually I can't really follow your view on this, since Programmers and the other StackExchange sites have far less problems with this than any other forum, Q&A site or similar community I have seen so far and this is one reason why I like to stay here.
Comments are slightly (very slightly) different I think, we normally don't close those that often (as far as I am aware as a non admin). You will always have a few comments that are a bit more aggressive. See them as an option to keep a human touch to the whole thing. Still, if they become too extreme they should be closed, though we really don't need any additional punishment. At least not some automatism, I think the admins can handle it if a user becomes annoying. We still have the chat room where we can discuss such details and give point oiut such users.
But for the really bad type of users commenting isn't enough anyway. Those will soon enough try to ask flamewar questions and they disappear when they get those questions closed within minutes.

A:

Preventing the "What language should I use?" questions has probably done more to curtail this than anything else, but monitoring and group feedback also benefit it. There are some questions where the OP is trying to use a particular language for a task it was unintended or not as suitable as others. It may not be the ideal answer, but it is professional to comment that this may not be the best tool to use. It's up to others to determine if this is a constructive professional opinion, a personal preference or bashing.
I think it is just as easy to promote a language in a childish and unprofessional way. It's not limited to bashing.


Q:

Data explorer queries are missing an author attribution

Stack Exchange Data Explorer queries are licensed under cc-wiki with attribution required, like user contributions on normal sites. Yet query pages on SEDE do not have any user attribution whatsoever. Queries should link to their author's profile, like posts and post histories do. At the moment, SE displaying SEDE queries is technically illegal.

A:

This is now complete ... you get plenty of attribution.
The query show page shows who created the query and who last edited it.
The edit query page shows who created each revision.


Q:

CryptDerive key with AES256

I am trying to re-create this openssl command in C#:
openssl enc –e –aes-256-cbc –k SecretPhrase1234 –in profile.xml –out profile.cfg

This encrypted file will then be loaded by a device and the process is described as this:

A lower case –k precedes the secret key, which can be any plain text phrase and is used to generate a random 64-bit salt. Then, in combination with the secret specified with the –k argument, it derives a random 128-bit initial vector, and the actual 256-bit encryption key.

So, in my C# application I need to create a random 64 bit salt using my "SecretPhrase1234". Then I need to derive a 128 bit IV and a 256 bit key. The device already has the secret phrase loaded onto it.
Here is my code:
AesManaged aes = new AesManaged();

// Encrypt the string to an array of bytes.
aes.KeySize = 256;
aes.BlockSize = 128;
aes.Mode = CipherMode.CBC;

Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes("SecretPhrase1234", 8);
byte[] SALT = rfc.Salt;
PasswordDeriveBytes pdb = new PasswordDeriveBytes("SecretPhrase1234", SALT);
byte[] IV = rfc.GetBytes(aes.BlockSize/8);
//The next line doesn't work
byte[] KEY = pdb.CryptDeriveKey("AES", "SHA1", aes.KeySize, IV);
aes.Key = KEY;
aes.IV = IV;

byte[] encrypted = AESEncryption.EncryptStringToBytes(plainConfig,
                                                    aes.Key, aes.IV);
tw.WriteLine(Encoding.ASCII.GetString(encrypted));
tw.Close();

A:

I found a .NET implementation of OPENSSL which perfectly suits my needs. It is here:
openssl using only .NET classes


Q:

problem assigning declarative values in asp:hyperlink. error: this is not scriptlet. will output as plain text

I am trying to do this:
<asp:HyperLink NavigateUrl='<%= WebContext.RootUrl %><%= WebContext.CurrentUser.UserName %>' runat="server" Text='<%= GetProfileImage(WebContext.CurrentUser.AccountId) %>'></asp:HyperLink>

But am getting the error:

this is not scriptlet. will output as
  plain text.

when I mouse over my declarative statements.
Any ideas? Thanks.

A:

You cannot use <%= ... %> literals to set properties of server-side controls.
Instead, you can use a normal (client-side)  tag, like this:
<a href="<%= WebContext.RootUrl %><%= WebContext.CurrentUser.UserName %>"><%= GetProfileImage(WebContext.CurrentUser.AccountId) %>

If GetProfileImage doesn't return HTML tags, make sure to escape it.

A:

You can use data binding syntax <%# %>. Just be sure that your hyperlink is either in a databound control, such as a ListView item template, or that you explicitly call DataBind() on the control from code-behind.

A:

You can still populate an <asp:HyperLink> if you provide the ID and runat="server" properties.  You can then set any property of the HyperLink from code-behind.
ASP Code:
<asp:HyperLink ID="myLink" runat="server"/>

Code-behind:
public void Page_Init()
{
    myLink.NavigateURL = WebContext.RootUrl + WebContext.CurrentUser.UserName;
    myLink.Text = GetProfileImage(WebContext.CurrentUser.AccountId);
}


Q:

Xcode Server iOS Trigger issues error 35

I'm using Xcode 9.0.1
we increased the maximum number of processes until the next restart
sudo launchctl limit maxproc 2000 2500

I am having this issue while running integrations in Xcode Server.

Assertion: Exception trying to execute trigger:
  NSInternalInconsistencyException: Couldn't posix_spawn: error 35

A:

For anyone coming to this issue via googling "Couldn't posix_spawn: error 35"
Check your activity monitor. There may be a bunch of idle processes. For me, I ran into this error message ala source tree when I have a ton of idle python processes. Killing them all seemed to resolve the issue. I've been having this issue more since upgrading to mojave but it seems to have existed in prior versions of osx as well.


Q:

Bedeutung und Grammatik von "wie nebenbei"

Aus dem Spiegel-Magazin:

Freunde als sozialpolitische Notwendigkeit also, als Ersatz für die traditionellen Institutionen fürsorglichen Zusammenlebens? Es klingt, als könne das Modell des pensionierten Politikers zumindest einige Probleme der modernen Gesellschaft wie nebenbei lösen.

Was bedeutet "wie nebenbei"? Hier und hier kann ich die Phrase nicht finden. Wie ist diese Verwendung konsequent mit der Tatsache, dass "nebenbei" ein Adverb ist?

A:

"Wie nebenbei" soll vermutlich "mühelos" bedeuten. Etwas ist so einfach, dass man es nebenbei machen kann.
Siehe auch: "Die Zeit vergeht wie im Flug." Anstelle eines Adverbs wird ein Vergleich hergestellt.


Q:

Notebook does not boot from bootable USB to install Windows XP

I have a Dell Inspiron Notebook which has an Atom processor and which had a factory set-up of XP onto it. I had opted out the CD-ROM drive @ the time of purchase. Now my Windows XP is corrupted.
I tried installing Windows 7 on it, but it popped some error and could not complete installation for some reason (did not proceed from the last page where it said completing installation).
However I have tried re-installing XP from a bootable USB drive. Still @ the time of set-up it pops up an error saying:
CD-ROM drive not found. Set-up cannot continue. Press F3 to exit.
Also it displays a note that SCSI adapter has not been removed.
How do I go about and install XP, can it be a problem with the bootable USB drive, or is there a problem with my hardware?

A:

If you need make bootable windows xp,vista,7 just you need this tools
http://downloadsquad.switched.com/2009/08/27/make-a-bootable-usb-installer-for-windows-xp-vista-7-with-wint/
Offical website program :
http://wintoflash.com/home/en/
Download link
http://wintoflash.com/download/en/
But you wanna install windows 7
I really suggest this
http://www.microsoftstore.com/store/msstore/html/pbPage.Help_Win7_usbdvd_dwnTool
that much better for windows 7 just you need iso and 4 GB or obove usb stick
That can be usefull good luck


Q:

Trigonometric problem: $2^{\sin{x}} + 2^{\cos{x}} \ge 2^{(1-1/{\sqrt2})}$

Show that:
$$\large2^{\sin{x}} + 2^{\cos{x}} \ge 2^\left({1-\frac{1}{\sqrt{2}}}\right)$$
This looks like an am gm problem to me where we should be using the fact that am is more that or equal to gm but I am having problem solving this equation after this:
$\large\left(2^{\sin{x}} + 2^{\cos{x}}\right)/2 \ge \sqrt{2^{\sin{x}+\cos{x}}}$
Please solve the sum step wise. Thanks

A:

By the am-gm inequality,
\begin{align}
\frac{2^{\sin x}+2^{\cos x}}{2}
&\ge 2^{\frac{1}{2}(\sin x+\cos x)}\\
\end{align}
Multiplying both sides of the inequality by $2$ yields
$$2^{\sin x}+2^{\cos x}\ge2\cdot 2^{\frac{1}{2}(\sin x+\cos x)}$$
Since $\color\red{\sin{x}+\cos{x}=\sqrt{2}\sin(x+\pi/4)}$, we have
\begin{align}
RHS
&=2\cdot2^{\frac{1}{2}(\sin{x}+\cos{x})}\\
&=2^{1+\frac{1}{\sqrt{2}}\sin(x+\pi/4)}\\
&\ge2^{1-\frac{1}{\sqrt{2}}}
\end{align}
as $-1\le \sin(x+\pi/4)\le 1.$
Hence
$$\color\red{2^{\sin x}+2^{\cos x}}\ge 2^{1+\frac{1}{\sqrt{2}}\sin(x+\pi/4)}\ge \color\red{2^{1-\frac{1}{\sqrt2}}}$$


Q:

insert current date time using laravel

I want to store current date time in MySQL using following laravel function. Actually, I stored static date instead of this i want store current date time at created_at,updated_at field in database.
 function insert(Request $req)
   {
       $name=$req->input('name');
       $address=$req->input('address');
       $data=array("name" => $name,"address" => $address,"created_at"=>'2017-04-27 10:29:59',"updated_at"=>'2017-04-27 10:29:59');
       DB::table('student')->insert($data);
       echo "Record inserted successfully.<br/>";
       return redirect('/');
   }

A:

use laravel helper function
now()

other wise used carbon class
Carbon\Carbon::now()

used like that
$data = array("name" => $name,"address" => $address,"created_at"=> Carbon::now(),"updated_at"=> now());
DB::table('student')->insert($data);

for more information see


Q:

SQL Server Agent Job - Schedule based on last working day of month

I need to run a SQL Server Agent Job once monthly, two days prior to the last working day of the month.
So if, for example, the last working day of the month is Friday the 28th, the job would run on Wednesday the 26th, two days prior to it.
Is there a way to use this schedule option in an Agent job?

A:

In the job, you can create a step to check the date and abort the job if necessary. The trick is to set the "On failure action" to "Quit the job reporting success." For details see here


Q:

Offline conversion with Google client ID not as eCommerce transaction in Analytics

I am working on a project to measure offline conversions with the new Universal Analytics from Google.
When a lead gets the status "order" in my custom made lead management system, we sent the earlier grabbed Google client ID with the code below to Universal Analytics. The upload is working, although Analytics sees it as an ecommerce transaction.
Does anyone know how I can modify the code or Analytics settings to make sure that Google Analytics sees it not as eCommerce transaction?
My code for uploading the Google Client ID to Analytics:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.google-analytics.com/collect');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; InfoPath.2; .NET CLR 2.0.50727)");
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1&tid=UA-XXXXXXXX-42&cid=379445656".urlencode('.')."1380816256&t=transaction&tr=123.00&ti=43388&z=".time());
curl_close ($ch);

A:

It sees it as a eCommerce transaction because the hit type you're sending t=transaction is for transactions. If you're wanting to send an alternative hit type, take a look at google's documentation for the other alternatives - Measurement Protocol Developer Guide - Sending Common Hit Types.


Q:

Finding the fibonacci numbers in a certain range using python

I am trying to write a function in python that returns a list of all the fibonacci numbers in a certain range but my code wont work it simply returns [0]. What is the problem?
from math import sqrt
def F(n):
    return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))

def Frange(x):
    A = [0]
    while max(A) < x:
        H = 1
        for i in range(H):
            A.append(F(i))
        H = H+1
    return A

A:

You set H = 1 as the first statement in your while loop; so every time you enter the for loop, H = 1 and you'll only get the Fibonacci number for n=0
You need to set H = 1 outside the while loop:
def Frange(x):
    A = [0]
    H = 1
    while max(A) < x:

        for i in range(H):
            A.append(F(i))
        H = H+1
    return A

You could have solved this yourself very easily by printing various values inside the loops, such as print H.


Q:

Why is a.dot(b) faster than a@b although Numpy recommends a@b

According to the answers from this question and also according to numpy, matrix multiplication of 2-D arrays is best done via a @ b, or numpy.matmul(a,b) as compared to a.dot(b).

If both a and b are 2-D arrays, it is matrix multiplication, but using
  matmul or a @ b is preferred.

I did the following benchmark and found contrary results.
Questions: Is there an issue with my benchmark? If not, why does Numpy not recommend a.dot(b) when it is faster than a@b or numpy.matmul(a,b)?
Benchmark used python 3.5 numpy 1.15.0.
$ pip3 list | grep numpy
numpy                         1.15.0
$ python3 --version
Python 3.5.2

Benchmark code:
import timeit

setup = '''
import numpy as np
a = np.arange(16).reshape(4,4)
b = np.arange(16).reshape(4,4)
'''
test = '''
for i in range(1000):
    a @ b
'''
test1 = '''
for i in range(1000):
    np.matmul(a,b)
'''
test2 = '''
for i in range(1000):
    a.dot(b)
'''

print( timeit.timeit(test, setup, number=100) )
print( timeit.timeit(test1, setup, number=100) )
print( timeit.timeit(test2, setup, number=100) )

Results:
test  : 0.11132473500038031
test1 : 0.10812476599676302
test2 : 0.06115105600474635

Add on results:
>>> a = np.arange(16).reshape(4,4)
>>> b = np.arange(16).reshape(4,4)
>>> a@b
array([[ 56,  62,  68,  74],
       [152, 174, 196, 218],
       [248, 286, 324, 362],
       [344, 398, 452, 506]])
>>> np.matmul(a,b)
array([[ 56,  62,  68,  74],
       [152, 174, 196, 218],
       [248, 286, 324, 362],
       [344, 398, 452, 506]])
>>> a.dot(b)
array([[ 56,  62,  68,  74],
       [152, 174, 196, 218],
       [248, 286, 324, 362],
       [344, 398, 452, 506]])

A:

Your premise is incorrect. You should use larger matrices to measure performance to avoid function calls dwarfing insignificant calculations.
Using Python 3.60 / NumPy 1.11.3 you will find, as explained here, that @ calls np.matmul and both outperform np.dot.
import numpy as np

n = 500
a = np.arange(n**2).reshape(n, n)
b = np.arange(n**2).reshape(n, n)

%timeit a.dot(b)        # 134 ms per loop
%timeit a @ b           # 71 ms per loop
%timeit np.matmul(a,b)  # 70.6 ms per loop

Also note, as explained in the docs, np.dot is functionally different to @ / np.matmul. In particular, they differ in treatment of matrices with dimensions greater than 2.


Q:

What is the probability of rolling at least one one AND no sixes with $n$ six-sided dice?

I gather that the probability of rolling at least one 1 when $n$ six-sided dice are rolled is equivalent to $1-(5/6)^n$ and conversely $(5/6)^n$ for rolling no sixes...
But how do you calculate the odds for both occurring at the same time?

A:

Problems like this can be handled combinatorially:  Out of the $6^n$ possible rolls, there are $5^n$ rolls for which no sixes occur, but that includes $4^n$ rolls for which no ones occur either, so the answer is
$${5^n-4^n\over6^n}$$
Note, this can be rewritten in various ways, including $\left(5\over6\right)^n\left(1-\left(4\over5\right)^n\right)$.


Q:

How to invoke System.Linq.Enumerable.Count<> on IEnumerable using Reflection?

I have a bunch of IEnumerable Collections which exact number and types is subject of frequent changes (due to automatic code generation).
It looks something like this:
public class MyCollections {
    public System.Collections.Generic.IEnumerable<SomeType> SomeTypeCollection;
    public System.Collections.Generic.IEnumerable<OtherType> OtherTypeCollection;
    ...

At runtime i want to determine each Type and it's count without having to rewrite the code after every code generation. So i am looking for a generic approach using reflection. The result i am looking for is something like:
MyType: 23
OtherType: 42

My problem is that i can't figure how to invoke the Count method properly. Here is what i have so far:
        // Handle to the Count method of System.Linq.Enumerable
        MethodInfo countMethodInfo = typeof(System.Linq.Enumerable).GetMethod("Count", new Type[] { typeof(IEnumerable<>) });

        PropertyInfo[] properties = typeof(MyCollections).GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Type propertyType = property.PropertyType;
            if (propertyType.IsGenericType)
            {
                Type genericType = propertyType.GetGenericTypeDefinition();
                if (genericType == typeof(IEnumerable<>))
                {
                    // access the collection property
                    object collection = property.GetValue(someInstanceOfMyCollections, null);

                    // access the type of the generic collection
                    Type genericArgument = propertyType.GetGenericArguments()[0];

                    // make a generic method call for System.Linq.Enumerable.Count<> for the type of this collection
                    MethodInfo localCountMethodInfo = countMethodInfo.MakeGenericMethod(genericArgument);

                    // invoke Count method (this fails)
                    object count = localCountMethodInfo.Invoke(collection, null);

                    System.Diagnostics.Debug.WriteLine("{0}: {1}", genericArgument.Name, count);
                }
            }
        }

A:

If you insist on doing it the hard way ;p
Changes:

how you obtain countMethodInfo for a generic method
the arguments to Invoke

Code (note obj is my instance of MyCollections):
    MethodInfo countMethodInfo = typeof (System.Linq.Enumerable).GetMethods().Single(
        method => method.Name == "Count" && method.IsStatic && method.GetParameters().Length == 1);

    PropertyInfo[] properties = typeof(MyCollections).GetProperties();
    foreach (PropertyInfo property in properties)
    {
        Type propertyType = property.PropertyType;
        if (propertyType.IsGenericType)
        {
            Type genericType = propertyType.GetGenericTypeDefinition();
            if (genericType == typeof(IEnumerable<>))
            {
                // access the collection property
                object collection = property.GetValue(obj, null);

                // access the type of the generic collection
                Type genericArgument = propertyType.GetGenericArguments()[0];

                // make a generic method call for System.Linq.Enumerable.Count<> for the type of this collection
                MethodInfo localCountMethodInfo = countMethodInfo.MakeGenericMethod(genericArgument);

                // invoke Count method (this fails)
                object count = localCountMethodInfo.Invoke(null, new object[] {collection});

                System.Diagnostics.Debug.WriteLine("{0}: {1}", genericArgument.Name, count);
            }
        }
    }

A:

That is going to involve some MakeGenericMethod - and a lot of reflection generally. Personally, I would be tempted to just simplify by ditching the generics in this case:
public static int Count(IEnumerable data) {
    ICollection list = data as ICollection;
    if(list != null) return list.Count;
    int count = 0;
    IEnumerator iter = data.GetEnumerator();
    using(iter as IDisposable) {
        while(iter.MoveNext()) count++;
    }
    return count;
}

You can cast to the non-generic IEnumerable trivially, even if fetching via reflection.


Q:

Unable to create foreign key constraint?

I'm having two tables: Persons and person_config having the below schemas: -
/*Table: persons*/
------------------

/*Column Information*/
----------------------

Field        Type               Collation           Null    Key     Default              Extra           Privileges                       Comment
-----------  -----------------  ------------------  ------  ------  -------------------  --------------  -------------------------------  ---------
person_id    int(100) unsigned  (NULL)              NO      PRI     (NULL)               auto_increment  select,insert,update,references
person_name  varchar(25)        utf8mb4_general_ci  YES             (NULL)                               select,insert,update,references
added_date   date               (NULL)              YES             current_timestamp()                  select,insert,update,references
added_logon  varchar(10)        utf8mb4_general_ci  YES             Admin                                select,insert,update,references

/*Index Information*/
---------------------

Table    Non_unique  Key_name  Seq_in_index  Column_name  Collation  Cardinality  Sub_part  Packed  Null    Index_type  Comment  Index_comment
-------  ----------  --------  ------------  -----------  ---------  -----------  --------  ------  ------  ----------  -------  ---------------
persons           0  PRIMARY              1  person_id    A                  992    (NULL)  (NULL)          BTREE

and
/*Table: person_config*/
------------------------

/*Column Information*/
----------------------

Field        Type               Collation           Null    Key     Default              Extra           Privileges                       Comment
-----------  -----------------  ------------------  ------  ------  -------------------  --------------  -------------------------------  ---------
config_id    int(100) unsigned  (NULL)              NO      PRI     (NULL)               auto_increment  select,insert,update,references
person_id    int(100)           (NULL)              NO      PRI     (NULL)                               select,insert,update,references
config       varchar(25)        utf8mb4_general_ci  NO              (NULL)                               select,insert,update,references
value        varchar(25)        utf8mb4_general_ci  NO              (NULL)                               select,insert,update,references
added_date   timestamp          (NULL)              NO              current_timestamp()                  select,insert,update,references
added_logon  varchar(25)        utf8mb4_general_ci  YES             Admin                                select,insert,update,references

/*Index Information*/
---------------------

Table          Non_unique  Key_name  Seq_in_index  Column_name  Collation  Cardinality  Sub_part  Packed  Null    Index_type  Comment  Index_comment
-------------  ----------  --------  ------------  -----------  ---------  -----------  --------  ------  ------  ----------  -------  ---------------
person_config           0  PRIMARY              1  config_id    A                    1    (NULL)  (NULL)          BTREE
person_config           0  PRIMARY              2  person_id    A                    1    (NULL)  (NULL)          BTREE

I want to make something like ADD  Person_Config(person_id) refers to persons(person_id). Kindly find the below query:
Alter table `movies`.`person_config`
  add foreign key (`person_id`) references `movies`.`persons`(`person_id`)

Im getting the below error:

Can't create table movies.person_config (errno: 150 "Foreign key
  constraint is incorrectly formed")

Kindlye guide me on this, what is wrong with this.

A:

from what i see you have made person_id on person_config primary key plus person_id on person table is unsigned int but int on person_config foreign key type must be exactly the same on parent and child table so remove person_id primary key constraint and also make it unsigned int and try again.


Q:

Running npm install on Ubuntu with Octopus Deploy

We are using Octopus deploy to deploy an angularjs app. I'm running a post deployment script (bash) and in there I try to do npm install. This doesn't work, I get an error
npm: command not found

However if I login to the linux box as the Octopus user, go to the directory that Octopus Deploy is trying to run the script from, I am able to run npm install without error.
I've confirmed its the right user (running whoami before npm install in the post deployment script).
I've tried adding the npm executable to my PATH variables which didn't work. I've also put the full path to npm in my script which gives me a new error
/usr/bin/env: ‘node’: No such file or directory

A:

Please run the following command as octopus user to access npm for other users.
n=$(which node);n=${n%/bin/node}; chmod -R 755 $n/bin/*; sudo cp -r $n/{bin,lib,share} /usr/local

Or use nvm to install node
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.2/install.sh | bash

source ~/.bashrc

source ~/.profile

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

nvm ls-remote

nvm install 8.10.0

node --version

npm --version

which node

n=$(which node);n=${n%/bin/node}; chmod -R 755 $n/bin/*; sudo cp -r $n/{bin,lib,share} /usr/local

https://github.com/creationix/nvm
If you are installing new node version, please do the following steps.
nvm list     will show all installed node versions
nvm use v8.10.0
nvm alias default v8.10.0     set default node version for current user


Q:

Bing Search Suggestions using Jquery

I have  a requirement in my website where the user can type in some "text" in a textbox and i have to show some search suggestions in a drop down.  I have signed up for a Bing Search account and i got an account key. But i am not able to see any example code how to implement this feature using Jquery.
My website is written in Asp.Net MVC and it would be great if some one could point to an example code.
Thanks !

A:

http://api.bing.net/xml.aspx?Appid=<AppID>&sources=spell&query=cofee

Source: http://www.bing.com/developers/s/APIBasics.html
All you need to do is to post the REST API request via XHR (POST) and get the data as text. You can parse the repsonse with JSON.parse().


Q:

R - Error some group is too small for 'qda'

I'm trying to solve this problem from few days but google can't help :(
I got Error like that:

Error in qda.default(x, grouping, ...) :    some group is too small
  for 'qda'

At stack were simillar topic:
R Error : some group is too small for 'qda'
But I cant find out how to do that : /
This is my code:
library(MASS)
library(mlbench)
library(caret)
library(class)
data(Glass)
Glass <- data.frame(Glass)
Glass <- na.omit(Glass)

Glass$Type = as.factor(Glass$Type)
x = as.matrix(Glass[,names(Glass) != "Type"])
mode(x) = "numeric"
Glass[,names(Glass) != "Type"] <-x
ind <- sample(2, nrow(Glass), replace = TRUE, prob=c(0.8, 0.2))
train <- Glass[ind == 1,]
test <- Glass[ind == 2,]
train[,names(Glass) != "Type"] <- apply(train[,names(Glass) != "Type"], 2, jitter)

Everything is great but next lines..
qda_Typeifier <- qda(Type~ ., data=train)
ypred.test <- predict(qda_Typeifier,test)$Type
mean(ypred.test == test$Type)

Hope, help will came soon!

A:

It's not wrong code (there is little mistake), when this error show

some group is too small for 'qda'

Tt means that the dataSet is wrong.
To repair that you should modify dataSet.


Q:

NSMutableDictionary not Setting Keys

All,
I'm sure I'm overlooking something, but I've been staring at this code for too long trying to figure out what's going on.
-(IBAction)continue:(id)sender
{
    //setters for the limits
    NSLog(@"Log ageUnder18: %@", ageUnder18.text);   //returns Y
    NSMutableDictionary *cardLimits;
    [cardLimits setObject:ageUnder18.text forKey:@"ageUnder18"];
    NSLog(@"Just set %@", [cardLimits objectForKey:@"ageUnder18"]); //returns NULL

//more code here
}

Why is that returning NULL?
Thanks in advance,
James

A:

You're not initializing your variable. In fact, you're rather lucky that you aren't crashing outright on the -setObject:forKey: line. Your cardLimits variable currently holds garbage memory, i.e. whatever was on the stack at the address that the variable occupies. You need to use
NSMutableDictionary *cardLimits = [NSMutableDictionary dictionary];

Note that the Static Analyzer should be able to catch this for you.


Q:

How can I decrypt data encrypted with 'rijndael-128-cbc' in ruby

I need to decrypt data which is encrypted by php with 'rijndael-128-cbc' algorithm.
Now I have a problem to convert php code to ruby code.
ruby OpenSSL::Cipher doesn't support rijndael-128-cbc then I use "aes-128-cbc".
I heard AES is based on the Rijndael cipher, so I guess I can convert decryption with rijndael-128-cbc' to AES-128-CBC.
enc = OpenSSL::Cipher.new "AES-128-CBC"
enc.encrypt
puts enc.key_len

It's output is 16
However, In php
echo mcrypt_get_key_size('rijndael-128', 'cbc')

this gets 32
Is there any difference between 'rijndael-128' and "AES-128-CBC"?
and How can I convert rijndael-128-cbc descrytion to ruby?

A:

I am no Ruby developer, so I can't help you with the ruby code, but I can give you a few pointers about Rijndael, and PHP's mcrypt extension ...
Yes, AES is based on Rijndael-128 and therefore Rijndael-128 and AES-128 are the same thing.
It's important to note that the number in Rijndael's variations refers to the cipher's block size, while for AES - it's the key size, so (for example) Rijndael-192 is NOT AES-192; AES always has a block size of 16 bytes or 128 bits.
That being said, Rijndael-128 can also be AES-192 and AES-256, the difference being only the key size.
As described in the PHP manual for mcrypt_get_key_size(), the function returns the maximum key length for the supplied cipher ...
AES-256 == Rijndael-128 with a 32-byte key

This is why it's returning 32. For AES-128, the key size is of course 16 - you can hardcode that.
Hopefully, that will clear it up a bit for you.


Q:

SQL Server Update with group by

 insert into tableA (column1)
 select min(tableC.column1)
 from tableB
 inner join tableC on (tableC.coumn2 = tableB.column1
 and tableB.column2 = tableA.column2)
 group by tableA.column2

How would I change the above to a update with group by instead of insert with group by based on the criteria tableB.column2 = tableA.column2 ?
Note that I am using SQL SERVER 2008.

A:

  Update A set Column1 = minC
    from (select Ab.Column2, min(C.Column1) as minC
            from A Ab
            inner join B on Ab.Column2 = B.Column2
            inner join C on C.column2 = B.Column2 --No need to add again the A.col2 = B.col2
            group by Ab.Column2) Grouped where A.Column2 = Grouped.Column2

Is this what you want?
This will get for each columnA the C.Column1 min value, and will update it in A.Column1 (that's where you were inserting before), based on condition A.Column2 = Grouped.Column2.
here is a SQL-Fiddle Demo


Q:

PHP Opening file not on webserver for editing

I'm creating a simple script for editing html and php code.
I am using fopen() and fwrite() to open and save files. However, I am only able to open files that are on my web server and not from my computer.
What can I do to make opening files from my computer possible?
I would like to avoid setting up ftp servers and the like because
1) that ultimately defeats the object - might as well set up a local web server
2) I would like for others to be able to download and use the script with little effort
Any help would be appreciated.
Thanks

A:

OK - based on your comments above and here I think I understand now... ;-)
http://www.w3.org/TR/html-markup/input.file.html
https://developer.mozilla.org/en-US/docs/HTML/Element/Input
This will allow someone to upload a file to your PHP-enabled site via their browser (after they browse to your site).
Then, after the file has been saved to the server, your PHP code can use eg get_file_contents() to pick up the file and work with it.
The PHP would need to present the file (ie in more HTML) as a download link/button etc, for the user to collect back again after it's been processed.


Q:

How to blur 3D array of points, while maintaining their original values? (Python)

I have a sparse 3D array of values. I am trying to turn each "point" into a fuzzy "sphere", by applying a Gaussian filter to the array.
I would like the original value at the point (x,y,z) to remain the same. I just want to create falloff values around this point... But applying the Gaussian filter changes the original (x,y,z) value as well.
I am currently doing this:
dataCube = scipy.ndimage.filters.gaussian_filter(dataCube, 3, truncate=8)
Is there a way for me to normalize this, or do something so that my original values are still in this new dataCube? I am not necessarily tied to using a Gaussian filter, if that is not the best approach.

A:

You can do this using a convolution with a kernel that has 1 as its central value, and a width smaller than the spacing between your data points.
1-d example:
import numpy as np
import scipy.signal
data = np.array([0,0,0,0,0,5,0,0,0,0,0])
kernel = np.array([0.5,1,0.5])
scipy.signal.convolve(data, kernel, mode="same")

gives
array([ 0. ,  0. ,  0. ,  0. ,  2.5,  5. ,  2.5,  0. ,  0. ,  0. ,  0. ])

Note that fftconvolve might be much faster for large arrays. You also have to specify what should happen at the boundaries of your array.
Update: 3-d example
import numpy as np
from scipy import signal

# first build the smoothing kernel
sigma = 1.0     # width of kernel
x = np.arange(-3,4,1)   # coordinate arrays -- make sure they contain 0!
y = np.arange(-3,4,1)
z = np.arange(-3,4,1)
xx, yy, zz = np.meshgrid(x,y,z)
kernel = np.exp(-(xx**2 + yy**2 + zz**2)/(2*sigma**2))

# apply to sample data
data = np.zeros((11,11,11))
data[5,5,5] = 5.
filtered = signal.convolve(data, kernel, mode="same")

# check output
print filtered[:,5,5]

gives
[ 0.          0.          0.05554498  0.67667642  3.0326533   5.          3.0326533
  0.67667642  0.05554498  0.          0.        ]


Q:

Metaphor for the concept of shell?

I'm finding myself helping out some classmates in my computer science class, because I have prior development experience, and I'm having a hard time explaining certain things like the shell. What's a good metaphor for the shell in the context of the Terminal on Mac, contrasted with a remote shell via SSH?

A:

Hey you speak with the computer!

(Quote from a child who discovers the shell.)
“The shell” is basically a language the computer can recognize, obey to, and reply to if asked.
Local or not makes no difference. Think of a remote shell as an equivalent of communication over the phone.

A:

A shell is the interface through which a user interacts with a computer. The Windows GUI itself is a shell. A command line shell requires the user to type commands as opposed to point 'n click.

A:

Put simply, a terminal is an I/O environment for programs to operate in, and a shell is a command processor that allows for the input of commands to cause actions (usually both interactively and non-interactively (scripted)). The shell is run within the terminal as a program.
There is little difference between a local and remote shell, other than that they are local and remote (and a remote shell generally is connected to a pty, although local shells can be too).


Q:

Position of a sublist in a list haskell

Ok so I'm trying to write a function that determines the position of a string in another string if the first one is a sublist of the second. Say there's a string like "pie" and another one like "applepie", the function would return 5, since the first letter of "pie" is at the position 5 in the string "applepie"
Does anyone have an idea of how I can do that?

A:

Look at this question. It was asked (and answered) a few days ago and covers exactly your problem.
My solution:
findStr :: String -> String -> Maybe Int
findStr pat str = findStrHelp pat str 0
  where
    findStrHelp _ [] _ = Nothing
    findStrHelp pat s@(x:xs) n
      | pat == (take (length pat) s) = Just n
      | otherwise = findStrHelp pat xs (n+1)

To get this code without maybe, just remove the findStrHelp _ [] _ line and change the Just n to n. Also change the Maybe Int in the type signature to Int.


Q:

Explain the shell command: shift $(($optind - 1))

I am not a Linux guy but stuck in some Script which I have to read for my Project.
So can anyone can help me what this command is doing?
shift $(($optind - 1))

A:

shift $((OPTIND-1)) (note OPTIND is upper case) is normally found immediately after a getopts while loop. $OPTIND is the number of options found by getopts.
As pauljohn32 mentions in the comments, strictly speaking, OPTIND gives the position of the next command line argument.
From the GNU Bash Reference Manual:

getopts optstring name [args]
getopts is used by shell scripts to parse positional parameters.
  optstring contains the option characters to be recognized; if a
  character is followed by a colon, the option is expected to have an
  argument, which should be separated from it by whitespace. The colon
  (‘:’) and question mark (‘?’) may not be used as option characters.
  Each time it is invoked, getopts places the next option in the shell
  variable name, initializing name if it does not exist, and the index
  of the next argument to be processed into the variable OPTIND.
  OPTIND is initialized to 1 each time the shell or a shell script is
  invoked. When an option requires an argument, getopts places that
  argument into the variable OPTARG. The shell does not reset OPTIND
  automatically; it must be manually reset between multiple calls to
  getopts within the same shell invocation if a new set of parameters
  is to be used.
When the end of options is encountered, getopts exits with a return
  value greater than zero. OPTIND is set to the index of the first
  non-option argument, and name is set to ‘?’.
getopts normally parses the positional parameters, but if more
  arguments are given in args, getopts parses those instead.

shift n
removes n strings from the positional parameters list. Thus shift $((OPTIND-1)) removes all the options that have been parsed by getopts from the parameters list, and so after that point, $1 will refer to the first non-option argument passed to the script.
Update
As mikeserv mentions in the comment, shift $((OPTIND-1)) can be unsafe. To prevent unwanted word-splitting etc, all parameter expansions should be double-quoted. So the safe form for the command is
shift "$((OPTIND-1))"

A:

$((...)) just calculates stuff. In your case it takes the value of $optint and substracts 1.
shift removes positional parameters. In your case it removes optint-1 parameters.
For more information have a look at help getopts, help shift, look at man bash for "Arithmetic Expansion", and especially google for getopts.


Q:

Why do the properties of determinants (used to calculate determinants from multiple matrices) apply not only to rows, but to columns as well?

A set of rules in my textbook is as follows:
a. If $A$ has a zero row (column), then $\det A = 0$
b. If $B$ is obtained by interchanging two rows (columns) of $A$, then $\det B = -\det A$
c. If $A$ has two identical rows (columns), then $\det A = 0$
d. If $B$ is obtained by multiplying a row (column) of $A$ by $k$, then $\det B = k\cdot\det A$
e. If $A$, $B$, and $C$ are identical except that the $i$-th row (column) of $C$ is the sum of the $i$-th rows (columns) of $A$ and $B$, then $\det C = \det B + \det A$
f. If $B$ is obtained by adding a multiple of one row (column) of $A$ to another row (column), then $\det B = \det A$
I don't understand why "column" is in parentheses after every instance of row. Is that the same as saying, for example with clause a: "if $A$ has a zero row or a zero column, then $\det A = 0$"? As in, it's saying that column and row can be used interchangably in the statement, as the statement holds true either way?
If the above interpretation is correct, then how? Why would these statements that apply to rows also apply to columns. The only situation I could see it applying is if the matrix is symmetrical, but the question doesn't specify that, it only says that the matrix is square.
Any help is appreciated.

A:

The trick is that $\det A^T=\det A$. Therefore, if there's a zero column in $A$ there's a zero row in $A^T$, implying $\det A^T=0$. You can check all the other copy-paste-to-column results in that way.


Q:

Objective-C Drawing without drawRect: shapes won't display

I have a class called mapWindow which is hooked up to a window in IB.
No matter what, the red circle which I want the program to render won't show up unless the code is under drawRect or I move the window borders. Not even unlocking and locking the focus updates the window.
theOtherWindowView is actually a NSView hooked up to a custom view in IB.
- (void)test
{
    [theOtherWindowView lockFocus];
    NSBezierPath *path = [NSBezierPath bezierPath];
    NSPoint center = [self drawPoint];
    [path moveToPoint: center];
    [path appendBezierPathWithArcWithCenter:center
                                        radius:explosionRadius
                                    startAngle:0
                                    endAngle:360];
    [[NSColor redColor] set];
    [path fill];

    [theOtherWindowView unlockFocus];
}

I don't want to use drawRect because I want multiple instances not one shape that has it's coordinates changed every update.
I've also tried [self lockFocus] and [mapWindow lockFous]

A:

Keep doing your drawing in -drawRect:.   When -drawRect: is sent, your view's coordinate system and clipping boundaries will have been set up for you, and your window's drawing context will be the current one.
In that method, draw as many of these circles as you want.


Q:

I want to write a get and set method using the arrow function

I am using typescript 3.1.6 .
Can I write a get and a set method using an arrow function:
export class foo {
/* attributures ... */
/* constructor ... */

/* ---- Example ---- */

get bar = ():string => this.anAttributeToGet;
set baz = (attr: string) => this.anAttributeToSet = attr;

/* ---- ( obviously does not run ) ---- */
}

instead of a function statement?
export class foo {
/* attributures ... */
/* constructor ... */

/* ---- Example ---- */

get bar():string{return this.anAttributeToGet;}
set baz(attr: string){this.anAttributeToSet = attr;}

/* ---- Example ---- */
}

A:

As far as i know, you cannot use arrow syntax for class getters/setters, unfortunately.


Q:

apn_sender gem daemon not running

Im using apn_sender for rails 3 and i have been able to install the gem and get it working just fine by using
rake apn:sender

I have tried to get it started in production mode on a ubuntu box by starting the daemon and it does not seem to work. When i type
script/apn_sender --environment=production --verbose start

I dont see anything. No log present.
when i try to type
script/apn_sender status

It returns with
apn_sender: no instances running

Just trying to understand why it is not running.

A:

i just solved this problem. Try to create a file called 'script' in generators/apn_sender/templates . .
Put this in your script file
# !/usr/bin/env ruby

# Daemons sets pwd to /, so we have to explicitly set RAILS_ROOT
RAILS_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))

require 'rubygems'
require 'apn'
require 'apn/sender_daemon'

APN::SenderDaemon.new(ARGV).daemonize

bash 'rails g apn_sender' in your terminal and will create 'script/apn_server' with same content as above
After that bash this code
./script/apn_server --environment=production --verbose start

it will create log/apn_sender.log . Try running
APN.notify('token',{:alert => '#' , :badge => 1})
or else in rails c to confirm if it works or not , and of course
rake apn:sender
Hope it will help :)
EDIT
You have to install redis and configure


Q:

Angular redirect to parameter in lazy loaded module

I have some lazy loaded routes as following:
const routes: Routes = [
    {
        path: ':lang',
        loadChildren: './components/home/home.module#HomeModule',
        // redirectTo: "en"
    },
    {
        path: ':id/customers',
        loadChildren: './components/customers/customers.module#CustomersModule'
    },
    {
        path: 'products',
        loadChildren: './components/products/products.module#ProductsModule'
    }
];

When I open the page with this url: http://localhost:4200/en it works fine. But the user doesn't know to add en parameter to the url, so the page doesn't load without parameter. So, I must redirect it to /en. But when I use redirectTo: "en" I get the following errors:
Error: Invalid configuration of route ':lang': redirectTo and loadChildren cannot be used together

I found something about this error, but doesn't relate to my case. Any idea?

A:

Setting redirectTo on the route :lang means: if the user is on that route, it should be redirected to /en. That's not what you want. You want to redirect the user to /enwhen the path is the root path. So you need to add an empty path route and redirect from there:
{
    path: '',
    redirectTo: '/en',
    pathMatch: 'full'
}


Q:

Before launch, run external tool asynchronously?

Is it possible to create run configurations where it doesn't wait for the external tool to exit before launching?
I'm currently trying to get Dart's pub serve to run on my project directory before opening the Dartium browser on localhost:8080 but it seems that it's just waiting for pub to exit before it does. Which won't happen as pub serve continues to show output from the local server.
Any ideas?

A:

Probably not the best answer, but this should work:
Create a wrapper script, say pub_async.bat, that asynchronously calls pub.bat with correct command line arguments and returns immediately.
You may lose the ability to "stop" the process, and so shutting down / cleaning up may need to be handled in a different way.


Q:

Why is Helen Magnus' Father Still Alive?

In Sanctuary, Helen Magnus appears to have stopped aging, even in the first few years of the series (to say nothing of what happened in Season 4).  But then her Father shows up and is in several episodes.  Yet there's no reference to him having had any connection with the Source Blood.
Why didn't he die at a "normal" age?  Will he not age, or is he aging extremely slowly?

A:

Later on in the series, there are a few more clues that pop up about Gregory Magnus's life.

He gave Helen the two pieces to the Praxis map when she was in her 20s and 30s.  So he definitely knew of the city's existence at that time.
He was well-known as a model citizen of Praxis.

Adam Worth was taken in openly, while Magnus and the rest of the Sanctuary team most definitely were not.  I doubt he could've become such a model citizen in just a year.

Adam Worth was also still alive due to the advanced medicine of Praxis.

Gregory Magnus's long life is, like Adam Worth, due to having lived in Praxis for so long.  However, because this is a retcon of the originally implied cryo-freezing by the Cabal, it leaves a gap as to why he left Praxis in the first place.  The Sanctuary wikia page on him does say he left so he could make contact with Helen, when he was captured by the Cabal.  However, I don't recall that being in an episode myself.

A:

In season 1, episode 10 Warriors, he's revived because the Cabal is interested in what he knows. It is not explained exactly how, but according to Wikipedia, citing the audio commentary for the episode on the DVD:

In writing "Warriors", Egan wanted to reintroduce Magnus' father Gregory Magnus from the webisodes; there were plans to introduce him in "Fata Morgana", but the idea did not make it to the final episode. Gregory was written not to have the longevity of his daughter. Egan decided not to include a full explanation of how he survived a hundred years without aging, but wanted to hint to the audience that he was in fact cryogenically frozen by the Cabal.

Presumably, then, he is aging at a normal rate and will die within a few decades.


Q:

Release Management vNext Component Deployment Bottleneck

We're using Release Management 2015 with vNext release templates. We have a Powershell DSC based component deployment for each of the portions of our application, and in fact, we have two distinct applications being deployed and that are in active development and are often deployed at nearly the same time.
We very frequently get the following error during deployments:

OperationFailedException: New deployment is not allowed as an another deployment is in progress. Retry the deployment after sometime.

The full stack trace shows that the error is coming not from Powershell itself, but from Release Management's system that's in charge of execution of the powershell script on the target machine:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.TeamFoundation.Release.Common.Helpers.OperationFailedException: New deployment is not allowed as an another deployment is in progress. Retry the deployment after sometime.
   at Microsoft.TeamFoundation.Release.EnvironmentProvider.OnPrem.Implementation.OnPremDeploymentProvider.ReadDeploymentResponse(DeploymentResponse response)
   at Microsoft.TeamFoundation.Release.EnvironmentProvider.OnPrem.Implementation.OnPremDeploymentProvider.RunScript(String scriptPath, String configurationPath, MachineSpecification machine, StorageSpecification storage, Dictionary`2 configurationVariables)
   at Microsoft.TeamFoundation.Release.MonitorServices.Dsc.OnPrem.OnPremDeploymentActions.InvokePlatform(String activityId, MachineSpecification machineSpecification, StorageSpecification storageSpecification, String scriptPath, String configurationPath, Dictionary`2 configurationVariables)
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.TeamFoundation.Release.DeploymentAgent.Services.Deployer.Dsc.DscComponentInstaller.InvokeMethodByReflection(String methodArguments)

The above error causes the entire deployment to fail, and we're forced to retry the stage or the entire deployment to have it finish.
There are two scenarios that cause this:

Two release templates execute their powershell scripts on the same target server at the same time
A single release template has a parallel control flow which contains two different components that both execute scripts on the same target server

In other words, the mechanism that Release Management uses to execute a powershell script on a remote server can only seem to ever execute a single script at a time, and has no ability to wait/hold for others to complete.
This kinda/sorta makes sense if the script in question as actively modifying the server on which it's executing, but in our case, the server acts as basically a staging area to run the script. The "real" target of the script has nothing to do with the server on which the powershell happens to be executing.
Aside from having a server-per-simultaneously-deployed-component (wow), what's the work around here? It seems like a major oversight and it's seriously making me consider dropping Release Management altogether.

A:

I was having an issue was well with running Powershell scripts on remote servers. I ended up going a slightly different route. Instead, I just run a normal Powershell command with an Invoke-Command block. I believe you should be able to run this in parallel.
Function Get-PSCredential($User,$Password) {
    $SecPass = ConvertTo-SecureString -AsPlainText -String $Password -Force
    $Creds = New-Object System.Management.Automation.PSCredential -ArgumentList $User,$SecPass
    Return $Creds
}

$credential = Get-PSCredential -User $deployUser -Password $deployPass
$session = New-PSSession YourServerName -Credential $credential

Invoke-Command -Session $session -ScriptBlock {
    # do your work here
}

If you are running as a service account that has access to the machine, you should be able to eliminate the credential stuff and just go with
$session = New-PSSession YourServerName

I only started using Release Management this week so this seemed the best way to go in that short amount of time.
Also, If you've never used Invoke-Command before, everything inside the script block is actually in its own scope so you need to pass your variables into it using -ArgumentList if you have any. Check out this article if you have any more questions about that.

A:

As I explained in another post today, MS Release Management's way of deploying is a bit counter-intuitive: Rather than just executing your Powershell deployment script against the target server using PSRemoting, it uses PSRemoting to install a Windows Service (VisualStudioRemoteDeployer.exe) on the target server. This service then runs your deployment script locally, and the MSRM server regularly polls this Windows service (see here) to see if it is finished deploying.
I suspect this strange setup has something to do with avoiding the double-hop issue - so that it allows your script to make a 2nd hop from the target server to another server, e.g. for a webservice call.
Anyway, this Windows service probably forms the bottleneck, because there can be only one such instance running per server - hence the fact that parallel deployments of components to the same server appear to collide.
I think your problems originate from the fact that you chose a setup where "the server acts as basically a staging area to run the script" - MS Release Management 2013/2015 doesn't play well in this scenario (as you found out), you should really deploy your components directly to the target servers on which they need to be installed, thus avoiding the staging area bottleneck.
The next version of MS Release Management will be using deployment agents that will serve as a staging point from which the components will be deployed to the other servers. This helps reducing the number of connections you have to allow on your firewall between the MS Release Management and the target servers (which is probably why you chose the staging area setup), while still allowing parallel (or at least queued) deployments.


Q:

Limit involving integral with fraction

$$\lim\limits_{x \to 0}\frac{\int_0^{x^2}\cos t^2dt}{(\sin x)^2}.$$How to compute such a limit never seen that kind before

A:

Let $F(t)$ be any primitive function of $\cos t^2$ (note that you don't need to calculate it!). Then
$$\lim_{x \to 0} \frac{\int_0^{x^2} \cos t^2 dt}{(\sin x)^2}  = \lim_{x \to 0} \frac{F(x^2)-F(0)}{x^2} = \lim_{x \to 0} \frac{2x \cos x^2}{2x} = 1$$
where in the first equality I used $\sin x \sim x$ and the fundamental theorem of integral calculus, while in the second I used L'Hopital.


Q:

string search in body.html() not working

Hi  here is my total work to search a string in HTML and highlight it if it is found in document:
The problem is here
var SearchItems = text.split(/\r\n|\r|\n/);
   var replaced = body.html();
   for(var i=0;i<SearchItems.length;i++)
   {
     var tempRep= '';
     tempRep = tempRep + SearchItems[i];
     tempRep = tempRep + '';
     replaced = replaced.replace(SearchItems[i],tempRep); // It is trying to match along with html tags...
     // As the  tags will not be there in search text, it is not matching...
   }
$("body").html(replaced);

The HTML I'm using is as follows;

The clipboardData object is reserved for editing actions performed through the Edit menu, shortcut menus, and shortcut keys. It transfers information using the system clipboard, and retains it until data from the next editing operation replace s it. This form of data transfer is particularly suited to multiple pastes of the same data.

This object is available in script as of Microsoft Internet Explorer 5.

If I search for a page which is pure or without any html tags it will match. However, if I have any tags in HTML this will not work.. Because I am taking body html() text as the target text. It is exactly trying to match along with html tags..
In fiddle second paragraph will not match.

A:

First of all, to ignore the HTML tags of the element to look within, use the .text() method.
Secondly, in your fiddle, it wasn't working because you weren't calling the SearchQueue function on load.
Try this amended fiddle


Q:

While trying to send POST request in HTTPCLIENT -JAVA, getting 400 Bad Request

I am trying to POST a request using JAVA HTTPCLIENT, and while doing so, I am getting 404 Bad Request.
I tried writing the JAVA code in Eclipse and got 404 Bad Request and tried sending the request through POSTMAN and received HTTP Status 500
package com.apex.customer.service;

public class CustServicePostTest {

    public static void main(String[] args) throws ClientProtocolException, IOException {

        String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/102";
        //create the http client
        HttpClient client = HttpClientBuilder.create().build();
        //create the post message
        HttpPost post = new HttpPost(url);

        List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
        urlParameters.add(new BasicNameValuePair("ID", "102"));
        urlParameters.add(new BasicNameValuePair("FIRSTNAME", "Apex"));
        urlParameters.add(new BasicNameValuePair("LASTNAME", "Consultancy"));
        urlParameters.add(new BasicNameValuePair("STREET", "Shell Blvd"));
        urlParameters.add(new BasicNameValuePair("CITY", "Fremont"));

        post.setEntity(new UrlEncodedFormEntity(urlParameters));

        HttpResponse response = client.execute(post);

        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println("Parameters : " + urlParameters);
        System.out.println("Response Code: " + response);
        System.out.println(response.getStatusLine().getReasonPhrase());

    }

}

I am looking for 200 OK request.

A:

The issue here is due few mistakes:

First is related to the input format. The code you're using tries to map key and values, but as I could see from this guide, it expects a XML format in a plain text as input.
The second mistake is that you are trying to post over an existing ID. In this case, to create a resource you should use http://www.thomas-bayer.com/sqlrest/CUSTOMER/

So in this case in order to make it work, try something like this:
        String url = "http://www.thomas-bayer.com/sqlrest/CUSTOMER/";
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);

        String xml = "<resource>";
        xml += "<ID>102</ID>";
        xml += "<FIRSTNAME>Apex</FIRSTNAME>";
        xml += "<LASTNAME>Consultancy</LASTNAME>";
        xml += "<STREET>Shell Blvd</STREET>";
        xml += "<CITY>Fremont</CITY>";
        xml += "</resource>";

        post.setEntity(new StringEntity(xml));
        HttpResponse response = client.execute(post);

        System.out.println(response.getStatusLine().getStatusCode());
        System.out.println("Response Code: " + response);
        System.out.println(response.getStatusLine().getReasonPhrase());

It is also very useful to learn another way to test it with tools like curl command line utility. For example you can POST a product like this:
curl -X POST  http://www.thomas-bayer.com/sqlrest/PRODUCT/ -d '<resource><ID>103</ID><NAME>X</NAME><PRICE>2.2</PRICE></resource>'

Once you solve this, it will be important to get used with HTTP codes. For example a 500 error means something wrong on the server side while a 404 usually means that you're hitting an invalid endpoint (it does not exists).
Finally, I'll not discuss why are you using this project to send HTTP requests to a server - but keep in mind that this is not a very common way to go. Currently the REST with JSON would be much more interesting and enjoyable :) In case you're interested on it, take a look on Spring Boot REST


Q:

How to filter or custom filter array of objects based on matching values from another object

I implemented an advance search with 15 input fields in AngularJS.
In the page load itself the result set is return from database in JSON format and i need to do the filter in client side only.
The input criteria's equivalent column is available in the result set and i need to check in its respective column only.
I am converting each column by JSON.stringify() and check with the search params like the below :
$scope.filteredData = $scope.actualData.filter(function(item) {
    return JSON.stringify(item.FirstName).toLowerCase().indexOf(lowerFirstName) != -1 &&
    JSON.stringify(item.LastName).toLowerCase().indexOf(lowerLastName) != -1 &&
    JSON.stringify(item.EmailAddress).toLowerCase().indexOf(lowerEmailAddress) != -1 &&
    JSON.stringify(item.Address1).toLowerCase().indexOf(lowerAddress1) != -1 &&
    JSON.stringify(item.Address2).toLowerCase().indexOf(lowerAddress2) != -1;
    ...... etc // upto 15 fields
});

Since i have the 15 input fields and the actual result set contains a minimum of 50,000 records.
So converting each record's each column by JSON.stringify() and check with search params will surely cause the performance issue.
Is there any other way to achieve the filtering in client side with other approach.
I posted a sample code in Plunker with 5 input fields only : http://plnkr.co/edit/nUWZEbGvz7HG6gb91YZP

A:

sylwester's answer is the normal way you'd filter things. Your code looks like you want to filter down to only the object that matches every input field. You code attempts to find an object where every property matches the searchParams object. At that point, I don't see what benefit there is to finding that object, because the user already created the object again! Nonetheless, here's a proper version of your code:
Live demo here.
<div ng-repeat="data in actualData | filter:searchData()">

 $scope.searchData = function() {
    return function(item) {
      return Object.keys(item).every(function(key) {
        // skip the $$hashKey property Angular adds to objects
        if (key === '$$hashKey') { return true; }
        var searchKey = key.charAt(0).toLowerCase()+key.slice(1);
        return item[key].toLowerCase() === $scope.searchParams[searchKey].toLowerCase();
      });
    };
  };

You really need to limit the data coming from the server for the browser's sake and for the server's sake. It's easy to implement a LIMIT, OFFSET system. It sounds like, overall, you just need to be able to query the server for a certain record.
From your comments, it seems you definitely want Angular's built in filter filter:searchParams, and just capitalize your searchParams models to match your data. For fun, I'll include more options for finer tuning.
This one almost mimics filter:searchParams. You can change > 1 to adjust when the partial matching kicks in, or have it return true only when both items are strictly equal === to disable partial matching. The difference here is that all items are hidden until matched, whereas filter:searchParams will show all items and then remove what doesn't match.
Live demo here.
  $scope.searchData = function() {
    return function(item) {
      return Object.keys(item).some(function(key) {
        if (key === '$$hashKey') { return false; }
        var searchKey = key.charAt(0).toLowerCase()+key.slice(1);
        var currentVal = $scope.searchParams[searchKey].toLowerCase();
        var match = item[key].toLowerCase().match(currentVal);
        return currentVal.length > 1 && match;
      });
    };
  };

Lastly, to perfectly mimic filter:searchParams, you'd just put in a check to NOT filter the items until there is user input and the input is long enough to start the partial match.
Live demo here.
  $scope.searchData = function() {
    var partialMatchLength = 2;
    return function(item) {
      var shouldFilter = Object.keys($scope.searchParams).some(function(key) {
        return $scope.searchParams[key] && $scope.searchParams[key].length >= partialMatchLength;
      });
      if (!shouldFilter) { return true; }
      return Object.keys(item).some(function(key) {
        if (key === '$$hashKey') { return false; }
        var searchKey = key.charAt(0).toLowerCase()+key.slice(1);
        var currentVal = $scope.searchParams[searchKey].toLowerCase();
        var match = item[key].toLowerCase().match(currentVal);
        return currentVal.length >= partialMatchLength && match;
      });
    };
  };