问:
Clean methodology for running a function for a large set of input parameters (in Matlab)
I have a differential equation that's a function of around 30 constants. The differential equation is a system of (N^2+1) equations (where N is typically 4). Solving this system produces N^2+1 functions.

Often I want to see how the solution of the differential equation functionally depends on constants. For example, I might want to plot the maximum value of one of the output functions and see how that maximum changes for each solution of the differential equation as I linearly increase one of the input constants.

Is there a particularly clean method of doing this?

Right now I turn my differential-equation-solving script into a large function that returns an array of output functions. (Some of the inputs are vectors & matrices). For example:

```<code>for i = 1:N
[OutputArray1(i, :), OutputArray2(i, :), OutputArray3(i, :), OutputArray4(i, :), OutputArray5(i, :)] =  DE_Simulation(Parameter1Array(i));
end
</code>```

Here I loop through the function. The function solves a differential equation, and then returns the set of solution functions for that input parameter, and then each is appended as a row to a matrix.

There are a few issues I have with my method:

If I want to see the solution to the differential equation for a different parameter, I have to redefine the function so that it is an input of one of the thirty other parameters. For the sake of code readability, I cannot see myself explicitly writing all of the input parameters as individual inputs. (Although I've read that structures might be helpful here, but I'm not sure how that would be implemented.)

I typically get lost in parameter space and often have to update the same parameter across multiple scripts. I have a script that runs the differential-equation-solving function, and I have a second script that plots the set of simulated data. (And I will save the local variables to a file so that I can load them explicitly for plotting, but I often get lost figuring out which file is associated with what set of parameters). The remaining parameters that are not in the input of the function are inside the function itself. I've tried making the parameters global, but doing so drastically slows down the speed of my code. Additionally, some of the inputs are arrays I would like to plot and see before running the solver. (Some of the inputs are time-dependent boundary conditions, and I often want to see what they look like first.)

I'm trying to figure out a good method for me to keep track of everything. I'm trying to come up with a smart method of saving generated figures with a file tag that displays all the parameters associated with that figure. I can save such a file as a notepad file with a generic tagging-number that's listed in the title of the figure, but I feel like this is an awkward system. It's particularly awkward because it's not easy to see what's different about a long list of 30+ parameters.

Overall, I feel as though what I'm doing is fairly simple, yet I feel as though I don't have a good coding methodology and consequently end up wasting a lot of time saving almost-identical functions and scripts to solve fairly simple tasks.

答:
It seems like what you really want here is something that deals with N-D arrays instead of splitting up the outputs.

If all of the OutputArray_ variables have the same number of rows, then the line

```<code> for i = 1:N
 [OutputArray1(i, :), OutputArray2(i, :), OutputArray3(i, :), OutputArray4(i, :), OutputArray5(i, :)] =  DE_Simulation(Parameter1Array(i));
 end
</code>```

seems to suggest that what you really want your function to return is an M x K array (where in this case, K = 5), and you want to pack that output into an M x K x N array.  That is, it seems like you'd want to refactor your DE_Simulation to give you something like

```<code> for i = 1:N
     OutputArray(:,:,i) = DE_Simulation(Parameter1Array(i));
 end
</code>```

If they aren't the same size, then a struct or a table is probably the best way to go, as you could assign to one element of the struct array per loop iteration or one row of the table per loop iteration (the table approach would assume that the size of the variables doesn't change from iteration to iteration).

If, for some reason, you really need to have these as separate outputs (and perhaps later as separate inputs), then what you probably want is a cell array.  In that case you'd be able to deal with the variable number of inputs doing something like

```<code> for i = 1:N
      [OutputArray{i, 1:K}] = DE_Simulation(Parameter1Array(i));
 end
</code>```

I hesitate to even write that, though, because this almost certainly seems like the wrong data structure for what you're trying to do.

Body:
I have a differential equation that's a function of around 30 constants. The differential equation is a system of (N^2+1) equations (where N is typically 4). Solving this system produces N^2+1 functions.

Often I want to see how the solution of the differential equation functionally depends on constants. For example, I might want to plot the maximum value of one of the output functions and see how that maximum changes for each solution of the differential equation as I linearly increase one of the input constants.

Is there a particularly clean method of doing this?

Right now I turn my differential-equation-solving script into a large function that returns an array of output functions. (Some of the inputs are vectors & matrices). For example:

for i = 1:N
[OutputArray1(i, :), OutputArray2(i, :), OutputArray3(i, :), OutputArray4(i, :), OutputArray5(i, :)] =  DE_Simulation(Parameter1Array(i));
end

Here I loop through the function. The function solves a differential equation, and then returns the set of solution functions for that input parameter, and then each is appended as a row to a matrix.

There are a few issues I have with my method:

If I want to see the solution to the differential equation for a different parameter, I have to redefine the function so that it is an input of one of the thirty other parameters. For the sake of code readability, I cannot see myself explicitly writing all of the input parameters as individual inputs. (Although I've read that structures might be helpful here, but I'm not sure how that would be implemented.)

I typically get lost in parameter space and often have to update the same parameter across multiple scripts. I have a script that runs the differential-equation-solving function, and I have a second script that plots the set of simulated data. (And I will save the local variables to a file so that I can load them explicitly for plotting, but I often get lost figuring out which file is associated with what set of parameters). The remaining parameters that are not in the input of the function are inside the function itself. I've tried making the parameters global, but doing so drastically slows down the speed of my code. Additionally, some of the inputs are arrays I would like to plot and see before running the solver. (Some of the inputs are time-dependent boundary conditions, and I often want to see what they look like first.)

I'm trying to figure out a good method for me to keep track of everything. I'm trying to come up with a smart method of saving generated figures with a file tag that displays all the parameters associated with that figure. I can save such a file as a notepad file with a generic tagging-number that's listed in the title of the figure, but I feel like this is an awkward system. It's particularly awkward because it's not easy to see what's different about a long list of 30+ parameters.

Overall, I feel as though what I'm doing is fairly simple, yet I feel as though I don't have a good coding methodology and consequently end up wasting a lot of time saving almost-identical functions and scripts to solve fairly simple tasks.

Body:
It seems like what you really want here is something that deals with N-D arrays instead of splitting up the outputs.

If all of the OutputArray_ variables have the same number of rows, then the line

 for i = 1:N
 [OutputArray1(i, :), OutputArray2(i, :), OutputArray3(i, :), OutputArray4(i, :), OutputArray5(i, :)] =  DE_Simulation(Parameter1Array(i));
 end

seems to suggest that what you really want your function to return is an M x K array (where in this case, K = 5), and you want to pack that output into an M x K x N array.  That is, it seems like you'd want to refactor your DE_Simulation to give you something like

 for i = 1:N
     OutputArray(:,:,i) = DE_Simulation(Parameter1Array(i));
 end

If they aren't the same size, then a struct or a table is probably the best way to go, as you could assign to one element of the struct array per loop iteration or one row of the table per loop iteration (the table approach would assume that the size of the variables doesn't change from iteration to iteration).

If, for some reason, you really need to have these as separate outputs (and perhaps later as separate inputs), then what you probably want is a cell array.  In that case you'd be able to deal with the variable number of inputs doing something like

 for i = 1:N
      [OutputArray{i, 1:K}] = DE_Simulation(Parameter1Array(i));
 end

I hesitate to even write that, though, because this almost certainly seems like the wrong data structure for what you're trying to do.


来源: stackexchange

问:
C programming - segmentation fault (core dump)
I am continuously getting a seg fault (core dump) each time that I run it, no matter what I change or the fact that is compiling fine! Not sure where I am making the mistake? Any suggestions?</p>

```<code>int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            exit (EXIT_FAILURE);
    }

    int data = 1;
    while (scanf("%d", data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}
</code>```

答:
```<code>while (scanf("%d", data) > 0)
</code>```

should be changed to

```<code>while (scanf("%d", &data) > 0)
</code>```

as scanf expects address of variable to be passed not the variable itself, if you pass a variable , scanf will end up accessing wrong memory by considering the value you passed as memory address, this will lead to undefined behavour

ContentLicense: CC BY-SA 3.0

Body:
I am continuously getting a seg fault (core dump) each time that I run it, no matter what I change or the fact that is compiling fine! Not sure where I am making the mistake? Any suggestions?

int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            exit (EXIT_FAILURE);
    }

    int data = 1;
    while (scanf("%d", data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}

Body:
while (scanf("%d", data) > 0)

should be changed to

while (scanf("%d", &data) > 0)

as scanf expects address of variable to be passed not the variable itself, if you pass a variable , scanf will end up accessing wrong memory by considering the value you passed as memory address, this will lead to undefined behavour


问:
Android Room - Select query with LIKE
I'm trying to make a query to search all objects whose names contain text:

```<code>@Query("SELECT * FROM hamster WHERE name LIKE %:arg0%")
fun loadHamsters(search: String?): Flowable<List<Hamster>>
</code>```

Messages:

```<code>Error:no viable alternative at input 'SELECT * FROM hamster WHERE name LIKE %'
Error:There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (near "%": syntax error)
Error:Unused parameter: arg0
</code>```

Also, I'm trying:

```<code>@Query("SELECT * FROM hamster WHERE name LIKE '%:arg0%'")
fun loadHamsters(search: String?): Flowable<List<Hamster>>
</code>```

Messages:

```<code>Error:Unused parameter: arg0
</code>```

How to fix this?

答:
You can just concat using SQLite string concatenation.</p>

```<code>@Query("SELECT * FROM hamster WHERE name LIKE '%' || :search || '%'")
fun loadHamsters(search: String?): Flowable<List<Hamster>>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Android Room - Select query with LIKE

Body:
I'm trying to make a query to search all objects whose names contain text:

@Query("SELECT * FROM hamster WHERE name LIKE %:arg0%")
fun loadHamsters(search: String?): Flowable<List<Hamster>>

Messages:

Error:no viable alternative at input 'SELECT * FROM hamster WHERE name LIKE %'
Error:There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (near "%": syntax error)
Error:Unused parameter: arg0

Also, I'm trying:

@Query("SELECT * FROM hamster WHERE name LIKE '%:arg0%'")
fun loadHamsters(search: String?): Flowable<List<Hamster>>

Messages:

Error:Unused parameter: arg0

How to fix this?

Body:
You can just concat using SQLite string concatenation.

@Query("SELECT * FROM hamster WHERE name LIKE '%' || :search || '%'")
fun loadHamsters(search: String?): Flowable<List<Hamster>>


问:
Why is jQuery .prop() not working for 'allowfullscreen'?
According to the documentation, the jQuery .prop() method only works for selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked and defaultSelected.

But as far as I checked and tried, it is not working for the iFrame attribute allowFullscreen.

However, this attribute is boolean, so if I want to set it to either work or not, it is not possible to do so with jQuery .attr(), since the attribute is active as long as any value is set. So the only way is to either set the attribute or remove it (again) completely which is at least not the optimal way to go.

Currently, I need to set it as follows:

```<code>allowFullscreen ? $iframe.attr('allowFullscreen', 'true') : $iframe.removeAttr('allowFullscreen');
</code>```

But it is somehow not working to normal/easy/logical way:

```<code>$iframe.prop('allowfullscreen', allowFullscreen);
</code>```

Is this a bug or is this somehow intended?

答:
For historical reasons, the distinction between HTML attributes and HTML properties is messy.  XHTML, being actual XML, did properties like disabled="disabled" so that they would parse as valid XML.  Luckily, HTML5 saved us from that hell.

The MDN documentation refers to HTML properties (like disabled) as "Boolean" attributes.

However, allowfullscreen is referenced as having a value that can be set to true rather than being a "Boolean" attribute.  In other words, allowfullscreen is an attribute not a property.

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#Attributes

allowfullscreen

  This attribute can be set to true if the frame is allowed to be placed into full screen mode by calling its Element.requestFullscreen() method. If this isn't set, the element can't be placed into full screen mode.

"Boolean" is not mentioned.  The value of "true" is another giveaway...

https://www.w3.org/TR/html5/infrastructure.html#boolean-attribute

Note: The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

If properties are ducks, allowfullscreen looks like a duck, swims like a duck, and quacks like a duck, but is not actually a duck.

Body:
According to the documentation, the jQuery .prop() method only works for selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked and defaultSelected.

But as far as I checked and tried, it is not working for the iFrame attribute allowFullscreen.

However, this attribute is boolean, so if I want to set it to either work or not, it is not possible to do so with jQuery .attr(), since the attribute is active as long as any value is set. So the only way is to either set the attribute or remove it (again) completely which is at least not the optimal way to go.

Currently, I need to set it as follows:

allowFullscreen ? $iframe.attr('allowFullscreen', 'true') : $iframe.removeAttr('allowFullscreen');

But it is somehow not working to normal/easy/logical way:

$iframe.prop('allowfullscreen', allowFullscreen);

Is this a bug or is this somehow intended?


问:
Using opencv4android,how to cut out video frame automatically when the camera is opened
There is a sample which can cut out the video frame in the official SDK.
The main code as follows:

```<code>@SuppressLint("SimpleDateFormat")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i(TAG,"onTouch event");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String currentDateandTime = sdf.format(new Date());
        String fileName = Environment.getExternalStorageDirectory().getPath() +
                               "/sample_picture_" + currentDateandTime + ".jpg";
        mOpenCvCameraView.takePicture(fileName);
        Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
        return false;
    }
</code>```

Now I want to change it to be a sample which can cute out video frame automatically. I had Commented the above code and changed the method named
onManagerConnected.The change as follows:

```<code>private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                    String filename = Environment.getExternalStorageDirectory().getPath()+"test"+".jpg";
                    mOpenCvCameraView.takePicture(filename);
                    Log.i(TAG, filename);
//                  mOpenCvCameraView.setOnTouchListener(Tutorial3Activity.this);
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };
</code>```

And then there throws a nullpointException showing  the var "mPictureFileName" and "mCamera" are null.

```<code> public void takePicture(final String fileName) {
            Log.i(TAG, "Taking picture");
            mPictureFileName = fileName;
            // Postview and jpeg are sent in the same buffers if the queue is not empty when performing a capture.
            // Clear up buffers to avoid mCamera.takePicture to be stuck because of a memory issue
            mCamera.setPreviewCallback(null);

            // PictureCallback is implemented by the current class
            mCamera.takePicture(null, null, this);
        }
</code>```

Anyway!

Thanks for answers!

答:
When the view opens, the camera isn't initating.So you can't cut out video in the method "initating".
I move those code to the the method "onCameraFrame".Done!</p>

```<code>public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    String filename = null;
    filename = Environment.getExternalStorageDirectory().getPath()+"/test"+i+".jpg";
    mOpenCvCameraView.takePicture(filename);
    Log.d("camera", filename);
    return inputFrame.rgba();
}
</code>```

Body:
There is a sample which can cut out the video frame in the official SDK.
The main code as follows:

@SuppressLint("SimpleDateFormat")
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Log.i(TAG,"onTouch event");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String currentDateandTime = sdf.format(new Date());
        String fileName = Environment.getExternalStorageDirectory().getPath() +
                               "/sample_picture_" + currentDateandTime + ".jpg";
        mOpenCvCameraView.takePicture(fileName);
        Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
        return false;
    }

Now I want to change it to be a sample which can cute out video frame automatically. I had Commented the above code and changed the method named
onManagerConnected.The change as follows:

private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
        @Override
        public void onManagerConnected(int status) {
            switch (status) {
                case LoaderCallbackInterface.SUCCESS:
                {
                    Log.i(TAG, "OpenCV loaded successfully");
                    mOpenCvCameraView.enableView();
                    String filename = Environment.getExternalStorageDirectory().getPath()+"test"+".jpg";
                    mOpenCvCameraView.takePicture(filename);
                    Log.i(TAG, filename);
//                  mOpenCvCameraView.setOnTouchListener(Tutorial3Activity.this);
                } break;
                default:
                {
                    super.onManagerConnected(status);
                } break;
            }
        }
    };

And then there throws a nullpointException showing  the var "mPictureFileName" and "mCamera" are null.

 public void takePicture(final String fileName) {
            Log.i(TAG, "Taking picture");
            mPictureFileName = fileName;
            // Postview and jpeg are sent in the same buffers if the queue is not empty when performing a capture.
            // Clear up buffers to avoid mCamera.takePicture to be stuck because of a memory issue
            mCamera.setPreviewCallback(null);

            // PictureCallback is implemented by the current class
            mCamera.takePicture(null, null, this);
        }

Anyway!

Thanks for answers!

Body:
When the view opens, the camera isn't initating.So you can't cut out video in the method "initating".
I move those code to the the method "onCameraFrame".Done!

public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
    String filename = null;
    filename = Environment.getExternalStorageDirectory().getPath()+"/test"+i+".jpg";
    mOpenCvCameraView.takePicture(filename);
    Log.d("camera", filename);
    return inputFrame.rgba();
}


问:
XAMPP (WIndows) PHP GMP Functions
Is there any way to use PHP GMP Functions on windows without using a virtual machine?

Thanks in advance.

[http://php.net/manual/en/ref.gmp.ph]

答:
According to GMP's website:

GMP's main target platforms are Unix-type systems, such as GNU/Linux, Solaris, HP-UX, Mac OS X/Darwin, BSD, AIX, etc. It also is known to work on Windows in both 32-bit and 64-bit mode.

Also try to uncomment ;extension=php_gmp.dll in php.ini

Hope it works!

Title: XAMPP (WIndows) PHP GMP Functions


问:
Android Rooms - Search in String
In the Android Rooms persistence library, how would I write the following SQL statement as a @Query?

SELECT * FROM table WHERE field LIKE %:value%

This syntax is invalid, and I can't find anything about it in the documentation.

答:
You can just concatenate using SQLite string concatenation.</p>
```<code>@Query("SELECT * FROM table WHERE field LIKE '%' || :value  || '%'")
</code>```

Title: Android Rooms - Search in String

Body:
You can just concatenate using SQLite string concatenation.

@Query("SELECT * FROM table WHERE field LIKE '%' || :value  || '%'")


问:
Publish test utils from maven project
I created a library in maven that can be extended by implementing some interfaces. To test the default implementation I have written some hamcrest matchers that currently live in src/test/java.

However, I think they might be useful for users of the library if they want to test their customization.

So how can I make them available? Moving them to src/main would require to make hamcrest a runtime dependency and I don't want that.

答: It sounds like you need to move them to their own project and release it. From there you can determine in the original project what scope you'd like.</p>

ContentLicense: CC BY-SA 2.5

Title: Publish test utils from maven project


问:
Default value for each type in typescript
Where can I find the default value of each type in typescript? For example, where is mentioned the default value for number type is null or 0.? Or about the string?

The default value means the value of a variable that is defined, but not assigned. Like let a : number;. This happens a lot in object definitions. For example:

```<code> class A{
     let a: number;
     let b: string;
 }
 let obj: A;
</code>```

Therefore, the question is on the values of a and b for obj.

答:
You have to remember that Typescript transpiles to javascript. In Javascript, the default value of an unassigned variable is undefined, as defined here.

For example, the following typescript code:

```<code>let a: string; console.log(a);
</code>```

will transpile to the following javascript and logs undefined.

```<code>var a; console.log(a);
</code>```

This also applies when you pass parameters to a function or a constructor of a class:

// Typescript
function printStr(str: string) {
    console.log(str);
}

class StrPrinter {
    str: string;
    constructor(str: string) {
        this.str = str;
        console.log(this.str);
    }
}

printStr();
let strPrinter = StrPrinter();```
</div>
</div>
</p>

<p>In the code example above, typescript will complain that the function and the class constructor is missing a parameter. Nevertheless, it will still transpile to transpile to:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function printStr(str) {
    console.log(str);
}
var StrPrinter = (function () {
    function StrPrinter(str) {
        this.str = str;
        console.log(this.str);
    }
    return StrPrinter;
}());
printStr();
var strPrinter = StrPrinter();</code>```

You might also want to see how typescript transpiles to javascript here.

Body:
Where can I find the default value of each type in typescript? For example, where is mentioned the default value for number type is null or 0.? Or about the string?

The default value means the value of a variable that is defined, but not assigned. Like let a : number;. This happens a lot in object definitions. For example:

 class A{
     let a: number;
     let b: string;
 }
 let obj: A;

Therefore, the question is on the values of a and b for obj.

Body:
You have to remember that Typescript transpiles to javascript. In Javascript, the default value of an unassigned variable is undefined, as defined here.

For example, the following typescript code:

let a: string; console.log(a);

will transpile to the following javascript and logs undefined.

var a; console.log(a);

This also applies when you pass parameters to a function or a constructor of a class:

// Typescript
function printStr(str: string) {
    console.log(str);
}

class StrPrinter {
    str: string;
    constructor(str: string) {
        this.str = str;
        console.log(this.str);
    }
}

printStr();
let strPrinter = StrPrinter();

In the code example above, typescript will complain that the function and the class constructor is missing a parameter. Nevertheless, it will still transpile to transpile to:

function printStr(str) {
    console.log(str);
}
var StrPrinter = (function () {
    function StrPrinter(str) {
        this.str = str;
        console.log(this.str);
    }
    return StrPrinter;
}());
printStr();
var strPrinter = StrPrinter();

You might also want to see how typescript transpiles to javascript here.


问:
How to set time taken in "Seconds" while uploading file to move?
I am doing MVC C# . I got a web page where user upload csv files. After uploading and saving data I write code to move the uploaded file to be moved with the same name to another folder in server,if another folder dont have means,we write code to create new folder. Now, the issue is, after move, if user immediately upload another file means the error message comes out "File Exists". My senior told me add seconds /milliseconds to the movepath file. Can anybody help how to add time? </p>

<p>my code is </p>

```<code>string Name = Path.GetFileNameWithoutExtension(loadPath);
            Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
                        string MovePath = System.IO.Path.Combine(Output, Name);

            if (!System.IO.Directory.Exists(Output))
            {
                System.IO.Directory.CreateDirectory(Output);
                System.IO.File.Move(loadPath, MovePath);
            }
            else
            {
                System.IO.File.Move(loadPath, MovePath);
            }
</code>```

答:
Your senior probably means for you to do something like this to burn a little time after the transfer (see the very last line):

```<code>string Name = Path.GetFileNameWithoutExtension(loadPath);
Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
string MovePath = System.IO.Path.Combine(Output, Name);
if (!System.IO.Directory.Exists(Output))
{
   System.IO.Directory.CreateDirectory(Output);
}
System.IO.File.Move(loadPath, MovePath);
System.Threading.Thread.Sleep(250); // sleeps the thread for 250 msecs
</code>```

EDIT

```<code>int sleepSeconds = 2;  // sleep for 2 seconds after moving file
string Name = Path.GetFileNameWithoutExtension(loadPath);
Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
string MovePath = System.IO.Path.Combine(Output, Name);
if (!System.IO.Directory.Exists(Output))
{
   System.IO.Directory.CreateDirectory(Output);
}
System.IO.File.Move(loadPath, MovePath);
System.Threading.Thread.Sleep(sleepSeconds * 1000); // sleeps the thread for sleepSeconds seconds
</code>```

Body:
I am doing MVC C# . I got a web page where user upload csv files. After uploading and saving data I write code to move the uploaded file to be moved with the same name to another folder in server,if another folder dont have means,we write code to create new folder. Now, the issue is, after move, if user immediately upload another file means the error message comes out "File Exists". My senior told me add seconds /milliseconds to the movepath file. Can anybody help how to add time?

my code is

string Name = Path.GetFileNameWithoutExtension(loadPath);
            Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
                        string MovePath = System.IO.Path.Combine(Output, Name);

            if (!System.IO.Directory.Exists(Output))
            {
                System.IO.Directory.CreateDirectory(Output);
                System.IO.File.Move(loadPath, MovePath);
            }
            else
            {
                System.IO.File.Move(loadPath, MovePath);
            }

Body:
Your senior probably means for you to do something like this to burn a little time after the transfer (see the very last line):

string Name = Path.GetFileNameWithoutExtension(loadPath);
Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
string MovePath = System.IO.Path.Combine(Output, Name);
if (!System.IO.Directory.Exists(Output))
{
   System.IO.Directory.CreateDirectory(Output);
}
System.IO.File.Move(loadPath, MovePath);
System.Threading.Thread.Sleep(250); // sleeps the thread for 250 msecs

EDIT

int sleepSeconds = 2;  // sleep for 2 seconds after moving file
string Name = Path.GetFileNameWithoutExtension(loadPath);
Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
string MovePath = System.IO.Path.Combine(Output, Name);
if (!System.IO.Directory.Exists(Output))
{
   System.IO.Directory.CreateDirectory(Output);
}
System.IO.File.Move(loadPath, MovePath);
System.Threading.Thread.Sleep(sleepSeconds * 1000); // sleeps the thread for sleepSeconds seconds


问:
Creating a file in Python. Beginner. How to format text in the created file
first post here...I'm learning about Python and I was able to learn how to create a .txt file from Python. However, in the tutorial I follow, once I run the code I am supposed to see these 4 lines in the .txt file

Hello World

This is our new text file

and this is another line.

Why? Because we can.

However what I see once I create the file is this:

Hello WorldThis is our new text fileand this is another line.Why? Because we can.

Basically instead of 4 different lines I see everything together in the same line. My question is, how can I make sure I am getting 4 lines and not everything together. Thank you, this is my code:

```<code>file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")

file.close()
</code>```

答:
Use "\n" in between your text, from where you want to start a new line. Just like below in the example :

Code :

```<code>f = open("Hello.txt","w")
f.write("This is first line.\nThis is second line.")

f = open("Hello.txt","r")
print(f.read())
</code>```

Output :

```<code>This is first line.
This is second line.
</code>```

Body:
first post here...I'm learning about Python and I was able to learn how to create a .txt file from Python. However, in the tutorial I follow, once I run the code I am supposed to see these 4 lines in the .txt file

Hello World

This is our new text file

and this is another line.

Why? Because we can.

However what I see once I create the file is this:

Hello WorldThis is our new text fileand this is another line.Why? Because we can.

Basically instead of 4 different lines I see everything together in the same line. My question is, how can I make sure I am getting 4 lines and not everything together. Thank you, this is my code:

file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")

file.close()

Body:
Use "\n" in between your text, from where you want to start a new line. Just like below in the example :

Code :

f = open("Hello.txt","w")
f.write("This is first line.\nThis is second line.")

f = open("Hello.txt","r")
print(f.read())

Output :

This is first line.
This is second line.


问:
Implement Gmail-like labels in a Rails app
This is more of an application design question then a specific Rails question. I'm trying to implement a system like "labels" within Gmail. So I want a user to be able to apply a label (or many) to a specific post. However, I also want the user to be able to manage labels using standard Rails CRUD.

Let's say I have a model called Post. So a user has many Posts. A user can create labels which is a separate model from Posts, but these can also be applied to posts with the use of checkboxes in the Post new/edit views. If a user deletes a specific label, it simply gets removed from the Post view and doesn't affect the Post in any other way.

This situation shows my lack of knowledge of db relationships, but is this a case for a has_many_and_belongs_to_many relationship?

If so, would the following design be the way to implement this?

User has_many Posts

User has_many Labels

Post has_many_and_belongs_to_many
Labels

Label has_many_and_belongs_to_many
Posts

Maybe I'm over thinking this and my logic is way off.

答: It sounds like you could implement this functionality through tags. Check out this post for a list of tagging plugins and gems for rails.</p>


问:
oracle RAC TAF session Failover
I use two nodes oracle RAC, I use a progress to connect to the database to do some data writing, while insert 100 rows I do a commit. I use the client-side TAF configuration of Session Failover.
So if the node 1 fail over, and I just insert 50 rows and do not execute the commit, when it automatically shift to the node 2, all the data I insert will be lost or will be insert again in the node 2, so the application of the progress will not concern about it?
Thanks for your help.</p>

答: All the data will be rollbacked for all transactional statement (insert, update ,delete). You have to configure in the source code that if failure occur then check for connection with other available node and insert process is re triggered from the code. Application will not be effected if it is configured in source code.</p>

Title: oracle RAC TAF session Failover


问:
Efficient SQL query for selecting records where a related record DOES NOT exist
I am trying to select a User where that User DOES NOT have an associated record with a certain value.

I have a User model, a User has_one Feed, a Feed has_many FeedTracks, a FeedTrack belongs_to a Track. I want to select Users only where they DO NOT have a FeedTrack with a certain TrackId.

I'm using rails but I would be open to strict SQL for this.

The best I've got is:

```<code> SELECT TOP 1000 *
 FROM Users u
 LEFT JOIN Feeds f ON f.user_id = u.id
 LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 ONLY IF ALL OF THOSE feedTracks' track_id !== <<track_id>>
</code>```

Obviously that last part statement is not real SQL and that's what my question is. How would I say, hey, get me the Users where this related record doesn't exist. But if that record does exist, don't return that User.

In other words, if that user has a feed, with a feed track with that track id, don't return that User. But if it doesn't, do return that User.

答:
You can use GROUP  BY and HAVING:

```<code>SELECT u.id
FROM Users u
LEFT JOIN Feeds f
    ON f.id = u.feed_id
LEFT JOIN FeedTracks ft
    ON ft.feed_id = f.id
GROUP BY u.id
HAVING
    SUM(CASE WHEN ft.track_id = @track_id THEN 1 ELSE 0 END) = 0
</code>```

Modify the columns in the SELECT and GROUP BY as needed.

Body:
I am trying to select a User where that User DOES NOT have an associated record with a certain value.

I have a User model, a User has_one Feed, a Feed has_many FeedTracks, a FeedTrack belongs_to a Track. I want to select Users only where they DO NOT have a FeedTrack with a certain TrackId.

I'm using rails but I would be open to strict SQL for this.

The best I've got is:

 SELECT TOP 1000 *
 FROM Users u
 LEFT JOIN Feeds f ON f.user_id = u.id
 LEFT JOIN FeedTracks ft ON ft.feed_id = f.id
 ONLY IF ALL OF THOSE feedTracks' track_id !== <<track_id>>

Obviously that last part statement is not real SQL and that's what my question is. How would I say, hey, get me the Users where this related record doesn't exist. But if that record does exist, don't return that User.

In other words, if that user has a feed, with a feed track with that track id, don't return that User. But if it doesn't, do return that User.

Body:
You can use GROUP  BY and HAVING:

SELECT u.id
FROM Users u
LEFT JOIN Feeds f
    ON f.id = u.feed_id
LEFT JOIN FeedTracks ft
    ON ft.feed_id = f.id
GROUP BY u.id
HAVING
    SUM(CASE WHEN ft.track_id = @track_id THEN 1 ELSE 0 END) = 0

Modify the columns in the SELECT and GROUP BY as needed.


问:
Is it possible to record “sign in audit reports” in Azure AD Microsoft (Individual) Accounts even though the documentation states otherwise?
previously, I had provided the following information to my customer.

https://support.office.com/en-us/article/Use-Azure-Active-Directory-sign-in-and-audit-reports-940d7b1b-4447-4024-b02c-e57c42121a96

“Events for the last 30 days are displayed in the list. The activity report includes the date and time that the user signed in, the application signed into, the user’s IP address, the user’s location when signing in, and the type of client device used to sign in. Events are logged for only work or school account sign-ins. Events aren’t logged when the user signs in using a Microsoft account.”

However, my customer has been able to confirm that Microsoft (Individual) Accounts do in fact record SOME audit report records (sign in audit records to be exact).  (He claims he knows that he knows for sure that the account he registered using OutlookJP did in fact record these reports. )

Also, my customer claims from experience that when inviting an Azure AD account / user from a different organization (Work Account), these reports were NOT recorded, which runs counter to what the documentation states

Is are there any other factors outside of the type of account used that would influence whether these signs in audit reports get recorded?

答:
In my test , both microsoft account and account from a different organization will include in Sign-ins activity in new portal .Below is microsoft account sign in logs :

And below is records for the account from a different organization:

Sign-ins don’t appear immediately in the sign-ins activity log. It can take anywhere from 15 minutes to 2 hours to see the sign-in logs in the Azure portal.

You could click here for more details about sign-in activity reports in the Azure Active Directory portal


问:
WPF BitmapSource ImageSource
I am binding an Image.Source property to the result of the property shown below.

```<code>public BitmapSource MyImageSource
{
    get
    {
        BitmapSource source = null;

        PngBitmapDecoder decoder;
        using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                source = decoder.Frames[0];
        }

        return source;
    }
}
</code>```

For some reason this is failing during the rendering of the image (Deep in the PresentationCore assembly). I am certain the image is not corrupt as I can successfully show the same image w/o the binding

```<code><Image Name="FooImage" Source="/logo.png" />
</code>```

I have to bind the image source in code because I will eventually be creating the image stream from a base64 string.

Anyone know if this is a bug w/ WPF? or am I doing something incorrectly?

答:
Also, have you tried just using a BitmapImage to load the image? It works fine with PNG, BMP, and JPEG.

It's also a specialized type of BitmapSource, so you could just replace your code in your property with this:

```<code>BitmapImage img = new BitmapImage(new Uri(@"C:\Temp\logo.png"));
return img;
</code>```

Title: WPF BitmapSource ImageSource

Body:
I am binding an Image.Source property to the result of the property shown below.

public BitmapSource MyImageSource
{
    get
    {
        BitmapSource source = null;

        PngBitmapDecoder decoder;
        using (var stream = new FileStream(@"C:\Temp\logo.png", FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);

            if (decoder.Frames != null && decoder.Frames.Count > 0)
                source = decoder.Frames[0];
        }

        return source;
    }
}

For some reason this is failing during the rendering of the image (Deep in the PresentationCore assembly). I am certain the image is not corrupt as I can successfully show the same image w/o the binding

<Image Name="FooImage" Source="/logo.png" />

I have to bind the image source in code because I will eventually be creating the image stream from a base64 string.

Anyone know if this is a bug w/ WPF? or am I doing something incorrectly?

Body:
Also, have you tried just using a BitmapImage to load the image? It works fine with PNG, BMP, and JPEG.

It's also a specialized type of BitmapSource, so you could just replace your code in your property with this:

BitmapImage img = new BitmapImage(new Uri(@"C:\Temp\logo.png"));
return img;

OwnerDisplayName: KP Adrian


问:
Infragistics UltraTree print/preview with nodes that have formatted/markup text
I'm trying to print/preview an Infragistics UltraTree (winform) (version 14.2) which has formatted/markup text

The nodes of the tree use Infragistics.Win.FormattedLinkLabel.UltraFormattedTextEditor
with TreatValueAs = FormattedLinkLabel.TreatValueAs.FormattedText

On the screen the tree looks nice.  However when I use Infragistics.Win.Printing.UltraPrintPreviewDialog, the resulting tree displays each node with all of its markups.

```<code><span style='color:Navy; font-size:11pt; font-weight:bold; '> The Node's Text  </span>
</code>```

Is there a way to have the preview display the same way it looks on the screen?  That is instead of the above, display "The Node's Text", where this text is printed in 11pt and the text color is navy.

答:
As @wnvko indicated, Infragistics acknowledges the bug which will be corrected in their next service release.  This is the statement I received from Infragistics:

Issue "237272: EditorComponent is not taken into account when printing
  the tree" has been fixed and verified by our Engineering Team in the
  following versions . We are in the final stages of creating the
  service release and expect to publish it according to following
  schedule:

http://www.infragistics.com/support/service-releases/

Body:
I'm trying to print/preview an Infragistics UltraTree (winform) (version 14.2) which has formatted/markup text

The nodes of the tree use Infragistics.Win.FormattedLinkLabel.UltraFormattedTextEditor
with TreatValueAs = FormattedLinkLabel.TreatValueAs.FormattedText

On the screen the tree looks nice.  However when I use Infragistics.Win.Printing.UltraPrintPreviewDialog, the resulting tree displays each node with all of its markups.

 The Node's Text

Is there a way to have the preview display the same way it looks on the screen?  That is instead of the above, display "The Node's Text", where this text is printed in 11pt and the text color is navy.


问:
laravel 5.0 delete and edit in database
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

```<code>@foreach ($allJobs as $job)
    <tr>
        <td><img src="{{$job->selected_icon}}" width="50" /> </td>
        <td>{{$job->jobtitle_de}}</td>
        <td>{{$job->location}}</td>
        <td><img src="{{$job->selected_image}}" width="100" /></td>
        <td>{{$job->workinghours}}</td>
        <td>{{$job->grey_header_de}}</td>
        <td>{{$job->date}}</td>
        <td>
            <a href=""><button>Edit</button></a> <a href="/delete">
            <button>Delete</button></a></td>
            <!--<td> <button type="delete" name="button"></button>-->
        <td>
        </td>
    </tr>
@endforeach
</code>```

答:
in your route:

```<code>Route::post('delete','CallyourController@delete');
Route::post('update','CallyourController@update');
</code>```

I think this is what you want to do.

Title: laravel 5.0 delete and edit in database

Body:
How can I delete or edit things from my database in Laravel 5.0 with the public function destroy and edit?

This is my library, here I want to delete or update something from my database

@foreach ($allJobs as $job)

        selected_icon}}" width="50" />
        {{$job->jobtitle_de}}
        {{$job->location}}
        selected_image}}" width="100" />
        {{$job->workinghours}}
        {{$job->grey_header_de}}
        {{$job->date}}

            <button>Edit</button>
            <button>Delete</button>

@endforeach

Body:
in your route:

Route::post('delete','CallyourController@delete');
Route::post('update','CallyourController@update');

I think this is what you want to do.


问:
Can not show jplayer full-screen control on mobile
From the developer guide page, jplayer has noFullWindow option.

Parameter: Object - Defines the user agent blocklist, which contains regular expressions, which cause the full-screen and restore-screen buttons to be hidden if a match is found.

This object has default value:

```<code>noFullWindow: {
    msie: /msie [0-6]\./,
    ipad: /ipad.*?os [0-4]\./,
    iphone: /iphone/,
    ipod: /ipod/,
    android_pad: /android [0-3]\.(?!.*?mobile)/,
    android_phone: /android.*?mobile/,
    blackberry: /blackberry/,
    windows_ce: /windows ce/,
    iemobile: /iemobile/,
    webos: /webos/
}
</code>```

I tried to set noFullWindow to null but wasn't successful.

答:
OK, I solved the problem.
My project is using the old version of jplayer (latest: 2.9.2, mine: 2.1.0)

jplayer version 2.1.0 has noFullScreen option instead of noFullWindow option.

Body:
From the developer guide page, jplayer has noFullWindow option.

Parameter: Object - Defines the user agent blocklist, which contains regular expressions, which cause the full-screen and restore-screen buttons to be hidden if a match is found.

This object has default value:

noFullWindow: {
    msie: /msie [0-6]\./,
    ipad: /ipad.*?os [0-4]\./,
    iphone: /iphone/,
    ipod: /ipod/,
    android_pad: /android [0-3]\.(?!.*?mobile)/,
    android_phone: /android.*?mobile/,
    blackberry: /blackberry/,
    windows_ce: /windows ce/,
    iemobile: /iemobile/,
    webos: /webos/
}

I tried to set noFullWindow to null but wasn't successful.


问:
Firebase Storage/Bucket public upload with node.js
Code:

```<code>var storage = require('@google-cloud/storage');
var gcs = storage({
    projectId: config.google.projectId,
    keyFilename: config.google.keyFilenameFirebase
});

var bucket = gcs.bucket('project-id.appspot.com');
var destination = 'uploads/12345/full.jpg';

bucket.upload(myFile, { public: true, destination: destination }, function(err, file) {
    if (err) {
        console.log(err);
    }
});
</code>```

My file is successfully uploaded to my firebase storage, but:

The file is now publicly accessible through the url:
https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg. Can I use this fixed URL in my App or is it likely, that it will change or expire?

public: true seems to break the Firebase Storage UI:

The preview of the image on the right side is not showing and I'm unable to download the image via the download button. Also, there is no download url (which I don't mind, cause I can access it via the link above) and when clicking "Create new download URL" Firebase yields

Error generating download URL

When removing public: true the preview is shown correctly and I can also generate a download URL. But the public url  https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg won't work anymore, which is necessary for me.

So my plan is to stick to public: true, but it still bugs me, that the preview/download button is not working and it looks like a bug in Firebase to me. Can anyone confirm that?

答:
1) It will not expire as long as it is always public. (I added a link related to this at the bottom)

2) Here's the quick fix. (You can do either of the following)

Add yourself in the default ACL (below is the command using gsutil)

gsutil defacl ch -u your_email@mail.com:OWNER gs://your_bucket;

Add yourself as a Storage Admin in the Google IAM admin console

Then reupload your file....

TL;DR

Here's the reason why, according to the Firebase Documentation:

You can use the Google Cloud Storage APIs to access files uploaded via
  Firebase SDKs for Cloud Storage, especially to perform more complex
  operations, such as copying or moving a file, or listing all the files
  available at a reference.

It's important to note that these requests use Google Cloud Storage
  ACLs or Project Level IAM, rather than Firebase Authentication and
  Storage Security Rules.

With regard to the public:true, I think that it will only enable and create the public link. Refer here

Body:
Code:

var storage = require('@google-cloud/storage');
var gcs = storage({
    projectId: config.google.projectId,
    keyFilename: config.google.keyFilenameFirebase
});

var bucket = gcs.bucket('project-id.appspot.com');
var destination = 'uploads/12345/full.jpg';

bucket.upload(myFile, { public: true, destination: destination }, function(err, file) {
    if (err) {
        console.log(err);
    }
});

My file is successfully uploaded to my firebase storage, but:

The file is now publicly accessible through the url:
https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg. Can I use this fixed URL in my App or is it likely, that it will change or expire?

public: true seems to break the Firebase Storage UI:

The preview of the image on the right side is not showing and I'm unable to download the image via the download button. Also, there is no download url (which I don't mind, cause I can access it via the link above) and when clicking "Create new download URL" Firebase yields

Error generating download URL

When removing public: true the preview is shown correctly and I can also generate a download URL. But the public url  https://storage.googleapis.com/project-id.appspot.com/uploads/12345/full.jpg won't work anymore, which is necessary for me.

So my plan is to stick to public: true, but it still bugs me, that the preview/download button is not working and it looks like a bug in Firebase to me. Can anyone confirm that?


问:
C programming - segmentation fault (core dump)
I am continuously getting a seg fault (core dump) each time that I run it, no matter what I change or the fact that is compiling fine! Not sure where I am making the mistake? Any suggestions?</p>

```<code>int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            exit (EXIT_FAILURE);
    }

    int data = 1;
    while (scanf("%d", data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}
</code>```

答:
1 change while (scanf("%d", data) > 0) to while (scanf("%d", &data) > 0) .

2 move the function of print to the begin.

This could work for you.

```<code>#include <stdio.h>
#include <string.h>
#define MAX 100

void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}

int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            return -1;
    }

    int data = 1;
    while (scanf("%d", &data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
</code>```

Input

1 2 3  "Enter"  "Ctrl+D"

Body:
I am continuously getting a seg fault (core dump) each time that I run it, no matter what I change or the fact that is compiling fine! Not sure where I am making the mistake? Any suggestions?

int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            exit (EXIT_FAILURE);
    }

    int data = 1;
    while (scanf("%d", data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}
void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}

Body:
1 change while (scanf("%d", data) > 0) to while (scanf("%d", &data) > 0) .

2 move the function of print to the begin.

This could work for you.

#include <stdio.h>
#include <string.h>
#define MAX 100

void print(FILE* output, int data)
{
    fprintf(output, "%d\n", data);
    return;
}

int main (int argc, char** argv)
{
    FILE *output;
    if ((output = fopen("output", "w")) == NULL)
    {
            printf ("cannot open the file input\n");
            return -1;
    }

    int data = 1;
    while (scanf("%d", &data) > 0)
    {
            print(output, data);
    }

    fclose(output);
    return (0);
}

Input

1 2 3  "Enter"  "Ctrl+D"


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答:
Whether it's binary or decimal doesn't really have anything to do with the integer itself. Binary or decimal is a property of a physical representation of the integer, i.e. a String. Thus, the methods you should look at are Integer.toString() and Integer.valueOf() (the versions that take a radix parameter).

BTW, internally, all Java integers are binary, but literals in the source code are decimal (or octal).

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?


问:
Remove the lines starting with a character in shell
I have dataset as:

```<code>file.txt
de
fds
fds
a
sa
1
2
3
1
}
</code>```

I would like to delete all the lines starting with characters or special characters. So my outfile is:

```<code>out.txt
1
2
3
1
</code>```

I could do it manually with 'sed', but I am looking for a suitable command for this.

my code:

```<code>sed -i '/d//g' file.txt
sed -i '/f//g' file.txt
sed -i '/a//g' file.txt
sed -i '/s//g' file.txt
sed -i '/}//g' file.txt
</code>```

答:
just keep lines starting with a number:

```<code>$ sed -i.bak -r '/^[0-9]/!d' filename
</code>```

or delete lines starting with specific characters:

```<code>$ sed -i.bak -r '/^[dfas}]/d' filename
</code>```

Body:
I have dataset as:

file.txt
de
fds
fds
a
sa
1
2
3
1
}

I would like to delete all the lines starting with characters or special characters. So my outfile is:

out.txt
1
2
3
1

I could do it manually with 'sed', but I am looking for a suitable command for this.

my code:

sed -i '/d//g' file.txt
sed -i '/f//g' file.txt
sed -i '/a//g' file.txt
sed -i '/s//g' file.txt
sed -i '/}//g' file.txt

Body:
just keep lines starting with a number:

$ sed -i.bak -r '/^[0-9]/!d' filename

or delete lines starting with specific characters:

$ sed -i.bak -r '/^[dfas}]/d' filename


问:
Query Optimizer and FK constraints
I have read that if you add a FK using WITH NOCHECK, the query optimizer will not use this FK in any query plan it generates. That got me to thinking about how and why would the query optimizer even consider a FK when generating a query plan? What benefit is there to the query engine if a FK is in place?</p>

答:
What may happen is that if you have a query that join other foreign key table, and if there is a foreign key constraint, the query engine can take advantage of using the foreign table index.

You can test it out by looking at the query execution plan in SQL Server Management Studio. It is under Query->Include Actual Execution Plan. Try one with FK and one WITH NOCHECK and see the difference.

Title: Query Optimizer and FK constraints


答: You can try to change DateTime.Now.ToString("ddMMMyyyyHHmm") to DateTime.Now.ToString("ddMMMyyyyHHmmss") ? So that if the user uploaded immediatelty, the filename wont be the same because of the seconds interval?

Title: How to set time taken in "Seconds" while uploading file to move?

Body:
I am doing MVC C# . I got a web page where user upload csv files. After uploading and saving data I write code to move the uploaded file to be moved with the same name to another folder in server,if another folder dont have means,we write code to create new folder. Now, the issue is, after move, if user immediately upload another file means the error message comes out "File Exists". My senior told me add seconds /milliseconds to the movepath file. Can anybody help how to add time?

my code is

string Name = Path.GetFileNameWithoutExtension(loadPath);
            Name = string.Format("{0}_{1}_{2}.csv", Name, SessionUtil.LoginUser.UserId, DateTime.Now.ToString("ddMMMyyyyHHmm"));
                        string MovePath = System.IO.Path.Combine(Output, Name);

            if (!System.IO.Directory.Exists(Output))
            {
                System.IO.Directory.CreateDirectory(Output);
                System.IO.File.Move(loadPath, MovePath);
            }
            else
            {
                System.IO.File.Move(loadPath, MovePath);
            }


问:
Why adding items to map during its iteration produce inconsistent result?
From Go Spec:

If map entries are created during iteration, that entry may be produced during the iteration or may be skipped.

So what I expect from that statement is that the following code should at least print number 1, and how many more numbers which are going to be printed is not predictable and is different each time you run the program:

```<code>package main

import (
    "fmt"
)

func main() {

    test := make(map[int]int)

    test[1] = 1
    j := 2
    for i, v := range test {
        fmt.Println(i, v)
        test[j] = j
        j++
    }

    return

}
</code>```

Go playground link

On my own laptop (Go version 1.8) at maximum it prints till 8, in playground (still version 1.8) it prints exactly till 3!
I don't care much about the result from playground since its go is not vanilla but I wonder why on my local it never prints more than 8? even I tried to add more items in each iteration to make the possibility of going over 8 higher but there's no difference.

EDIT: my own explanation based on @Schwern 's answer

when the map is created with make function and without any size parameter only 1 bucket is assigned and in go each bucket has a size of 8 elements, so when the range starts it sees that the map has only 1 bucket and it will iterate at maximum 8 times. If I use a size parameter bigger than 7 like make(map[int]int, 8) two buckets is created and there would be possibility that I get more than 8 iterations over the added items.

答:
This is an issue inherent in the design of most hash tables. Here's a simple explanation hand waving a lot of unnecessary detail.

Under the hood, a hash table is an array. Each key is mapped onto an element in the array using a hash function. For example, "foo" might map to element 8, "bar" might map to element 4, and so on. Some elements are empty.

for k,v := range hash iterates through this array in whatever order they happen to appear. The ordering is unpredictable to avoid a collision attack.

When you add to a hash, it adds to the underlying array. It might even have to allocate a new, larger array. It's unpredictable where that new key will land in the hash's array.

So if you add more pairs while you're iterating through the hash, any pair that gets put into the array before the current index won't be seen; the iteration has already past that point. Anything that gets put after might be seen; the iteration has yet to reach that point, but the array might get reallocated and the pairs possibly rehashed.

but I wonder why on my local it never prints more than 8

Because the underlying array is probably of length 8. Go likely allocates the underlying array in powers of 2 and probably starts at 8. The range hash probably starts by checking the length of the underlying array and will not go further, even if it's grown.

Long story short: don't add keys to a hash while iterating through it.

Body:
From Go Spec:

If map entries are created during iteration, that entry may be produced during the iteration or may be skipped.

So what I expect from that statement is that the following code should at least print number 1, and how many more numbers which are going to be printed is not predictable and is different each time you run the program:

package main

import (
    "fmt"
)

func main() {

    test := make(map[int]int)

    test[1] = 1
    j := 2
    for i, v := range test {
        fmt.Println(i, v)
        test[j] = j
        j++
    }

    return

}

Go playground link

On my own laptop (Go version 1.8) at maximum it prints till 8, in playground (still version 1.8) it prints exactly till 3!
I don't care much about the result from playground since its go is not vanilla but I wonder why on my local it never prints more than 8? even I tried to add more items in each iteration to make the possibility of going over 8 higher but there's no difference.

EDIT: my own explanation based on @Schwern 's answer

when the map is created with make function and without any size parameter only 1 bucket is assigned and in go each bucket has a size of 8 elements, so when the range starts it sees that the map has only 1 bucket and it will iterate at maximum 8 times. If I use a size parameter bigger than 7 like make(map[int]int, 8) two buckets is created and there would be possibility that I get more than 8 iterations over the added items.


问:
Node.js Callback not returning value to the calling function. Just timing out
So I think I have this correct but for some reason it is not executing the way I would think.  I am just wanting to decode the JWT Token and pass the data back.  Here is the code:

```<code>var jwtToken = function(message, callback) {
    var tokenArray = message.headers['authorization'];
    var array = tokenArray.toString().split(' ');

    if (array[0] == 'Bearer') {
        var token = array[1];
    } else {
        return callback.status(401).json({message: "bad json token"});
    }

    var map = JSON.parse(process.env.AUTH0_SECRET);

    var decoded = jwt2.decode(token, {complete: true});
    console.log('PAYLOAD:');
    console.log(decoded.payload);
    var clientId = decoded.payload.aud;
    var secret = map[clientId];

    //console.log('ENVIRONMENT SECRET: ' + map);
    //console.log('CLIENT ID: ' + clientId);
    //console.log('MAPPED SECRET: ' + secret);

    jwt2.verify(token, secret, function(err, decode){
        if (err) {
            callback.status(401).json({message: "JSON is incorrect or expired"})
        } else {
            callback = decode;
        }
    });
};

//route to make sure that the API works
app.get('/', function(req,res) {
    jwtToken(req, function(data){
       console.log(data);
       res.json({ message: 'You are connected to the API  ' + data})
    });
});
</code>```

What I would expect is that I pass in the request into the jwtToken function and I would get back the decoded Token in the callback.  I would then send the Response with the message and the decoded Token.  What I am getting is the data in the logs from the jwtToken call but then it keeps running till it times out.  I am just not sure what I messed up in the Callback that would stop it from sending the result back.  Thanks for your help.

答:
You're not calling the callback anywhere. Just assigning it to decode. You need to do:

```<code>callback(decode);
</code>```

Assuming decode is the value that you want in your data in the callback.

Body:
So I think I have this correct but for some reason it is not executing the way I would think.  I am just wanting to decode the JWT Token and pass the data back.  Here is the code:

var jwtToken = function(message, callback) {
    var tokenArray = message.headers['authorization'];
    var array = tokenArray.toString().split(' ');

    if (array[0] == 'Bearer') {
        var token = array[1];
    } else {
        return callback.status(401).json({message: "bad json token"});
    }

    var map = JSON.parse(process.env.AUTH0_SECRET);

    var decoded = jwt2.decode(token, {complete: true});
    console.log('PAYLOAD:');
    console.log(decoded.payload);
    var clientId = decoded.payload.aud;
    var secret = map[clientId];

    //console.log('ENVIRONMENT SECRET: ' + map);
    //console.log('CLIENT ID: ' + clientId);
    //console.log('MAPPED SECRET: ' + secret);

    jwt2.verify(token, secret, function(err, decode){
        if (err) {
            callback.status(401).json({message: "JSON is incorrect or expired"})
        } else {
            callback = decode;
        }
    });
};

//route to make sure that the API works
app.get('/', function(req,res) {
    jwtToken(req, function(data){
       console.log(data);
       res.json({ message: 'You are connected to the API  ' + data})
    });
});

What I would expect is that I pass in the request into the jwtToken function and I would get back the decoded Token in the callback.  I would then send the Response with the message and the decoded Token.  What I am getting is the data in the logs from the jwtToken call but then it keeps running till it times out.  I am just not sure what I messed up in the Callback that would stop it from sending the result back.  Thanks for your help.

Body:
You're not calling the callback anywhere. Just assigning it to decode. You need to do:

callback(decode);

Assuming decode is the value that you want in your data in the callback.


问:
Uncaught TypeError: Cannot read property 'indexOf' of undefined in javascript
```<code>var id    = $('.getval_'+product_id+''+index+'').attr("id");
var value = "";

console.log(id);
//data that return by id
6059
s2id_6061
6122
s2id_8410

if (id.indexOf('s2id_') > 0) {
    value = $('.getval_'+product_id+''+index+'').select2('val');
}else{
    value = $('.getval_'+product_id+''+index+'').val();
}
</code>```

Question:
The code above is show that when the ID return by jquery, then it will show a list of data, so what I want is when the ID return, if the in front of ID don't have s2id_ it will go else statement. But the code return an error which is (Uncaught TypeError: Cannot read property 'indexOf' of undefined)

答:
You need to check whether id itself is set, and there are two ways of going about this.

Either chain the if (id.indexOf('s2id_') > 0) condition inside an outer if condition that checks for id:

```<code>if (id) {
    if (id.indexOf('s2id_') > 0) {
        value = $('.getval_'+product_id+''+index+'').select2('val');
    }else{
        value = $('.getval_'+product_id+''+index+'').val();
    }
}
</code>```

Or check for both conditions with an and statement:

```<code>if (id && id.indexOf('s2id_') > 0) {
    value = $('.getval_'+product_id+''+index+'').select2('val');
}else{
    value = $('.getval_'+product_id+''+index+'').val();
}
</code>```

Hope this helps! :)

Body:
var id    = $('.getval_'+product_id+''+index+'').attr("id");
var value = "";

console.log(id);
//data that return by id
6059
s2id_6061
6122
s2id_8410

if (id.indexOf('s2id_') > 0) {
    value = $('.getval_'+product_id+''+index+'').select2('val');
}else{
    value = $('.getval_'+product_id+''+index+'').val();
}

Question:
The code above is show that when the ID return by jquery, then it will show a list of data, so what I want is when the ID return, if the in front of ID don't have s2id_ it will go else statement. But the code return an error which is (Uncaught TypeError: Cannot read property 'indexOf' of undefined)

Body:
You need to check whether id itself is set, and there are two ways of going about this.

Either chain the if (id.indexOf('s2id_') > 0) condition inside an outer if condition that checks for id:

if (id) {
    if (id.indexOf('s2id_') > 0) {
        value = $('.getval_'+product_id+''+index+'').select2('val');
    }else{
        value = $('.getval_'+product_id+''+index+'').val();
    }
}

Or check for both conditions with an and statement:

if (id && id.indexOf('s2id_') > 0) {
    value = $('.getval_'+product_id+''+index+'').select2('val');
}else{
    value = $('.getval_'+product_id+''+index+'').val();
}

Hope this helps! :)


问:
When I insert node in adjacent list, I couldn't get value on the graph
```<code>  6 typedef struct _Node{
  7   int vertex;
  8   struct _Node * next;
  9 }Node;
 10
 11 typedef struct _graph{
 12   Node *adj[MAX_TERMS];
 13 }Graph;
 14
 15 void Linsert(Graph * graph, int count, Node * temp)
 16 {
 17   Node * cur = graph->adj[count];
 18
 19   while(cur != NULL)
 20     cur = cur->next;
 21
 22   cur = temp;
 23   printf("%d\n", temp->vertex);
 24   printf("%d\n", (graph->adj[0])->vertex);
 25 }
 26

 27 int main()
 28 {
 29   FILE * fp = fopen("input.txt", "r");
 30   int n, vertex;
 31   int count = 0;
 32   Graph * graph;
 33   fscanf(fp, "%d", &n);
 34
 35   graph = (Graph*)malloc(sizeof(Graph));
 36
 37   for(int i = 0; i < n; i++)
 38     graph->adj[i] = NULL;
 39
 40   Node * temp = (Node*)malloc(sizeof(Node));
 41   temp->vertex = 1; temp->next = NULL;
 42   Linsert(graph, 0, temp);
 43  }
</code>```

I would like to push Node in the adjacent list.

When I called Linsert without "Line24", program worked well and printed "1"

But when I included Line24, compiler said

segmentation fault(core Dumped)

I don't know why I couldn't get value graph->adj[0]->vertex.

答:
Error occurs in the function Linsert(), code should be like this:</p>

```<code>void Linsert(Graph * graph, int count, Node * temp) {
        if (!graph->adj[count]) {
                graph->adj[count] = temp;
                return ;
        }
        cur = graph->adj[count];
        while (cur->next != NULL) {
                cur = cur->next;
        }
        // then cur is the final nodes of the graph[count]
        cur->next = temp;
        temp->next = NULL; // I suggest the phrase to be used in constructor.
}
</code>```

Body:
  6 typedef struct _Node{
  7   int vertex;
  8   struct _Node * next;
  9 }Node;
 10
 11 typedef struct _graph{
 12   Node *adj[MAX_TERMS];
 13 }Graph;
 14
 15 void Linsert(Graph * graph, int count, Node * temp)
 16 {
 17   Node * cur = graph->adj[count];
 18
 19   while(cur != NULL)
 20     cur = cur->next;
 21
 22   cur = temp;
 23   printf("%d\n", temp->vertex);
 24   printf("%d\n", (graph->adj[0])->vertex);
 25 }
 26

 27 int main()
 28 {
 29   FILE * fp = fopen("input.txt", "r");
 30   int n, vertex;
 31   int count = 0;
 32   Graph * graph;
 33   fscanf(fp, "%d", &n);
 34
 35   graph = (Graph*)malloc(sizeof(Graph));
 36
 37   for(int i = 0; i < n; i++)
 38     graph->adj[i] = NULL;
 39
 40   Node * temp = (Node*)malloc(sizeof(Node));
 41   temp->vertex = 1; temp->next = NULL;
 42   Linsert(graph, 0, temp);
 43  }

I would like to push Node in the adjacent list.

When I called Linsert without "Line24", program worked well and printed "1"

But when I included Line24, compiler said

segmentation fault(core Dumped)

I don't know why I couldn't get value graph->adj[0]->vertex.

Body:
Error occurs in the function Linsert(), code should be like this:

void Linsert(Graph * graph, int count, Node * temp) {
        if (!graph->adj[count]) {
                graph->adj[count] = temp;
                return ;
        }
        cur = graph->adj[count];
        while (cur->next != NULL) {
                cur = cur->next;
        }
        // then cur is the final nodes of the graph[count]
        cur->next = temp;
        temp->next = NULL; // I suggest the phrase to be used in constructor.
}


问:
Visual Studio 2017 does not have Business Intelligence Integration Services/Projects
I do not see an option to create an SSIS project using Visual Studio 2017. </p>

答:
Information on this will probably get outdated fast because Microsoft is running to complete its work on this, but as today, June 9th 2017, support to create SQL Server Integration Services (SSIS) projects on Visual Studio 2017 is not available. So, you can't see this option because so far it doesn't exist yet.

Beyond that, even installing what is being called SSDT (SQL Server Data Tools) in VS 2017 installer (what seems very confusing from Microsoft's part, using a known name for a different thing, breaking the behavior we expect as users), you won't see SQL Server Analysis Services (SSAS) and SQL Server Reporting Services (SSRS) project templates as well.

Actually, the Business Intelligence group under the Installed templates on the New Project dialog won't be present at all.

You need to go to this page (https://learn.microsoft.com/en-us/sql/ssdt/download-sql-server-data-tools-ssdt) and install two separate installers, one for SSAS and one for SSRS.

Once you install at least one of these components, the Business Intelligence group will be created and the correspondent template(s) will be available. But as today, there is no installer for SSIS, so if you need to work with SSIS projects, you need to keep using SSDT 2015, for now.


问:
how to get rid of all trailing question marks and exclamation points in a string - ruby
How can I get rid of the trailing question marks and exclamation points in this string:

```<code> str = "Hello!!!!! World???"
</code>```

so that the final result is:

```<code>str = "Hello! World?"
</code>```

I only want the first "?" and "!" in the string.

答:
You can probably tackle it with a simple regular expression:

```<code>while (line = DATA.gets)
  puts line.chomp.gsub(/([\?\!])+/, '\1')
end

__END__
Hello!! World??
Hello!?!?
Hello!!!!!!
</code>```

Which yields:

```<code>Hello! World?
Hello?
Hello!
</code>```

Just using DATA here for convenience, but this will work on any strings you might have.

Body:
How can I get rid of the trailing question marks and exclamation points in this string:

 str = "Hello!!!!! World???"

so that the final result is:

str = "Hello! World?"

I only want the first "?" and "!" in the string.

Body:
You can probably tackle it with a simple regular expression:

while (line = DATA.gets)
  puts line.chomp.gsub(/([\?\!])+/, '\1')
end

__END__
Hello!! World??
Hello!?!?
Hello!!!!!!

Which yields:

Hello! World?
Hello?
Hello!

Just using DATA here for convenience, but this will work on any strings you might have.


问:
can execute php file from browser but cron job get fatal error on shared server hostgator
I can execute my php scrape file by typing in the address bar:

```<code>domain.com/scrape.php
</code>```

However, I try to use cron job on my shared server on host gator by this command:

```<code>/usr/bin/php-cli public_html/scrape.php
</code>```

I got this error message:
Fatal error: Call to undefined function GuzzleHttp\Handler\curl_reset() in /home4/username/public_html/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 78
I already update my php version to stable 5.6 or even 5.7  version also same error. I think that it should not be php version error because I still can execute the file from browser right ?
Also I cannot reboot server Apache because hostgator support said they cannot reboot it until the server is totally down...
Any help please ! Thank you !

答: I ran into this problem last week on my own server.  As it turned out, my browser was looking at one installation of PHP and cron was looking at a 2nd installation of PHP.  One way to check is to run a PHP script through your browser that executes phpinfo().  That will tell you what the browser is running.  Have cron do the same and save the results.  Compare the two and make sure they're pointing to the same installation of PHP.  Don't just check versions.  Check install paths and loaded modules.  Cheers.</p>

Body:
I can execute my php scrape file by typing in the address bar:

domain.com/scrape.php

However, I try to use cron job on my shared server on host gator by this command:

/usr/bin/php-cli public_html/scrape.php

I got this error message:
Fatal error: Call to undefined function GuzzleHttp\Handler\curl_reset() in /home4/username/public_html/vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php on line 78
I already update my php version to stable 5.6 or even 5.7  version also same error. I think that it should not be php version error because I still can execute the file from browser right ?
Also I cannot reboot server Apache because hostgator support said they cannot reboot it until the server is totally down...
Any help please ! Thank you !


问:
Single Page Application Security
Just a random thought, how do  SPA make their sites secure ? I mean all the embedded script are accessible right? People can just download and analyze the code .. Any ideas ?

Plus when connecting to other web services you need to pass certain "keys", where will you put it if you don't want it to be viewed

答: In a SPA you will not store any sensitive data. Based on the data you get you can run some client side business login. You can use components to reduce the client-side code and component communication to reduce the backend calls. The main adv is UI/UX performance would be good trying to reduce backend calls.</p>

Title: Single Page Application Security


问:
how to sign .apk with existing jks file using jenkins?
Here is my current configuration.

I have already downloaded the plugin 'Android Signing Plugin'. I just don't know what to put in there since i already have a generated key.

I can't create a new one because i already published the application in playstore.

答:
What i did was write a build variant and signed configs in gradle like this

```<code>android {

    signingConfigs {
        releaseConfig{
            storeFile file("*****");
            storePassword ("****");
            keyAlias "*****";
            keyPassword "****"
        }
</code>```

and in build types

```<code>    buildTypes {
    release {
        minifyEnabled false
        debuggable false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
    debug{
        debuggable true
    }
</code>```

now my jenkis generate 2 apk files 1 debug and 1 signed.

More info here.

Let me know if you have a better answer. Thanks.

Body:
What i did was write a build variant and signed configs in gradle like this

android {

    signingConfigs {
        releaseConfig{
            storeFile file("*****");
            storePassword ("****");
            keyAlias "*****";
            keyPassword "****"
        }

and in build types

    buildTypes {
    release {
        minifyEnabled false
        debuggable false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        signingConfig signingConfigs.releaseConfig
    }
    debug{
        debuggable true
    }

now my jenkis generate 2 apk files 1 debug and 1 signed.

More info here.

Let me know if you have a better answer. Thanks.


问:
How to get One Signal user's unique player id in iOS?
How to retrieve the OneSignal users' unique player id in iOS?
I only found iOS SDK Setup in OneSignal Official Documentation.

Thanks if any suggestions are given.

答:
You need to use OneSignal's observers such as OSSubscriptionObserver.

```<code>// Add OSSubscriptionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSSubscriptionObserver {

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      // Add your AppDelegate as an subscription observer
      OneSignal.add(self as OSSubscriptionObserver)
   }

   // After you add the observer on didFinishLaunching, this method will be called when the notification subscription property changes.
   func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
      if !stateChanges.from.subscribed && stateChanges.to.subscribed {
         print("Subscribed for OneSignal push notifications!")
      }
      print("SubscriptionStateChange: \n\(stateChanges)")

      //The player id is inside stateChanges. But be careful, this value can be nil if the user has not granted you permission to send notifications.
      if let playerId = stateChanges.to.userId {
         print("Current playerId \(playerId)")
      }
   }
}
</code>```

For a better explanation, here is the documentation for addSubscriptionObserver

Body:
You need to use OneSignal's observers such as OSSubscriptionObserver.

// Add OSSubscriptionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSSubscriptionObserver {

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      // Add your AppDelegate as an subscription observer
      OneSignal.add(self as OSSubscriptionObserver)
   }

   // After you add the observer on didFinishLaunching, this method will be called when the notification subscription property changes.
   func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
      if !stateChanges.from.subscribed && stateChanges.to.subscribed {
         print("Subscribed for OneSignal push notifications!")
      }
      print("SubscriptionStateChange: \n\(stateChanges)")

      //The player id is inside stateChanges. But be careful, this value can be nil if the user has not granted you permission to send notifications.
      if let playerId = stateChanges.to.userId {
         print("Current playerId \(playerId)")
      }
   }
}

For a better explanation, here is the documentation for addSubscriptionObserver


问:
Cast/convert array of bytes to address
So I have an address where an offset for a vftable is located. it is stored in the assembly as bytes. ex: 03 c3 bd 0c

I want to get the bytes, and convert them little endian style to an address.

```<code>byte[0] = ((unsigned char *)addr)[3];
byte[1] = ((unsigned char *)addr)[2];
byte[2] = ((unsigned char *)addr)[1];
byte[3] = ((unsigned char *)addr)[0];
</code>```

so the output of the example would be 0x0cbdc303.

how can I correctly code this?

答:
```<code>byte[0] = ((unsigned char *)addr)[3];
byte[1] = ((unsigned char *)addr)[2];
byte[2] = ((unsigned char *)addr)[1];
byte[3] = ((unsigned char *)addr)[0];
</code>```

should be followed by

```<code>uint32_t address = (byte[0] << 24)|(byte[1] << 16)|(byte[2] << 8)|(byte[3]);
</code>```

Of course you can get rid of byte[] and substitute the original values into this.

Title: Cast/convert array of bytes to address

Body:
So I have an address where an offset for a vftable is located. it is stored in the assembly as bytes. ex: 03 c3 bd 0c

I want to get the bytes, and convert them little endian style to an address.

byte[0] = ((unsigned char *)addr)[3];
byte[1] = ((unsigned char *)addr)[2];
byte[2] = ((unsigned char *)addr)[1];
byte[3] = ((unsigned char *)addr)[0];

so the output of the example would be 0x0cbdc303.

how can I correctly code this?

Body:
byte[0] = ((unsigned char *)addr)[3];
byte[1] = ((unsigned char *)addr)[2];
byte[2] = ((unsigned char *)addr)[1];
byte[3] = ((unsigned char *)addr)[0];

should be followed by

uint32_t address = (byte[0] << 24)|(byte[1] << 16)|(byte[2] << 8)|(byte[3]);

Of course you can get rid of byte[] and substitute the original values into this.


问:
Laravel generate secure https URL from route
Edit

I can't really find a way to generate a secure URL from route name.

To get a full URL, I use

```<code>echo route('my_route_name');
</code>```

But what to do, if I want a URL with https?

答:
Use secure_url:

```<code>secure_url(URL::route('your_route_name', [], false));
</code>```

You will need to set URL::route to false in order to not return a full URL. Then use secure_url function generates a fully qualified HTTPS URL to the given path.

From the UrlGenerator interface you can use URL::route

```<code>string route(string $name, mixed $parameters = array(), bool $absolute = true)

Get the URL to a named route.
Parameters
string  $name
mixed   $parameters
bool    $absolute
Return Value
string
</code>```

https://laravel.com/api/5.4/Illuminate/Contracts/Routing/UrlGenerator.html

Body:
Edit

I can't really find a way to generate a secure URL from route name.

To get a full URL, I use

echo route('my_route_name');

But what to do, if I want a URL with https?

Body:
Use secure_url:

secure_url(URL::route('your_route_name', [], false));

You will need to set URL::route to false in order to not return a full URL. Then use secure_url function generates a fully qualified HTTPS URL to the given path.

From the UrlGenerator interface you can use URL::route

string route(string $name, mixed $parameters = array(), bool $absolute = true)

Get the URL to a named route.
Parameters
string  $name
mixed   $parameters
bool    $absolute
Return Value
string

https://laravel.com/api/5.4/Illuminate/Contracts/Routing/UrlGenerator.html


问:
Javascript: REGEX to change all relative Urls to Absolute
I'm currently creating a Node.js webscraper/proxy, but I'm having trouble parsing relative Urls found in the scripting part of the source, I figured REGEX would do the trick.
Although it is unknown how I would achieve this.

Is there anyway I can go about this?

Also I'm open to an easier way of doing this, as I'm quite baffle about how other proxies parse websites. I figured that most are just glorified site scrapers that can read a site's source a relay all links/forms back to the proxy.

答:
From a comment by Rob W above about the base tag I wrote an injection function:</p>

```<code>function injectBase(html, base) {
  // Remove any <base> elements inside <head>
  html = html.replace(/(<[^>/]*head[^>]*>)[\s\S]*?(<[^>/]*base[^>]*>)[\s\S]*?(<[^>]*head[^>]*>)/img, "$1 $3");

  // Add <base> just before </head>
  html = html.replace(/(<[^>/]*head[^>]*>[\s\S]*?)(<[^>]*head[^>]*>)/img, "$1 " + base + " $2");
  return(html);
}
</code>```

Body:
From a comment by Rob W above about the base tag I wrote an injection function:

function injectBase(html, base) {
  // Remove any <base> elements inside <head>
  html = html.replace(/(<[^>/]*head[^>]*>)[\s\S]*?(<[^>/]*base[^>]*>)[\s\S]*?(<[^>]*head[^>]*>)/img, "$1 $3");

  // Add <base> just before </head>
  html = html.replace(/(<[^>/]*head[^>]*>[\s\S]*?)(<[^>]*head[^>]*>)/img, "$1 " + base + " $2");
  return(html);
}


问:
React onRouteChange
I am trying to make my Header component render when the Route is changed.
I tried using onChange and onValueChange on the Switch but neither one gets called.
Is there a way to call a function whenever the route gets changed?</p>

```<code><Switch>
  <Route path="/posts/new" component={PostsNew}/>
  <Route path="/posts/:id" component={PostsShow}/>
  <Route exact path="/" component={PostsIndex}/>
</Switch>
</code>```

答:
After digging through the React Router docs (https://reacttraining.com/react-router/web/api/withRouter) I found a solution.

To make my header component update when the route changes all I had to do was import withRouter:

```<code>import {withRouter} from 'react-router-dom';
</code>```

and export the class using withRouter:

```<code>export default withRouter((connect(null, mapStateToProps)(Header)));
</code>```

Title: React onRouteChange

Body:
I am trying to make my Header component render when the Route is changed.
I tried using onChange and onValueChange on the Switch but neither one gets called.
Is there a way to call a function whenever the route gets changed?

<Switch>
  <Route path="/posts/new" component={PostsNew}/>
  <Route path="/posts/:id" component={PostsShow}/>
  <Route exact path="/" component={PostsIndex}/>
</Switch>

Body:
After digging through the React Router docs (https://reacttraining.com/react-router/web/api/withRouter) I found a solution.

To make my header component update when the route changes all I had to do was import withRouter:

import {withRouter} from 'react-router-dom';

and export the class using withRouter:

export default withRouter((connect(null, mapStateToProps)(Header)));


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答:
First thing you should understand is that a value is an abstract notion, that is not bounded to any representation. For example, if you have 20 apples, the number of apples will be the same regardless of the representation. So, dec("10") == bin("1010").

The value of an int reffers to this abstract notion of value, and it does not have any form until you with to print it. This means that the notion of base is important only for conversions from string to int and back.

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?


问:
Identity Server: redirect after logout with WS Federation
I try to redirect user after logout from Identity Server to my client app.
I use next code  for identity server setup:

```<code> RelyingParties = (from RelyingPartyElement element in section.RelyingParties
                          select new RelyingParty()
                          {
                              PostLogoutRedirectUris = new List<string>()
                              {
                                "http://localhost:xxx"
                              },
</code>```

Also,  signOutReply param has been set to "http://localhost:xxx/"  for ws federation section.
But it is not enough for redirect user after sign out.
What i need to do for achive goals, described above?

答:
Did you try this? You would need to add Owin Extensions and point to signout

https://identityserver.github.io/Documentation/docsv2/advanced/federated-signout.html

Body:
I try to redirect user after logout from Identity Server to my client app.
I use next code  for identity server setup:

 RelyingParties = (from RelyingPartyElement element in section.RelyingParties
                          select new RelyingParty()
                          {
                              PostLogoutRedirectUris = new List<string>()
                              {
                                "http://localhost:xxx"
                              },

Also,  signOutReply param has been set to "http://localhost:xxx/"  for ws federation section.
But it is not enough for redirect user after sign out.
What i need to do for achive goals, described above?


问:
Big O Notation Confusion (C++)
```<code>int f(const std::vector<int>& v) {
    int result = 0;
    for (int i = 0; i < v.size(); ++i) {                O(N)
        for (int j = v.size(); j >= 0; j -= 2) {        O(N/2)
            result += v.at(i) * j;
        }
    }
    return result;
}
</code>```

The inner for loop is O(N/2), however I am wondering why this is because

For example, if v.size() is 10, then

10 >= 0  ✓

8 >= 0 ✓

6 >= 0 ✓

4 >= 0  ✓

2>= 0 ✓

0 >= 0 ✓

-2 Fails

The inner for loop could be executed 6 times with an input size of 10

What am I missing?

EDIT* I understand that only highest magnitude is taken into consideration. This question was more about coming up with the original O(N/2 + 1)

答:
Complexity gives you a way to assess the magnitude of time it would take an input of certain size to complete, not the accurate time it would perform with.

Therefore, when dealing with complexity, you should only consider the highest magnitude, without constant multipliers:

```<code>O(N/2 + 1) = O(N/2) = O(N)
</code>```

Title: Big O Notation Confusion (C++)

Body:
int f(const std::vector<int>& v) {
    int result = 0;
    for (int i = 0; i < v.size(); ++i) {                O(N)
        for (int j = v.size(); j >= 0; j -= 2) {        O(N/2)
            result += v.at(i) * j;
        }
    }
    return result;
}

The inner for loop is O(N/2), however I am wondering why this is because

For example, if v.size() is 10, then

10 >= 0  ✓

8 >= 0 ✓

6 >= 0 ✓

4 >= 0  ✓

2>= 0 ✓

0 >= 0 ✓

-2 Fails

The inner for loop could be executed 6 times with an input size of 10

What am I missing?

EDIT* I understand that only highest magnitude is taken into consideration. This question was more about coming up with the original O(N/2 + 1)

Body:
Complexity gives you a way to assess the magnitude of time it would take an input of certain size to complete, not the accurate time it would perform with.

Therefore, when dealing with complexity, you should only consider the highest magnitude, without constant multipliers:

O(N/2 + 1) = O(N/2) = O(N)


问:
Creating a file in Python. Beginner. How to format text in the created file
first post here...I'm learning about Python and I was able to learn how to create a .txt file from Python. However, in the tutorial I follow, once I run the code I am supposed to see these 4 lines in the .txt file

Hello World

This is our new text file

and this is another line.

Why? Because we can.

However what I see once I create the file is this:

Hello WorldThis is our new text fileand this is another line.Why? Because we can.

Basically instead of 4 different lines I see everything together in the same line. My question is, how can I make sure I am getting 4 lines and not everything together. Thank you, this is my code:

```<code>file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")

file.close()
</code>```

答:
You can use print() in Python 3:

```<code>f = open('Hello.txt', 'w')
print('Hello World', file=f)
print('This is our new text file', file=f)
</code>```

The following works for both Python 2 and 3.

```<code>f = open('Hello.txt', 'w')
f.write("Hello World\n")
f.write("This is our new text file\n")
f.close()
</code>```

\n will be converted to os.linesep automatically by Python.

Body:
first post here...I'm learning about Python and I was able to learn how to create a .txt file from Python. However, in the tutorial I follow, once I run the code I am supposed to see these 4 lines in the .txt file

Hello World

This is our new text file

and this is another line.

Why? Because we can.

However what I see once I create the file is this:

Hello WorldThis is our new text fileand this is another line.Why? Because we can.

Basically instead of 4 different lines I see everything together in the same line. My question is, how can I make sure I am getting 4 lines and not everything together. Thank you, this is my code:

file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")

file.close()

Body:
You can use print() in Python 3:

f = open('Hello.txt', 'w')
print('Hello World', file=f)
print('This is our new text file', file=f)

The following works for both Python 2 and 3.

f = open('Hello.txt', 'w')
f.write("Hello World\n")
f.write("This is our new text file\n")
f.close()

\n will be converted to os.linesep automatically by Python.