问:
How to make cakephp cacheAction work with multilanguage
I'm working with cakephp 2.x

I've got a site with static pages (Multilanguage) and cacheAction.

The cache does not recognize the language and caches the page in the firest language....

Any idea how to solve (a part from disabling the cache?)
Thanks,
Massimo

```<code>class PagesController extends AppController {

/**
* This controller does not use a model
*
* @var array
*/
public $uses = array();
public $helpers = ['Cache','AbTest.AbTest'];
public $cacheAction = '1 month';
public $components = array('AbTest.AbTest');
</code>```

....

```<code>if ($locale && file_exists(APP . 'View' . $theme_path . DS .     $this->viewPath . DS . $locale .DS. implode('/', $path) . $this->ext ))
    {
        array_unshift($path,$locale);
    }

    try {
        $this->render(implode('/', $path));
    } catch (MissingViewException $e) {
        if (Configure::read('debug')) {
            throw $e;
        }
        throw new NotFoundException();
    }
</code>```

I expect the cache to present me ita/pages/who and eng/pages/who as different pages, while it outputs alway ita/pages/who

答:
There is an option for this called Cache.viewPrefix. You didn't mention how you manage the languages in your site, but the basic logic is that you can set the cache file prefix with the language and this way you will have separate cache files for every language. For example, you can do it in your PagesController or AppController like

Configure::write('Cache.viewPrefix', /* place the language here */);

Body:
I'm working with cakephp 2.x

I've got a site with static pages (Multilanguage) and cacheAction.

The cache does not recognize the language and caches the page in the firest language....

Any idea how to solve (a part from disabling the cache?)
Thanks,
Massimo

class PagesController extends AppController {

/**
* This controller does not use a model
*
* @var array
*/
public $uses = array();
public $helpers = ['Cache','AbTest.AbTest'];
public $cacheAction = '1 month';
public $components = array('AbTest.AbTest');

....

if ($locale && file_exists(APP . 'View' . $theme_path . DS .     $this->viewPath . DS . $locale .DS. implode('/', $path) . $this->ext ))
    {
        array_unshift($path,$locale);
    }

    try {
        $this->render(implode('/', $path));
    } catch (MissingViewException $e) {
        if (Configure::read('debug')) {
            throw $e;
        }
        throw new NotFoundException();
    }

I expect the cache to present me ita/pages/who and eng/pages/who as different pages, while it outputs alway ita/pages/who


来源: stackexchange

问:
JavaScript: How to display time using a switch statement?
I want to generate a custom time-formatted string via a switch statement where the date information is passed in an array.

For an array like this:

let displaySumTimes = ['00', '00', '10']

the expected output would be:

10sec

If a value in the array is greater than zero, then that should be included in the formatted string that is returned from my switch statement. Each non-zero value in the result also needs to have the corresponding time unit included with it in the formatted string result.

My current code looks like this:

```<code> let displaySumTimes = ['00', '00', '10'];

 const formatTime = (time) => {
  const [hour, minute, sec] = time.split(':');
  console.log([hour, minute, sec]);
  switch([hour, minute, sec]) {
    case hour > 0:
      return `${hour} h ${minute} min ${sec} sec`;
      break;
    case minute > 0:
      return `${minute} min ${sec} sec`;
      break;
    case minute < 1:
      return `${sec} sec`;
    default:
      // code block
  }
}

 formatTime(displaySumTimes); //output 10sec

 let displaySumTimes1 = ['00', '10', '10'];

 formatTime(displaySumTimes1); //output 10min 10 sec
</code>```

答:
Perhaps you could take a functional approach to this which would avoid the need for a switch statement.

For instance, you could dynamically build a list containing each part of the formatted string result (which is built based on the input values), and then join() that list a white-space character to compose a string with the required format:

const formatTime = (time) => {
  const [h, m, s] = time;

  /* Dynamically build a temporary list containing each part of the formatted time depending
  on input values supplied*/
  return [].concat(
    h > 0 ? [`${ h }hr`] : [],
    m > 0 ? [`${ m }min`] : [],
    s > 0 ? [`${ s }sec`] : [])
  /* Join each part of the formatted time with a whitespace to achieve required formatting */
  .join(' ');
}

let displaySumTimes = ['00', '00', '10'];
let displaySumTimes1 = ['00', '10', '10'];

console.log(formatTime(displaySumTimes)); //output 10sec
console.log(formatTime(displaySumTimes1)); //output 10min 10 sec```

ContentLicense: CC BY-SA 4.0

Body:
I want to generate a custom time-formatted string via a switch statement where the date information is passed in an array.

For an array like this:

let displaySumTimes = ['00', '00', '10']

the expected output would be:

10sec

If a value in the array is greater than zero, then that should be included in the formatted string that is returned from my switch statement. Each non-zero value in the result also needs to have the corresponding time unit included with it in the formatted string result.

My current code looks like this:

 let displaySumTimes = ['00', '00', '10'];

 const formatTime = (time) => {
  const [hour, minute, sec] = time.split(':');
  console.log([hour, minute, sec]);
  switch([hour, minute, sec]) {
    case hour > 0:
      return `${hour} h ${minute} min ${sec} sec`;
      break;
    case minute > 0:
      return `${minute} min ${sec} sec`;
      break;
    case minute < 1:
      return `${sec} sec`;
    default:
      // code block
  }
}

 formatTime(displaySumTimes); //output 10sec

 let displaySumTimes1 = ['00', '10', '10'];

 formatTime(displaySumTimes1); //output 10min 10 sec


问:
How to parse string value from xlworksheet to time(hh:mm) value into the newsheet?
I can't convert my object "Time" which has properties in0 and out0 from string to DateTime.

```<code>for (int row = 2; row <= rw; row++)
                    {
                        for (cCnt = 6; cCnt <= 6; cCnt++)
                        {
                            var in0 = (String)(xlworkSheet.Cells[row, 7]
                             as Excel.Range).Value;
                            Time.In0 = in0;
                            Console.WriteLine(Time.In0.ToString());
                            DateTime dtnew = DateTime.Parse(in0);

                            Excel.Range formatRange;
                            formatRange = xlNewSheet.Cells[row, 7];
                            formatRange.NumberFormat = "hh:mm";
                            xlNewSheet.Cells[row, 7].Value = Time.In0;

                        }
                    }
 //this is my class
  public class DateandTime
      {
       public string In0 { get; set; }
       public string Out0 { get; set; }
       public string In1 { get; set; }
       public string Out1 { get; set; }
       public string In2 { get; set; }
       public string Out2 { get; set; }
       public string In3 { get; set; }
       public string Out3 { get; set; }
       public string In4 { get; set; }
       public string Out4 { get; set; }
       public string break_time { get; set; }

         }
</code>```

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

答:
'String was not recognized as a valid DateTime' says the value that you are providing to the Parse method is not valid to proceed with the conversion. This means you should look at the possibility of invalid casting happening at the following line:

```<code>var in0 = (String)(xlworkSheet.Cells[row, 7] as Excel.Range).Value;
</code>```

This could also be true that there exists no explicit casting between the Value field to String which then can be converted to a valid date format.
For me, it sounds like Excel.Range value returns a collection of some type such as an array and there exists no implicit conversion from this array to string, which is convertible to a valid date format.

Update: You may check following urls for the beter understanding of Range and Values.

Worksheet.Range

Value

Body:
I can't convert my object "Time" which has properties in0 and out0 from string to DateTime.

for (int row = 2; row <= rw; row++)
                    {
                        for (cCnt = 6; cCnt <= 6; cCnt++)
                        {
                            var in0 = (String)(xlworkSheet.Cells[row, 7]
                             as Excel.Range).Value;
                            Time.In0 = in0;
                            Console.WriteLine(Time.In0.ToString());
                            DateTime dtnew = DateTime.Parse(in0);

                            Excel.Range formatRange;
                            formatRange = xlNewSheet.Cells[row, 7];
                            formatRange.NumberFormat = "hh:mm";
                            xlNewSheet.Cells[row, 7].Value = Time.In0;

                        }
                    }
 //this is my class
  public class DateandTime
      {
       public string In0 { get; set; }
       public string Out0 { get; set; }
       public string In1 { get; set; }
       public string Out1 { get; set; }
       public string In2 { get; set; }
       public string Out2 { get; set; }
       public string In3 { get; set; }
       public string Out3 { get; set; }
       public string In4 { get; set; }
       public string Out4 { get; set; }
       public string break_time { get; set; }

         }

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: String was not recognized as a valid DateTime.

Body:
'String was not recognized as a valid DateTime' says the value that you are providing to the Parse method is not valid to proceed with the conversion. This means you should look at the possibility of invalid casting happening at the following line:

var in0 = (String)(xlworkSheet.Cells[row, 7] as Excel.Range).Value;

This could also be true that there exists no explicit casting between the Value field to String which then can be converted to a valid date format.
For me, it sounds like Excel.Range value returns a collection of some type such as an array and there exists no implicit conversion from this array to string, which is convertible to a valid date format.

Update: You may check following urls for the beter understanding of Range and Values.

Worksheet.Range

Value


问:
How can I get specific object key in map iteration
I have one json file and I iterate it with map but I have a deep object key with name 'content' and  I want to get specific key from it when I return my json array with map

JSON:

```<code>{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}
</code>```

My javascript code:

```<code>getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts)
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title,
       link: item.link,
       image: item.content._url,
       // and here I try get _url
       id: item.guide,

    }

}
</code>```

答:
To correctly handle all cases, remember to always check whether the property effectively exists:

```<code>return {
       title: item.title,
       link: item.link,
       image: (item.content && item.content._url) ? item.content._url : '', // <-- fix here.
       id: item.guide,

    }
</code>```

Possible issues probably were:

Typo on your line: item.conten._url, (should be content)

item with missing content. In that case, item.content._url would raise an exception. Adding a ternary operator like I did above will ensure the property exists, otherwise it will set the default value to ''. Feel free to change it if that's not the intended default value.

Body:
I have one json file and I iterate it with map but I have a deep object key with name 'content' and  I want to get specific key from it when I return my json array with map

JSON:

{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}

My javascript code:

getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts)
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title,
       link: item.link,
       image: item.content._url,
       // and here I try get _url
       id: item.guide,

    }

}

Body:
To correctly handle all cases, remember to always check whether the property effectively exists:

return {
       title: item.title,
       link: item.link,
       image: (item.content && item.content._url) ? item.content._url : '', // <-- fix here.
       id: item.guide,

    }

Possible issues probably were:

Typo on your line: item.conten._url, (should be content)

item with missing content. In that case, item.content._url would raise an exception. Adding a ternary operator like I did above will ensure the property exists, otherwise it will set the default value to ''. Feel free to change it if that's not the intended default value.


问:
Browser-compatibility with IE 7 and below
Surely there is an easier way of doing this. The IE comment tags were the only way I could make the page look right in IE 7 and below.

EDIT: I'm not too sure why this got down-voted. It's a legitimate question. If anyone should get down-voted, it's those who have discussed this as of now. Nobody is answering the question. They are either too vague or telling me what not to do. I already know that. That is why I am asking what the better way is.

答:
You shouldn't need to use an html table just to get IE7 working, and in fact you shouldn't use them at all if you're not intending to display tabular data.

Instead of all those messy conditions, just use one immediately after your stylesheet import to add an IE specific stylesheet.

Consider creating another container for your form, and instead of trying to make the form display as table use positioning to place your new container in the corner instead.  This is more likely to translate well into older versions of IE, and so your IE specific styles will only be needed to correct minor box model differences.

ContentLicense: CC BY-SA 3.0


问:
Select data where condition matches and if none, then select all?

select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id
```

<p>scenario1:
     @id = 'user1'</p>

```dept1
```

<p>scenario2:
    @id = 'user5'</p>

```dept1
dept2
dept3
dept4
```

<p>this is what it looks like from a noobish query</p>

<pre class="lang-sql prettyprint-override"><code>declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0
</code>```

答:
You can have a slightly better execution plan if you separate the "if exist" logic from the actual query:</p>

```<code>DECLARE @id varchar(10) = 'user5'
DECLARE @table TABLE ([department] varchar(10), [user] varchar(10))

insert into @table values
                    ('dept1','user1'),
                    ('dept2','user2'),
                    ('dept3','user3'),
                    ('dept4','user4')

DECLARE @exists BIT =
(SELECT 1 FROM @table WHERE [user] = @id)

SELECT department FROM @table
WHERE [user] = CASE @exists WHEN 1 THEN @id ELSE [user] END
</code>```

Body:
select * from (values
    ('dept1','user1'),
    ('dept2','user2'),
    ('dept3','user3'),
    ('dept4','user4')
    )table1([department],[user])
where [user] = @id

scenario1:
     @id = 'user1'

dept1

scenario2:
    @id = 'user5'

dept1
dept2
dept3
dept4

this is what it looks like from a noobish query

declare @id varchar(12) = 'user1'
declare @var int = (select count(*) from table1 where [user] = @id)

select * from table1 where [user] = @id or @var = 0

Body:
You can have a slightly better execution plan if you separate the "if exist" logic from the actual query:

DECLARE @id varchar(10) = 'user5'
DECLARE @table TABLE ([department] varchar(10), [user] varchar(10))

insert into @table values
                    ('dept1','user1'),
                    ('dept2','user2'),
                    ('dept3','user3'),
                    ('dept4','user4')

DECLARE @exists BIT =
(SELECT 1 FROM @table WHERE [user] = @id)

SELECT department FROM @table
WHERE [user] = CASE @exists WHEN 1 THEN @id ELSE [user] END


问:
Should we modify a function signature for unit testing?
Suppose we have a function add() as below:

```<code>void add(int a, int b) {
    int sum=a+b;
    cout<<sum;
    sendSumToStorage(sum);
}
</code>```

This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file).  This is how we ideally want it in the application (meaning, we don't want it to return anything).

For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the sum?  We could then have a test like:

```<code>bool checkAdd() {
    int res=add(3, 4);
    if(res==7) return true;
    else return false;
}
</code>```

Better yet, is this (returning a value) the only way we could unit test it?  Is there some valid way in which we could unit test the add() function without changing the function signature?

答:
Ignoring the fact that this example has a bad desing.

For cases like this, when you want to check some internal behaviour instead of API you should rather try using some testing libraries like gtest and gmock.
It allows you to describe more sophisticated expectations than just function result.

For example you can set expectation that some method will be called during code execution using EXPECT_CALL macro.

More details here:
https://github.com/google/googletest/blob/master/googlemock/docs/ForDummies.md

Answering your question, it's always a bad practice to modify any part of tested code for the purpose of testing. In that case you are not longer testing production code. As it was suggested before it's better to split the functionality into smaller parts and test them isolated.

Body:
Suppose we have a function add() as below:

void add(int a, int b) {
    int sum=a+b;
    cout<<sum;
    sendSumToStorage(sum);
}

This simple function adds to input values, prints the sum to the console and also sends it to some external storage (say, a file).  This is how we ideally want it in the application (meaning, we don't want it to return anything).

For purposes of unit testing, is it valid (from a design perspective) if we modify the function signature so that it returns the sum?  We could then have a test like:

bool checkAdd() {
    int res=add(3, 4);
    if(res==7) return true;
    else return false;
}

Better yet, is this (returning a value) the only way we could unit test it?  Is there some valid way in which we could unit test the add() function without changing the function signature?


问:
How to add initial value without edit initial value on Flutter?
I added initial value like this, But user can edit initial text. How to disable to edit initial value? But user can be able to add value with initial value?

```<code> var _myController = TextEditingController(text: "https://");
</code>```

Output should be like this

```<code>print(url);
</code>```

https://(user_type_value)

答: As far as I understand, you need something like masked edit, look here: https://github.com/benhurott/flutter-masked-text/blob/master/README.md</p>

Body:
I added initial value like this, But user can edit initial text. How to disable to edit initial value? But user can be able to add value with initial value?

 var _myController = TextEditingController(text: "https://");

Output should be like this

print(url);

https://(user_type_value)


问:
Can I change the Aspnet-version of my logic app?
I was recently handed over the support of an already built logic app that accepts some json and performs some validations and send it to some endpoint. There's nothing wrong with the Logic app functionality, it works completely fine.

The problem is, penetration testing was done on the app and it presented us with security concern of X-aspnet-Version:4.0.30319.

I found this post here and it says:

That is not the actual .NET framework version. It is the version of
  the CLR

My questions are, can the above quote be considered as the valid reference to address the issue? If not, can the logic app be somehow upgraded to use aspnet version 4.5 or higher?

And if I can change the version, can this have impacts on my current logic app's behavior?

Note: The app was made entirely through logic app designer and not a
 single chunk of coding was implemented

答:
X-AspNet-Version:  specifies the version of ASP.NET being used. Note that this value returns the core framework version. Typical examples include 1.1.4322, 2.0.50727 and 4.0.30319.

ASP.NET web sites send the ASP.NET version information in the web server HTTP Response Header as X-AspNet-Version value automatically to the client. So, you could not change it in logic app.


问:
How to limit use to only one computer per installation?
I'm about to release my application which is built in C# VS2008 to my customer, and I want to prevent copy abuse post deployment, since it's easy to copy installation files to another machine and use the application. I want to limit usage to only one computer per installation.</p>

答: Just make a pre-screen to enter login\pwd

ContentLicense: CC BY-SA 2.5


问:
I have a few questions about asynchronous programming
I use the following code and it works, but I'm not sure if it is the best/recommanded way to do asynchronous programming.

For example, is the following code necessary or can I call UpdateUsername() without writing this code?

```<code> NewUsername();

 public async void NewUsername()
 {
   await UpdateUsername();
 }
</code>```

I use "await" twice in my code, is it necessary to use it twice?

Is it always necessary to use "await" before some code that is marked with async, like the "await" before "PlayFabClientAPI.UpdateUserTitleDisplayNameAsync"?

```<code> private async Task UpdateUsername()
 {
   var resultupdatee = await PlayFabClientAPI.UpdateUserTitleDisplayNameAsync(new UpdateUserTitleDisplayNameRequest()
   {
     DisplayName = "NewName"
   });

   if (resultupdatee.Error != null)
   {
     // Handle error if any
     Console.WriteLine(resultupdatee.Error.GenerateErrorReport());
   }
   else
   {
     Console.WriteLine("User display name updated");
   }
 }
</code>```

When gets the line "int Count = 10;" executed? Is it possible that this line gets excuted before "await PlayFabClientAPI.UpdateUserTitleDisplayNameAsync" finished?

I want that "int Count = 10;" is only then executed after the code UpdateUsername() is finished.

```<code>NewUsername();
int Count = 10;
</code>```

答:
Based on that NewUsername returns void, it does not support awaiting, so there is no need to make it an asynchronous method.

```<code>public void NewUsername()
{
    UpdateUsername();
}
</code>```

But you need to ensure that int Count = 10 executes after the asynchronous task is done, we cannot let NewUsername return void, otherwise there is nothing to await.

Based on your code I assume that there is no further operation after UpdateUsername, so there is no need for NewUsername to be a async method

```<code>public Task NewUsername()
{
    return UpdateUsername();
}
</code>```

But if there is, you need

```<code>public async Task NewUsername()
{
    await UpdateUsername();
    //Operations after UpdateUsername is done.
}
</code>```

As long as NewUsername returns Task, you can use await to ensure int Count = 10; executes after everything is done.

```<code>//Must be in an async function
await NewUsername();
int Count = 10;
</code>```

As you can see, if there is some operation in a function A that needs to execute after another asynchronous function B is done, then function A needs to be asynchronous. In other words, asynchronous function is transitive. An asynchronous callee makes the caller asynchronous, unless you don't need to ensure the sequence of execution or you block the thread to wait synchronously.

Conclusion, there are 3 ways to do after calling an asynchronous function:

Waiting asynchronously, which is to await it to add operations after the callee is done. This makes the caller asynchronous.

Waiting synchronously, which is to call Wait method on the returned Task value to block the current thread for the completion. This is not recommanded for it makes the asynchronous callings meaningless.

Waiving the returned Task value of the asynchronous callee or the callee returning void, which is not to go ahead executing without waiting for the completion of the callee.

Body:
I use the following code and it works, but I'm not sure if it is the best/recommanded way to do asynchronous programming.

For example, is the following code necessary or can I call UpdateUsername() without writing this code?

 NewUsername();

 public async void NewUsername()
 {
   await UpdateUsername();
 }

I use "await" twice in my code, is it necessary to use it twice?

Is it always necessary to use "await" before some code that is marked with async, like the "await" before "PlayFabClientAPI.UpdateUserTitleDisplayNameAsync"?

 private async Task UpdateUsername()
 {
   var resultupdatee = await PlayFabClientAPI.UpdateUserTitleDisplayNameAsync(new UpdateUserTitleDisplayNameRequest()
   {
     DisplayName = "NewName"
   });

   if (resultupdatee.Error != null)
   {
     // Handle error if any
     Console.WriteLine(resultupdatee.Error.GenerateErrorReport());
   }
   else
   {
     Console.WriteLine("User display name updated");
   }
 }

When gets the line "int Count = 10;" executed? Is it possible that this line gets excuted before "await PlayFabClientAPI.UpdateUserTitleDisplayNameAsync" finished?

I want that "int Count = 10;" is only then executed after the code UpdateUsername() is finished.

NewUsername();
int Count = 10;

Body:
Based on that NewUsername returns void, it does not support awaiting, so there is no need to make it an asynchronous method.

public void NewUsername()
{
    UpdateUsername();
}

But you need to ensure that int Count = 10 executes after the asynchronous task is done, we cannot let NewUsername return void, otherwise there is nothing to await.

Based on your code I assume that there is no further operation after UpdateUsername, so there is no need for NewUsername to be a async method

public Task NewUsername()
{
    return UpdateUsername();
}

But if there is, you need

public async Task NewUsername()
{
    await UpdateUsername();
    //Operations after UpdateUsername is done.
}

As long as NewUsername returns Task, you can use await to ensure int Count = 10; executes after everything is done.

//Must be in an async function
await NewUsername();
int Count = 10;

As you can see, if there is some operation in a function A that needs to execute after another asynchronous function B is done, then function A needs to be asynchronous. In other words, asynchronous function is transitive. An asynchronous callee makes the caller asynchronous, unless you don't need to ensure the sequence of execution or you block the thread to wait synchronously.

Conclusion, there are 3 ways to do after calling an asynchronous function:

Waiting asynchronously, which is to await it to add operations after the callee is done. This makes the caller asynchronous.

Waiting synchronously, which is to call Wait method on the returned Task value to block the current thread for the completion. This is not recommanded for it makes the asynchronous callings meaningless.

Waiving the returned Task value of the asynchronous callee or the callee returning void, which is not to go ahead executing without waiting for the completion of the callee.


问:
Keeping track of boolean data
I need to keep track of n samples. The information I am keeping track of is of boolean type, i.e. something is true or false. As soon as I am on sample n+1, i basically want to ignore the oldest sample and record information about the newest one.

So say I keep track of samples, I may have something like

OLDEST 0   0   1   1  0   NEWEST

If the next sample is 1, this will become

OLDEST 0   1   1   0  1   NEWEST

if the next one is 0, this will become...

OLDEST 1   1   0   1  0   NEWEST

So what is the best way to implement this in terms of simplicity and memory?

Some ideas I had:

Vector of bool (this would require shifting elements so seems expensive)
    Storing it as bits...and using bit shifting (memorywise --cheap? but is there a limit on the number of samples?)
    Linked lists? (might be an overkill for the task)

Thanks for the ideas and suggestions :)

答:
You want a set of bits. Maybe you can look into a std::bitset

http://www.sgi.com/tech/stl/bitset.html

Very straightfoward to use, optimal memory consumption and probably the best performance

The only limitation is that you need to know at compile-time the value of n. If you want to set it on runtime, have a look at boost http://www.boost.org/doc/libs/1_36_0/libs/dynamic_bitset/dynamic_bitset.html

Title: Keeping track of boolean data


问:
How to write code to help garbage collector
On interview I got a question - "How to help garbage collector when writing code?".

In my opinion GC works really good and we don't need to use anything more than basic good code practices, later added that closing resources in finally clause help GC for sure but generally got suprised with such question.

Is there a good reply? Do we need to do something incredible to help garbage collector?

答:
Garbage collector is very efficent and dexterous in its work but we can enchance its's ability to collect garbage by pointing the variables and objects to null, which are not being used any more and there are no more references to them.
During file handling use the close() and flush() methods.
And in thread handling destroy the thread when not in use.


问:
Unable to read file because of unfinished subprocess: Python
I'm using subprocess to run a script.R file from test.py. My test.py goes as:

```<code>import subprocess
import pandas as pd
subprocess.call(["/usr/bin/Rscript", "--vanilla", "script.R"])   #line 3
df=pd.read_csv("output.csv")                                     #line 4
</code>```

script.R goes as:

```<code>library(limma)
df <- read.csv("input.csv")
df<-normalizeCyclicLoess(df)
write.csv(df,"output.csv")
</code>```

When I run the above file (test.py), I get an error:

```<code>FileNotFoundError: [Errno 2] File b'output.csv' does not exist: b'output.csv'
</code>```

I understand that this error is because a output.csv file doesn't exist in my working directory. But, I assume that it would be created by script.R, which isn't happening probably because before the execution of line 3 finishes, python goes to line 4. We used help from here for this, and as mentioned, we are using call for this. What's going wrong then? Thanks...

EDIT: I noticed that if I don't import any libraries in my code (like limma above), everything works fine. I can write any lengthy code as I want, and it doesn't give me any error and proceeds to completion. But, as soon as I import any library, subprocess.call(....) gives me a non-zero result (zero means process completed). For a test, I changed my script.R to library(limma) (and nothing else) (tried for other libraries too- got the same results), and it gave me a non-zero result. Thus, I think, there's some problem with the import of libraries using subprocess. Please note that I'm able to run this R code directly, and nothing is wrong with my code/library. Please give me some hints on what might be going wrong here...

答:
Apologies, my initial answer was completely wrong.

Your subprocess call:

```<code>subprocess.call(["/usr/bin/Rscript", "--vanilla", "script.R"])
</code>```

will return a number - this is the exit code of the process. If it succeeds, without error, it should be zero. You could check this to make sure your R code ran correctly.

Have you tried running your R code directly? Does it produce the output.csv? And if so, does it produce it in the right place?

Body:
I'm using subprocess to run a script.R file from test.py. My test.py goes as:

import subprocess
import pandas as pd
subprocess.call(["/usr/bin/Rscript", "--vanilla", "script.R"])   #line 3
df=pd.read_csv("output.csv")                                     #line 4

script.R goes as:

library(limma)
df <- read.csv("input.csv")
df<-normalizeCyclicLoess(df)
write.csv(df,"output.csv")

When I run the above file (test.py), I get an error:

FileNotFoundError: [Errno 2] File b'output.csv' does not exist: b'output.csv'

I understand that this error is because a output.csv file doesn't exist in my working directory. But, I assume that it would be created by script.R, which isn't happening probably because before the execution of line 3 finishes, python goes to line 4. We used help from here for this, and as mentioned, we are using call for this. What's going wrong then? Thanks...

EDIT: I noticed that if I don't import any libraries in my code (like limma above), everything works fine. I can write any lengthy code as I want, and it doesn't give me any error and proceeds to completion. But, as soon as I import any library, subprocess.call(....) gives me a non-zero result (zero means process completed). For a test, I changed my script.R to library(limma) (and nothing else) (tried for other libraries too- got the same results), and it gave me a non-zero result. Thus, I think, there's some problem with the import of libraries using subprocess. Please note that I'm able to run this R code directly, and nothing is wrong with my code/library. Please give me some hints on what might be going wrong here...

Body:
Apologies, my initial answer was completely wrong.

Your subprocess call:

subprocess.call(["/usr/bin/Rscript", "--vanilla", "script.R"])

will return a number - this is the exit code of the process. If it succeeds, without error, it should be zero. You could check this to make sure your R code ran correctly.

Have you tried running your R code directly? Does it produce the output.csv? And if so, does it produce it in the right place?


问:
HTTP/1.1 client: How to decide good keep-alive timeout default?
I’m writing a HTTP/1.1 client that will be used against a variety of servers.

How can I decide a reasonable default keep-alive timeout value, as in, how long the client should keep an unused connection open before closing? Any value I think of seems extremely arbitrary.

答:
First note that that with HTTP keep alive both client and server can close an idle connection (i.e. no outstanding response, no unfinished request) at any time. This means especially that the client cannot make the server keep the connection open by enforcing some timeout, all what a client-side timeout does is limit how long the client will try to keep the connection open. The server might close the connection even before this client-side timeout is reached.

Based on this there is no generic good value for the timeout but there actually does not need to be one. The timeout is essentially used to limit resources, i.e. how much idle connections will be open at the same time. If your specific use case will never visit the same site again anyway then using HTTP keep-alive would just be a waste of resources. If instead you don't know your specific usage pattern you could just place a limit on the number of open connections, i.e. close the longest unused connection if the limit is reached and a new connection is needed. It might make sense to have some upper limit timeout of 10..15 minutes anyway since usually after this time firewalls and NAT routers in between will have abandoned the connection state so the idle connection will no longer work for new requests anyway.

But in any case you also need to be sure that you detect if the server closes a connection and then discard this connection from the list of reusable connections. And if you use HTTP keep-alive you also need to be aware that the server might close the connection in the very moment you are trying to send a new request on an existing connection, i.e. you need to retry this request then on a newly created connection.


问:
How can I let the list page remember some params?
I have a Vue project, but there is a issue to me,

In my router.js:

```<code>{
      path: '/home/aftersale_physicalserver_workpanel/:use_flag/:areapartition_homeshowtext',
      meta: { keepAlive: true },
      icon: 'compose',
      name: 'aftersale_physicalserver_workpanel',
      title: 'work panel',
      component: resolve => {
        require(['./views/main_home/home/components/general_admin_staff_panel/physicalserver/physicalserver_workpanel.vue'], resolve);
      }
    },
</code>```

there is the code:

```<code>...
<template>
  <lml-page
     ref="lml_page_ref"
     v-if=" origin_data && origin_data.count"
     :data_count="origin_data.count"
     :current.sync="cur_page"
     @change_page_for_parent="server_change_page">
  </lml-page>
</template>
...

<script>
  export default {
  props: {
    ...
    cur_page: 1,
  },
</script>
</code>```

you see the cur_page is the page number. I want the URL append the page number.
because when I enter a detail page, when I go back, there will go to page 1 by default.

My purpose

my purpose is let the list_page remember some params. such as the upper page_number, and some search params. but in Vue I don't know how.

When I from a searched params page enter a detail page, when I go back:

```<code><span class="go-left" @click="$router.go(-1)">
   <Icon type="chevron-left"></Icon>
   <span>Go back</span>
</span>
</code>```

there will get a list_page without the searched data.

答:
You would need to use either local storage or a central state, what I use is vuex like this:

```<code>onPageChange: function (pageNo) {
        this.$store.dispatch(this.$mts.some.SOMETHING, pageNo);
      },
</code>```

Then you can call your store wherever you need and get the page number.
Look for the vuex docs on how to setup state management.
Like this:

```<code>this.page = this.$store.getters.some.page
</code>```

Body:
I have a Vue project, but there is a issue to me,

In my router.js:

{
      path: '/home/aftersale_physicalserver_workpanel/:use_flag/:areapartition_homeshowtext',
      meta: { keepAlive: true },
      icon: 'compose',
      name: 'aftersale_physicalserver_workpanel',
      title: 'work panel',
      component: resolve => {
        require(['./views/main_home/home/components/general_admin_staff_panel/physicalserver/physicalserver_workpanel.vue'], resolve);
      }
    },

there is the code:

...
<template>
  <lml-page
     ref="lml_page_ref"
     v-if=" origin_data && origin_data.count"
     :data_count="origin_data.count"
     :current.sync="cur_page"
     @change_page_for_parent="server_change_page">
  </lml-page>
</template>
...

you see the cur_page is the page number. I want the URL append the page number.
because when I enter a detail page, when I go back, there will go to page 1 by default.

My purpose

my purpose is let the list_page remember some params. such as the upper page_number, and some search params. but in Vue I don't know how.

When I from a searched params page enter a detail page, when I go back:

   <Icon type="chevron-left"></Icon>
   Go back

there will get a list_page without the searched data.

Body:
You would need to use either local storage or a central state, what I use is vuex like this:

onPageChange: function (pageNo) {
        this.$store.dispatch(this.$mts.some.SOMETHING, pageNo);
      },

Then you can call your store wherever you need and get the page number.
Look for the vuex docs on how to setup state management.
Like this:

this.page = this.$store.getters.some.page


问:
formating of databricks notebook titles like header,point
How to make the notebook cmd title has format like in the picture ?

答:
You can use markdown for this:

```<code>%md
###The next command...

1. Select color...
2. Displays a table...
</code>```

See also the Databricks documentation.

Body:
You can use markdown for this:

%md
###The next command...

1. Select color...
2. Displays a table...

See also the Databricks documentation.


答:
It looks like your switch syntax is incorrect. You are not destructuring there, you're making a switch on a new array (which you're creating there in the conditional). Why not simply refactor your cases to be ifs?

Also, you're using a string method (split) on an array. I don't see any strings with ":"s in your code. If you're going to be using an array which you know will look like that ['##', '##', '##'], you could use ifs like this:

```<code>if (hour !== "00") return `${hour} h ${minute} min ${sec} sec`;
if (minute !== "00") return `${minute} min ${sec} sec`;
return `${sec} sec`;
</code>```

Title: JavaScript: How to display time using a switch statement?

Body:
It looks like your switch syntax is incorrect. You are not destructuring there, you're making a switch on a new array (which you're creating there in the conditional). Why not simply refactor your cases to be ifs?

Also, you're using a string method (split) on an array. I don't see any strings with ":"s in your code. If you're going to be using an array which you know will look like that ['##', '##', '##'], you could use ifs like this:

if (hour !== "00") return `${hour} h ${minute} min ${sec} sec`;
if (minute !== "00") return `${minute} min ${sec} sec`;
return `${sec} sec`;


问:
Getting 403 forbidden error when calling API from node.js code, whereas working fine from Postman
I have microservices deployed on AWS lambda and node.js code deployed on EC2 instance.

When I am trying to access the microservice API from postman it is giving the correct response.
But the same API if I call from node.js code, it fails with error code 403.

Error-

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>403 ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.

<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: TtGE8OD711qm0s6NPCNPl2ExUUJUa7l_J_-h5GDtPEWk4CFiWDkixg==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>
</code>```

The API is a simple GET API like

https://xxx.amazonaws.com/v1/session/verify_email_token?token=123456

I am not using CloudFront and I am using Https.

答:
Following solution worked for me -
Change the API Gateway endpoint from edge-optimized to regional.</p>

Body:
I have microservices deployed on AWS lambda and node.js code deployed on EC2 instance.

When I am trying to access the microservice API from postman it is giving the correct response.
But the same API if I call from node.js code, it fails with error code 403.

Error-

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>

403 ERROR

The request could not be satisfied.

Bad request.

Generated by cloudfront (CloudFront)
Request ID: TtGE8OD711qm0s6NPCNPl2ExUUJUa7l_J_-h5GDtPEWk4CFiWDkixg==

<ADDRESS>
</ADDRESS>

The API is a simple GET API like

https://xxx.amazonaws.com/v1/session/verify_email_token?token=123456

I am not using CloudFront and I am using Https.


问:
Save option form and pass JS variable
I have a form that has radiobuttons and listboxes. I am trying to call a php file on button press to save the selected options into a MySQL database. I would like to pass the selected options as well as the total_cost, which is a JS variable.

How can I pass the JS variable to the php file when the form submit button is pressed?

```<code><form action="saveConfig.php" class="hide-submit" method="post">

<div class="btn-configure step2button">
<span class="pcButtonText">
Save
</span>
</div>

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

</form>
<br>
Total: <input id="total" type="text">
</code>```

JS:

```<code>let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}
</code>```

I cannot figure out how to pass the variable total_cost. Any advice would be appreciated.

答:
Use this to save your changes, then in saveConfig.php recive your data with json_decode($_POST)    </p>

```<code><form action="#" class="hide-submit">
<div class="btn-configure step2button">
<span class="pcButtonText">
Save
</span>
</div>

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="save();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>
</form>
<br>
Total: <input id="total" type="text">

<script>
function save(){
    $.ajax({
        url : 'saveConfig.php',
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {
            alert('saved');
        },
        error: function (jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
}
</script>
</code>```

Title: Save option form and pass JS variable

Body:
I have a form that has radiobuttons and listboxes. I am trying to call a php file on button press to save the selected options into a MySQL database. I would like to pass the selected options as well as the total_cost, which is a JS variable.

How can I pass the JS variable to the php file when the form submit button is pressed?

<form action="saveConfig.php" class="hide-submit" method="post">

Save

    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    Item 1 [£1.00]

    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    Item 2 [£12.34]

    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    Item 3 [£9.99]

<select id="plist" name="partlist" onchange="updateTotal();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>

</form>

Total: <input id="total" type="text">

JS:

let buildcost = 25.00;

function updateTotal() {
  let radios = document.getElementsByName('config-prod');
  let select = document.getElementById('plist');
  let partcost = 0;

  for (let i = 0, j = radios.length; i < j; i++) {
    if (radios[i].checked) {
      partcost = parseFloat(radios[i].value);
      break;
    }
  }

  partcost += parseFloat(select.options[select.selectedIndex].value);

  let total_cost = buildcost + partcost;
  document.getElementById('total').value = total_cost.toFixed(2);
}

I cannot figure out how to pass the variable total_cost. Any advice would be appreciated.

Body:
Use this to save your changes, then in saveConfig.php recive your data with json_decode($_POST)

<form action="#" class="hide-submit">
<div class="btn-configure step2button">
<span class="pcButtonText">
Save
</span>
</div>

<ul id="radio" class="input-list">
  <li>
    <input id="item-1" name="config-prod" value="1.00" type="radio" onchange="updateTotal();">
    <label for="item-1">Item 1 [£1.00]</label>
  </li>
  <li>
    <input id="item-2" name="config-prod" value="12.34" type="radio" onchange="updateTotal();">
    <label for="item-2">Item 2 [£12.34]</label>
  </li>
  <li>
    <input id="item-3" name="config-prod" value="9.99" type="radio" onchange="updateTotal();">
    <label for="item-3">Item 3 [£9.99]</label>
  </li>
</ul>

<select id="plist" name="partlist" onchange="save();">
  <option value="99.99">CPU 1</option>
  <option value="123.00">CPU 2</option>
  <option value="250.54">CPU 3</option>
</select>
</form>
<br>
Total: <input id="total" type="text">

<script>
function save(){
    $.ajax({
        url : 'saveConfig.php',
        type: "POST",
        data: $('#form').serialize(),
        dataType: "JSON",
        success: function(data)
        {
            alert('saved');
        },
        error: function (jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }
    });
}
</script>


问:
Style preference in setters: Class::member = value or this->member = value?
This seems like a really simple question, but I've been unable to find any opinions on it. When writing setters in C++, what is the difference between

```<code>void ClassName::set_member( type value ) {
    ClassName::member = value;
}
</code>```

and

```<code>void ClassName::set_member( type value ) {
    this->member = value;
}
</code>```

CLion generates the first version, so I suspect it has some advantage, but I don't see what that would be.

答:
The difference is purely syntactic. Both versions have exactly the same effect. It doesn’t even matter whether member is static or non-static. Only from inside a static member function you cannot use the this-> version because there is no object and thus no this.

Because it feels really weird it bears repeating: Even if member is a static member variable this->member = value; is valid and does the right thing.

As for preferring one style over the other: like all stylistic choices that’s highly subjective. A clear answer isn’t really possible. But there are indictators of what the C++ community prefers in general. You might look at:

open source C++ code on GitHub etc., or your standard library implementation

code snippets on presentation slides from major conferences like CppCon, Meeting C++, C++ Now etc.

major C++ books, e.g. Stroustroup’s The C++ Programming Language or Scott Meyers’ Effective C++ series

Considering all that I’m confident to say that the prevalent style is none of your two, but:

```<code>member = value;
</code>```

On a purely personal note: For non-static members the ClassName:: version feels unfamiliar to an extent that I would call it out in a code review. this-> usually makes me wonder “Was this written by a Java programmer?”, but overall – especially if it’s used consistently – it’s an ok style, although unusual; and in some special template metaprogramming cicumstances it’s even mandatory.

Body:
This seems like a really simple question, but I've been unable to find any opinions on it. When writing setters in C++, what is the difference between

void ClassName::set_member( type value ) {
    ClassName::member = value;
}

and

void ClassName::set_member( type value ) {
    this->member = value;
}

CLion generates the first version, so I suspect it has some advantage, but I don't see what that would be.

Body:
The difference is purely syntactic. Both versions have exactly the same effect. It doesn’t even matter whether member is static or non-static. Only from inside a static member function you cannot use the this-> version because there is no object and thus no this.

Because it feels really weird it bears repeating: Even if member is a static member variable this->member = value; is valid and does the right thing.

As for preferring one style over the other: like all stylistic choices that’s highly subjective. A clear answer isn’t really possible. But there are indictators of what the C++ community prefers in general. You might look at:

open source C++ code on GitHub etc., or your standard library implementation

code snippets on presentation slides from major conferences like CppCon, Meeting C++, C++ Now etc.

major C++ books, e.g. Stroustroup’s The C++ Programming Language or Scott Meyers’ Effective C++ series

Considering all that I’m confident to say that the prevalent style is none of your two, but:

member = value;

On a purely personal note: For non-static members the ClassName:: version feels unfamiliar to an extent that I would call it out in a code review. this-> usually makes me wonder “Was this written by a Java programmer?”, but overall – especially if it’s used consistently – it’s an ok style, although unusual; and in some special template metaprogramming cicumstances it’s even mandatory.


问:
How to integrate nodeJS + Socket.IO and PHP?
I have recently been looking around, to find a good way to communicate between nodeJS and PHP. Here is the idea : nodeJS is still quite new, and it can be kind of tricky to develop a full application only with it. Moreover, you may need it only for one module of your project, like realtime notifications, chat, ... And you want to manage all the other stuff with PHP, because it is probably more easy for you (and you can take advantage of the existing frameworks, like CodeIgniter or Symfony).

I would like to have an easy solution ; I don't want to use cURL, or a third server to communicate between Apache and Node servers. What I want is to be able to catch events from node in simple Javascript, client-side.

I didn't find any answers that where complete, most of the time client-side was running by the node server and so not applicable in my case. So I crawled all the possible topics, and finally find my answer ; I'll try to share this, and to have a point where it's all clear.

Hope this can help some people ! ;)

答:
Try similar or you can check my blog for complete sample code on nodejs

On your page side:

Load Socket JS

https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js

Make object of the socket

var socket = io();

Use the emit function to send data to nodeserver.

socket.emit('new_notification', {

              message: 'message',

              title: 'title',

              icon: 'icon',

  });

So now your code will be look like

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>

var socket = io();

$(document).ready(function($) {
  $('.rules-table').on('click', '.runRule', function(event) {
    event.preventDefault();
    /* Act on the event */
    var ruleID = $(this).parents('tr').attr('id');

    // send notification before going to post
    socket.emit('new_notification', {
        message: 'Messge is ready to sent',
        title: title,
        icon: icon,
    });
    $.ajax({
      url: '/ajax/run-rule.php',
      type: 'POST',
      dataType: 'json',
      data: {
        ruleID: ruleID
      },
    })
    .done(function(data) {
      console.log(data);

      // send notification when post success
      socket.emit('new_notification', {
        message: 'Messge was sent',
        title: title,
        icon: icon,
      });

    })
    .fail(function() {
      console.log("error");

      // send notification when post failed
      socket.emit('new_notification', {
        message: 'Messge was failed',
        title: title,
        icon: icon,
      });
    })
    .always(function() {
      console.log("complete");
    });

  });
});
</code>```

Now on Node server side make handler for your request to get your request and send a message to all connected devices/browsers(server.js)

```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res) {
   res.sendfile('index.html');
});

io.on('connection', function (socket) {
  socket.on( 'new_notification', function( data ) {
    console.log(data.title,data.message);

    // Now Emit this message to all connected devices
    io.sockets.emit( 'show_notification', {
      title: data.title,
      message: data.message,
      icon: data.icon,
    });
  });
});

http.listen(3000, function() {
   console.log('listening on localhost:3000');
});
</code>```

Now the client/browser/client side make a receiver to receive socket message from node server

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>

var socket = io();

/**
 * Set Default Socket For Show Notification
 * @param {type} data
 * @returns {undefined}
 */
socket.on('show_notification', function (data) {
    showDesktopNotification(data.title, data.message, data.icon);
});
/**
 * Set Notification Request
 * @type type
 */
function setNotification() {
    showDesktopNotification('Lokesh', 'Desktop Notification..!', '/index.jpeg');
    sendNodeNotification('Lokesh', 'Browser Notification..!', '/index.jpeg');
}
/**
 * Check Browser Notification Permission
 * @type window.Notification|Window.Notification|window.webkitNotification|Window.webkitNotification|Window.mozNotification|window.mozNotification
 */
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
Notification.requestPermission(function (permission) {
});
/**
 * Request Browser Notification Permission
 * @type Arguments
 */
function requestNotificationPermissions() {
    if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
        });
    }
}
/**
 * Show Desktop Notification If Notification Allow
 * @param {type} title
 * @param {type} message
 * @param {type} icon
 * @returns {undefined}
 */
function showDesktopNotification(message, body, icon, sound, timeout) {
    if (!timeout) {
        timeout = 4000;
    }
    requestNotificationPermissions();
    var instance = new Notification(
            message, {
                body: body,
                icon: icon,
                sound: sound
            }
    );
    instance.onclick = function () {
        // Something to do
    };
    instance.onerror = function () {
        // Something to do
    };
    instance.onshow = function () {
        // Something to do
    };
    instance.onclose = function () {
        // Something to do
    };
    if (sound)
    {
        instance.sound;
    }
    setTimeout(instance.close.bind(instance), timeout);
    return false;
}
</code>```

Body:
Try similar or you can check my blog for complete sample code on nodejs

On your page side:

Load Socket JS

https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js

Make object of the socket

var socket = io();

Use the emit function to send data to nodeserver.

socket.emit('new_notification', {

              message: 'message',

              title: 'title',

              icon: 'icon',

  });

So now your code will be look like

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>

var socket = io();

$(document).ready(function($) {
  $('.rules-table').on('click', '.runRule', function(event) {
    event.preventDefault();
    /* Act on the event */
    var ruleID = $(this).parents('tr').attr('id');

    // send notification before going to post
    socket.emit('new_notification', {
        message: 'Messge is ready to sent',
        title: title,
        icon: icon,
    });
    $.ajax({
      url: '/ajax/run-rule.php',
      type: 'POST',
      dataType: 'json',
      data: {
        ruleID: ruleID
      },
    })
    .done(function(data) {
      console.log(data);

      // send notification when post success
      socket.emit('new_notification', {
        message: 'Messge was sent',
        title: title,
        icon: icon,
      });

    })
    .fail(function() {
      console.log("error");

      // send notification when post failed
      socket.emit('new_notification', {
        message: 'Messge was failed',
        title: title,
        icon: icon,
      });
    })
    .always(function() {
      console.log("complete");
    });

  });
});

Now on Node server side make handler for your request to get your request and send a message to all connected devices/browsers(server.js)

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res) {
   res.sendfile('index.html');
});

io.on('connection', function (socket) {
  socket.on( 'new_notification', function( data ) {
    console.log(data.title,data.message);

    // Now Emit this message to all connected devices
    io.sockets.emit( 'show_notification', {
      title: data.title,
      message: data.message,
      icon: data.icon,
    });
  });
});

http.listen(3000, function() {
   console.log('listening on localhost:3000');
});

Now the client/browser/client side make a receiver to receive socket message from node server

<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>

var socket = io();

/**
 * Set Default Socket For Show Notification
 * @param {type} data
 * @returns {undefined}
 */
socket.on('show_notification', function (data) {
    showDesktopNotification(data.title, data.message, data.icon);
});
/**
 * Set Notification Request
 * @type type
 */
function setNotification() {
    showDesktopNotification('Lokesh', 'Desktop Notification..!', '/index.jpeg');
    sendNodeNotification('Lokesh', 'Browser Notification..!', '/index.jpeg');
}
/**
 * Check Browser Notification Permission
 * @type window.Notification|Window.Notification|window.webkitNotification|Window.webkitNotification|Window.mozNotification|window.mozNotification
 */
var Notification = window.Notification || window.mozNotification || window.webkitNotification;
Notification.requestPermission(function (permission) {
});
/**
 * Request Browser Notification Permission
 * @type Arguments
 */
function requestNotificationPermissions() {
    if (Notification.permission !== 'denied') {
        Notification.requestPermission(function (permission) {
        });
    }
}
/**
 * Show Desktop Notification If Notification Allow
 * @param {type} title
 * @param {type} message
 * @param {type} icon
 * @returns {undefined}
 */
function showDesktopNotification(message, body, icon, sound, timeout) {
    if (!timeout) {
        timeout = 4000;
    }
    requestNotificationPermissions();
    var instance = new Notification(
            message, {
                body: body,
                icon: icon,
                sound: sound
            }
    );
    instance.onclick = function () {
        // Something to do
    };
    instance.onerror = function () {
        // Something to do
    };
    instance.onshow = function () {
        // Something to do
    };
    instance.onclose = function () {
        // Something to do
    };
    if (sound)
    {
        instance.sound;
    }
    setTimeout(instance.close.bind(instance), timeout);
    return false;
}


问:
if condition not working in jenkins pipeline job?
Here I am using an choice parameters plugin, i need to build the jobs as per the parameter values in choices
for Example:

```<code> CHOICE PARAMETER
 NAME: Project
 VALUE:   Job1
           Job2
</code>```

Here Each parameter value has 6 jobs builds need to run in parallel.

```<code>import jenkins.model.*
import hudson.model.*
node('') {
if (Project == 'Job1'){
    stages ('Parallel-A'){
        parallel(firstTask: {
            stage ('Parallel-test1'){
            build job: 'test1'
    }
}, secondTask: {
        stage ('Parallel-test2'){
        build job: 'test2'
    }
})
}
}
if (Project =='Job2'){
    stages ('Parallel-B'){
        parallel(firstTask: {
            stage ('Parallel-test3'){
            build job: 'test3'
    }
}, secondTask: {
    stage ('Parallel-test4'){
    build job: 'test4'
    }
})
}
}
}
</code>```

but its not working here, Thanks in advance.

答:
Try <code>$Project</code>
As it was set as parameter, "$" shall be added before the variable.  </p>

Body:
Here I am using an choice parameters plugin, i need to build the jobs as per the parameter values in choices
for Example:

 CHOICE PARAMETER
 NAME: Project
 VALUE:   Job1
           Job2

Here Each parameter value has 6 jobs builds need to run in parallel.

import jenkins.model.*
import hudson.model.*
node('') {
if (Project == 'Job1'){
    stages ('Parallel-A'){
        parallel(firstTask: {
            stage ('Parallel-test1'){
            build job: 'test1'
    }
}, secondTask: {
        stage ('Parallel-test2'){
        build job: 'test2'
    }
})
}
}
if (Project =='Job2'){
    stages ('Parallel-B'){
        parallel(firstTask: {
            stage ('Parallel-test3'){
            build job: 'test3'
    }
}, secondTask: {
    stage ('Parallel-test4'){
    build job: 'test4'
    }
})
}
}
}

but its not working here, Thanks in advance.

Body:
Try $Project
As it was set as parameter, "$" shall be added before the variable.


问:
React - Redux App: "Invalid attempt to spread non-iterable instance" Issue

At the beginning, that sample app was working properly. I could see
  data that I inputted over browser page and database. At now, I can see
  the data only via the database, the browser doesn't show data and getting this
  error additionally: "Invalid attempt to spread non-iterable
  instance".

There is the sample code :

projectActions.js

```<code>import {FETCH_BOOK, CREATE_BOOK, DELETE_BOOK} from '../actions/projectTypes';
import axios from 'axios';

const apiUrl = 'http://api/books';

export const createBookSuccess =  (data) => {
  return {
    type: CREATE_BOOK,
    payload: {
      _id: data._id,
      author: data.author,
      publication: data.publication,
      publisher: data.publisher
    }
  }
};

export const deleteBookSuccess = _id => {
  return {
    type: DELETE_BOOK,
    payload: {
      _id
    }
  }
};

export const fetchBook = (books) => {
  return {
    type: FETCH_BOOK,
    books
  }
};

export const createBook = ({ author, publication, publisher }) => {
  return (dispatch) => {
    return axios.post(`${apiUrl}`, {author, publication, publisher})
      .then(response => {
        dispatch(createBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const deleteBook = _id => {
  return (dispatch) => {
    return axios.delete(`${apiUrl}/${_id}`)
      .then(response => {
        dispatch(deleteBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const fetchAllBooks = () => {
  return (dispatch) => {
    return axios.get(apiUrl)
      .then(response => {
        dispatch(fetchBook(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};
</code>```

projectReducer.js

```<code>import {CREATE_BOOK, DELETE_BOOK, FETCH_BOOK} from '../actions/projectTypes';

const projectReducer = (state = [], action) => {
  switch (action.types) {
    case CREATE_BOOK:
      return [...state, action.payload];
    case DELETE_BOOK:
      let afterDelete = state.filter(book => {
        return book._id !== action.payload._id
      });
      return {
        ...state,
        state: afterDelete
      }
    case FETCH_BOOK:
      return action.books;
    default:
      return state;
  }
}

export default projectReducer;
</code>```

rootReducer.js

```<code>import books from './projectReducer';
import {combineReducers} from 'redux';

const rootReducer = combineReducers({
    books: books
});

export default rootReducer;
</code>```

BookListElement.js

```<code>import React from 'react';
import {connect} from 'react-redux';
import BookList from '../components/bookList';
import {deleteBook} from '../store/actions/projectActions';

const BookListElement= ({books, deleteBook}) => {
  if(!books.length) {
    return (
      <div>
        No Books
      </div>
    )
  }
  return (
    <div>
      {books.map(book => {
        return (
          <BookList book={book} deleteBook={deleteBook} key={book._id} />
        );
      })}
    </div>
  );
}

const mapStateToProps = state => {
  return {
    books: state.books
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deleteBook: _id => {
      dispatch(deleteBook(_id));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement);
</code>```

bookList.js

```<code>import React from 'react';

const styles = {
  borderBottom: '2px solid #eee',
  background: '#fafafa',
  margin: '.75rem auto',
  padding: '.6rem 1rem',
  maxWidth: '500px',
  borderRadius: '7px'
};

const BookList =  ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  return (
    <div style={styles} key={_id}>
      <h2>{author}</h2>
      <p>{publication}</p>
      <p>{publisher}</p>
      <button className="btn waves-effect waves-light" type="submit" name="action" onClick={() => {deleteBook(_id)}}>
        <i className="large material-icons">delete_forever</i>
      </button>
    </div>
  );
};

export default BookList;
</code>```

bookCreate.js

```<code>import React, {Component} from 'react';

class BookCreate extends Component {
  state= {
    author: '',
    publication: '',
    publisher: ''
  }

  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.createBook(this.state)
  }

  render() {
    return (
      <div className="container">
        <form onSubmit={this.handleSubmit} className="white" autoComplete="off">
          <h5 className="grey-text text-darken-3">Create New Book</h5>
          <div className="input-field">
            <label htmlFor="author">Author</label>
            <input type="text" id="author" onChange={this.handleChange}/>
          </div>

          <div className="input-field">
            <label htmlFor="publication">Publication</label>
            <input type="text" id="publication" onChange={this.handleChange}/>
          </div>

          <div className="input-field">
            <label htmlFor="publisher">Publisher</label>
            <input type="text" id="publisher" onChange={this.handleChange}/>
          </div>

          <div className="input-field">
            <button className="btn pink lighten-1 z-depth-0">Create</button>
          </div>
        </form>
      </div>
    )
  }
}

export default BookCreate;
</code>```

I checked the code a few times and read an older post about this issue
  but I didn't find any solution as a junior. That would be great if you
  say what did I miss.

EDIT: Added view.js file as bookList.js .

答:
This error happens when you trying to copy an undefined array in your reducer.
eg:

```<code>const newList = [...state.someList];
</code>```

In this case 'someList' is undefined or not an array. make sure your spelling or you are using an correct array.

Body:
At the beginning, that sample app was working properly. I could see
  data that I inputted over browser page and database. At now, I can see
  the data only via the database, the browser doesn't show data and getting this
  error additionally: "Invalid attempt to spread non-iterable
  instance".

There is the sample code :

projectActions.js

import {FETCH_BOOK, CREATE_BOOK, DELETE_BOOK} from '../actions/projectTypes';
import axios from 'axios';

const apiUrl = 'http://api/books';

export const createBookSuccess =  (data) => {
  return {
    type: CREATE_BOOK,
    payload: {
      _id: data._id,
      author: data.author,
      publication: data.publication,
      publisher: data.publisher
    }
  }
};

export const deleteBookSuccess = _id => {
  return {
    type: DELETE_BOOK,
    payload: {
      _id
    }
  }
};

export const fetchBook = (books) => {
  return {
    type: FETCH_BOOK,
    books
  }
};

export const createBook = ({ author, publication, publisher }) => {
  return (dispatch) => {
    return axios.post(`${apiUrl}`, {author, publication, publisher})
      .then(response => {
        dispatch(createBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const deleteBook = _id => {
  return (dispatch) => {
    return axios.delete(`${apiUrl}/${_id}`)
      .then(response => {
        dispatch(deleteBookSuccess(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

export const fetchAllBooks = () => {
  return (dispatch) => {
    return axios.get(apiUrl)
      .then(response => {
        dispatch(fetchBook(response.data))
      })
      .catch(error => {
        throw(error);
      });
  };
};

projectReducer.js

import {CREATE_BOOK, DELETE_BOOK, FETCH_BOOK} from '../actions/projectTypes';

const projectReducer = (state = [], action) => {
  switch (action.types) {
    case CREATE_BOOK:
      return [...state, action.payload];
    case DELETE_BOOK:
      let afterDelete = state.filter(book => {
        return book._id !== action.payload._id
      });
      return {
        ...state,
        state: afterDelete
      }
    case FETCH_BOOK:
      return action.books;
    default:
      return state;
  }
}

export default projectReducer;

rootReducer.js

import books from './projectReducer';
import {combineReducers} from 'redux';

const rootReducer = combineReducers({
    books: books
});

export default rootReducer;

BookListElement.js

import React from 'react';
import {connect} from 'react-redux';
import BookList from '../components/bookList';
import {deleteBook} from '../store/actions/projectActions';

const BookListElement= ({books, deleteBook}) => {
  if(!books.length) {
    return (

        No Books

    )
  }
  return (

      {books.map(book => {
        return (
          <BookList book={book} deleteBook={deleteBook} key={book._id} />
        );
      })}

  );
}

const mapStateToProps = state => {
  return {
    books: state.books
  };
};

const mapDispatchToProps = dispatch => {
  return {
    deleteBook: _id => {
      dispatch(deleteBook(_id));
    }
  };
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(BookListElement);

bookList.js

import React from 'react';

const styles = {
  borderBottom: '2px solid #eee',
  background: '#fafafa',
  margin: '.75rem auto',
  padding: '.6rem 1rem',
  maxWidth: '500px',
  borderRadius: '7px'
};

const BookList =  ({ book: { author, publication, publisher, _id }, deleteBook }) => {
  return (

{author}

{publication}

{publisher}

      <button className="btn waves-effect waves-light" type="submit" name="action" onClick={() => {deleteBook(_id)}}>
        delete_forever
      </button>

  );
};

export default BookList;

bookCreate.js

import React, {Component} from 'react';

class BookCreate extends Component {
  state= {
    author: '',
    publication: '',
    publisher: ''
  }

  handleChange = (e) => {
    this.setState({
      [e.target.id]: e.target.value
    });
  }

  handleSubmit = (e) => {
    e.preventDefault();
    this.props.createBook(this.state)
  }

  render() {
    return (

        <form onSubmit={this.handleSubmit} className="white" autoComplete="off">

Create New Book

            Author
            <input type="text" id="author" onChange={this.handleChange}/>

            Publication
            <input type="text" id="publication" onChange={this.handleChange}/>

            Publisher
            <input type="text" id="publisher" onChange={this.handleChange}/>

            <button className="btn pink lighten-1 z-depth-0">Create</button>

        </form>

    )
  }
}

export default BookCreate;

I checked the code a few times and read an older post about this issue
  but I didn't find any solution as a junior. That would be great if you
  say what did I miss.

EDIT: Added view.js file as bookList.js .

Body:
This error happens when you trying to copy an undefined array in your reducer.
eg:

const newList = [...state.someList];

In this case 'someList' is undefined or not an array. make sure your spelling or you are using an correct array.


问:
How to read complex objects from json file in .net core
I have a json like this to read in c# but it showing null.

Provices.json contains this json

```<code>{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}
</code>```

start up file contains

```<code> services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));
</code>```

This is c# models

```<code>   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }
</code>```

This is how I am reading this file which is giving me null values

```<code>public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}
</code>```

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

答:
You have both Published and DisplayOrder declared as bool but in the file, the values are:

```<code>"Published": false,
"DisplayOrder": 0,
</code>```

Also, when you read your values into data in the code below, you return a new empty list. You need to return data instead.

```<code>public List<State> GetStates()
    {
        var data = this._states.Value.States; // Zero count shows here
        return new List<State>();
    }
</code>```

Body:
I have a json like this to read in c# but it showing null.

Provices.json contains this json

{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}

start up file contains

 services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));

This is c# models

   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }

This is how I am reading this file which is giving me null values

public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

Body:
You have both Published and DisplayOrder declared as bool but in the file, the values are:

"Published": false,
"DisplayOrder": 0,

Also, when you read your values into data in the code below, you return a new empty list. You need to return data instead.

public List<State> GetStates()
    {
        var data = this._states.Value.States; // Zero count shows here
        return new List<State>();
    }


问:
Is there a way to set a specific amount of maximum spaces for TAB character (backslash t) "\t" in C++?
I want to print a square matrix that needs to be spaced each between the elements by 3 spaces. Then I found that char '\t' might be the easiest way. But, I think the number of spaces is somehow defined in certain algorithm. Could someone give me a guide through the algorithm or is there a way to set certain spaces in C++ for '\t'?

I know how to output manually by determining the number of space character. However '\t' seems simple to code rather than looping certain algorithm.

For a simple square matrix :

```<code>for (int x = 0, num = 1; x < 5; x++) {
        for (int y = 0; y < 5; y++, num++) {
            cout << num << "\t";
        }
        cout << endl;
    }
</code>```

The code outputs

```<code>1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25
</code>```

while I need

```<code>1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25
</code>```

Is there a way to set '\t'?

答:
But, I think the number of spaces is somehow defined in certain algorithm.

  ...

  Is there a way to set '\t'?

Not unless your connected terminal allows you to control that in a way.

The usual way to control output formatting using I/O manipulators, for your case

std::setw()

std::left (or may be better std::right for numbers)

Body:
I want to print a square matrix that needs to be spaced each between the elements by 3 spaces. Then I found that char '\t' might be the easiest way. But, I think the number of spaces is somehow defined in certain algorithm. Could someone give me a guide through the algorithm or is there a way to set certain spaces in C++ for '\t'?

I know how to output manually by determining the number of space character. However '\t' seems simple to code rather than looping certain algorithm.

For a simple square matrix :

for (int x = 0, num = 1; x < 5; x++) {
        for (int y = 0; y < 5; y++, num++) {
            cout << num << "\t";
        }
        cout << endl;
    }

The code outputs

1       2       3       4       5
6       7       8       9       10
11      12      13      14      15
16      17      18      19      20
21      22      23      24      25

while I need

1   2   3   4   5
6   7   8   9   10
11  12  13  14  15
16  17  18  19  20
21  22  23  24  25

Is there a way to set '\t'?


问:
Is it possible in Go to call a function with named arguments?
I want to call a function in Go, and attach to the argument values the argument names

func sum(a int, b int) int {
  return a + b
}

func main() {
  result := sum(a=4, b=5) // result == 9
}
```

Is it possible?

答:
At the moment Go does not have a way to use named argument in functions.
If you really need to use named arguments you can try this library go-named-params</p>

Body:
I want to call a function in Go, and attach to the argument values the argument names

func sum(a int, b int) int {
  return a + b
}

func main() {
  result := sum(a=4, b=5) // result == 9
}

Is it possible?