问:
How to write a For Loop with variables that include an incremental split [] to minify JS code?
Hopefully I am asking this question in the right way, I am a total noob to  For Loops in JavaScript...

I have to write a For Loop for this:

```<code>var file = '/home/xxxxx/xxxx/xxxx/xxxx';
var obj = result.rows;
var split = JSON.stringify(obj).split(',');
var date1rpl = split[0].replace(/\"/g,"");
var date1og = date1rpl.slice(2,100);
var date1 = splitabc(date1og);
var usr1 = split[1].replace(/\"/g,"");
var session1 = split[2].replace(/("|])/g,"");
var date2rpl = split[3].replace(/\"/g,"");
var date2og = date2rpl.slice(1,100);
var date2 = splitabc(date2og);
var session2 = split[5].replace(/("|])/g,"");
var usr2 = split[4].replace(/\"/g,"");
var date3rpl = split[6].replace(/\"/g,"");
var date3og = date3rpl.slice(1,100);
var date3 = splitabc(date3og);
var session3 = split[8].replace(/("|])/g,"");
var usr3 = split[7].replace(/\"/g,"");
var date4rpl = split[9].replace(/\"/g,"");
var date4og = date4rpl.slice(1,100);
var date4 = splitabc(date4og);
var session4 = split[11].replace(/("|])/g,"");
var usr4 = split[10].replace(/\"/g,"");
var date5rpl = split[12].replace(/\"/g,"");
var date5og = date5rpl.slice(1,100);
var date5 = splitabc(date5og);
var session5 = split[14].replace(/("|])/g,"");
var usr5 = split[13].replace(/\"/g,"");
jsonfile.writeFile(file, obj);
</code>```

The split[] seems to be incrementing by +3 for each user, session, date1rpl. How can I include this in a for loop that would run through the variables so that I can just have daterpl, dateog, date, usr, and session as variables and not have to number each variable and repeat it?

var date1rpl = split[0].replace(/\"/g,"");
              var date1og = date1rpl.slice(2,100);
              var date1 = splitabc(date1og);
              var usr1 = split[1].replace(/\"/g,"");
              var session1 = split[2].replace(/("|])/g,"");

答:
So you want to loop over ever item in the split array and do some work on it and then save the updated version for later use.

You can use a For Loop

```<code>var dates = [];
var split = JSON.stringify(obj).split(',');
for(var i = 0; i< split.length; i++){
   var dateRpl = split[i].replace(/\"/g,"");
   var dateOG = dateRpl.slice(2,100);
   dates.push(splitabc(dateOG));
}

// dates is now an array of all the processed dates
</code>```

Or you can use the forEach method on arrays

```<code>var dates = [];
var split = JSON.stringify(obj).split(',');
split.forEach(function(string) {
   var dateRpl = string.replace(/\"/g,"");
   var dateOG = dateRpl.slice(2,100);
   dates.push(splitabc(dateOG));
});

// dates is now an array of all the processed dates
</code>```

Body:
Hopefully I am asking this question in the right way, I am a total noob to  For Loops in JavaScript...

I have to write a For Loop for this:

var file = '/home/xxxxx/xxxx/xxxx/xxxx';
var obj = result.rows;
var split = JSON.stringify(obj).split(',');
var date1rpl = split[0].replace(/\"/g,"");
var date1og = date1rpl.slice(2,100);
var date1 = splitabc(date1og);
var usr1 = split[1].replace(/\"/g,"");
var session1 = split[2].replace(/("|])/g,"");
var date2rpl = split[3].replace(/\"/g,"");
var date2og = date2rpl.slice(1,100);
var date2 = splitabc(date2og);
var session2 = split[5].replace(/("|])/g,"");
var usr2 = split[4].replace(/\"/g,"");
var date3rpl = split[6].replace(/\"/g,"");
var date3og = date3rpl.slice(1,100);
var date3 = splitabc(date3og);
var session3 = split[8].replace(/("|])/g,"");
var usr3 = split[7].replace(/\"/g,"");
var date4rpl = split[9].replace(/\"/g,"");
var date4og = date4rpl.slice(1,100);
var date4 = splitabc(date4og);
var session4 = split[11].replace(/("|])/g,"");
var usr4 = split[10].replace(/\"/g,"");
var date5rpl = split[12].replace(/\"/g,"");
var date5og = date5rpl.slice(1,100);
var date5 = splitabc(date5og);
var session5 = split[14].replace(/("|])/g,"");
var usr5 = split[13].replace(/\"/g,"");
jsonfile.writeFile(file, obj);

The split[] seems to be incrementing by +3 for each user, session, date1rpl. How can I include this in a for loop that would run through the variables so that I can just have daterpl, dateog, date, usr, and session as variables and not have to number each variable and repeat it?

var date1rpl = split[0].replace(/\"/g,"");
              var date1og = date1rpl.slice(2,100);
              var date1 = splitabc(date1og);
              var usr1 = split[1].replace(/\"/g,"");
              var session1 = split[2].replace(/("|])/g,"");

Body:
So you want to loop over ever item in the split array and do some work on it and then save the updated version for later use.

You can use a For Loop

var dates = [];
var split = JSON.stringify(obj).split(',');
for(var i = 0; i< split.length; i++){
   var dateRpl = split[i].replace(/\"/g,"");
   var dateOG = dateRpl.slice(2,100);
   dates.push(splitabc(dateOG));
}

// dates is now an array of all the processed dates

Or you can use the forEach method on arrays

var dates = [];
var split = JSON.stringify(obj).split(',');
split.forEach(function(string) {
   var dateRpl = string.replace(/\"/g,"");
   var dateOG = dateRpl.slice(2,100);
   dates.push(splitabc(dateOG));
});

// dates is now an array of all the processed dates


来源: stackexchange

问:
Firebase User photoURL and displayName
I'm having a time trying to wrap my head around what I thought was a simple concept.

I have an app where I sign up a user, allow that user to set a 'photoURL' to their 'user' information in the Firebase Auth system. This works. When the user creates a post in my app, I want to display the title, image and
'photoURL' of the creator.

Currently, I save the post:

```<code>-Post {
 -id
 -title
 -image
 -photoURL <- from current logged in user }
</code>```

I also allow users to visit the posters page via routing /poster/'displayName'

So later, when a user updates their profile information like displayName or photoURL, do I need to go find all posts, comments, messages, replies and any other place that this user has a record and update the photoURL?

What I thought I would be able to do is say: (pseudo code)

```<code>get all posts =>
 foreach(post)
   post = {
          title: post.title.val()
          image: post.image.val()
          avatar: firebase.database().ref().child('users' + post.key)
          }
</code>```

Everything I read says I need to store that photoURL in my own 'Users' table. If I do that, then none of the posts get updated unless I write a server call to do that every time there is a change. Problem is, if I have 100K users, and 10% of them change their photoURL, I then have to change it in posts, comments, replies and messages per user. If the average user has 100 posts, 4000 comments, 6000 replies, we're looking at about 10K places * 10K users that have to be updated and if the average server call is 137ms, then my costs are around $175 (costs)

The other option is to pull information from two tables and create a new object every time. This would lead to about double the server calls and time thus doubling my costs.

Is this the best approach for this? I thought this would be a lot easier to just get the user photo and display name.

Sorry for the epic long post but I'm trying to learn. Thanks all!

答:
What you're describing is a typical issue when working with noSQL databases.  On the one hand, data duplication makes your app and its queries run faster.  On the other hand, if you want to change any that duplicated data, it can be problematic to find and replace all occurrences.

There's no "best" way to determine what to do.  It's completely up to your particular case.  It sounds like, if you have extreme amounts of data duplication that could be costly to update, it would be better to simply query the user record every time rather than to do the updates.  But again, it's ultimately up to you.

ContentLicense: CC BY-SA 3.0

Title: Firebase User photoURL and displayName

Body:
I'm having a time trying to wrap my head around what I thought was a simple concept.

I have an app where I sign up a user, allow that user to set a 'photoURL' to their 'user' information in the Firebase Auth system. This works. When the user creates a post in my app, I want to display the title, image and
'photoURL' of the creator.

Currently, I save the post:

-Post {
 -id
 -title
 -image
 -photoURL <- from current logged in user }

I also allow users to visit the posters page via routing /poster/'displayName'

So later, when a user updates their profile information like displayName or photoURL, do I need to go find all posts, comments, messages, replies and any other place that this user has a record and update the photoURL?

What I thought I would be able to do is say: (pseudo code)

get all posts =>
 foreach(post)
   post = {
          title: post.title.val()
          image: post.image.val()
          avatar: firebase.database().ref().child('users' + post.key)
          }

Everything I read says I need to store that photoURL in my own 'Users' table. If I do that, then none of the posts get updated unless I write a server call to do that every time there is a change. Problem is, if I have 100K users, and 10% of them change their photoURL, I then have to change it in posts, comments, replies and messages per user. If the average user has 100 posts, 4000 comments, 6000 replies, we're looking at about 10K places * 10K users that have to be updated and if the average server call is 137ms, then my costs are around $175 (costs)

The other option is to pull information from two tables and create a new object every time. This would lead to about double the server calls and time thus doubling my costs.

Is this the best approach for this? I thought this would be a lot easier to just get the user photo and display name.

Sorry for the epic long post but I'm trying to learn. Thanks all!


问:
Spring Web Service Test with MongoDB
I'm writing service tests for my Spring Boot Web application that acts as an interface to MongoDB. Ideally, my service test will test each component of my Spring application before finally hitting a Mocked MongoTemplate. The following code uses a MockMvc to hit my web endpoints.

```<code>@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@AutoConfigureDataMongo
public class MyControllerServiceTest {

  @Autowired
  private MockMvc mvc;

  @Autowired
  private MongoTemplate mongoTemplate

  @SpyBean
  private MyMongoRepository myMongoRepository;

  @Test
  public void createTest() {
    MyObject create = new MyObject()

    given(this.myMongoRepository.insert(create));

    this.mvc.perform(post("localhost:8080/myService")...)...;
  }
}
</code>```

MyController contains an @Autowired MyMongoRepository, which in turn implements MongoRepository and necessitates a mongoTemplate bean. This code executes properly only if a running MongoDB instance can be found (this example is more of an integration test between my service and MongoDB).

How can I mock out MongoTemplate while still using my MockMvc?

答:
I think a better approach to test would be to test your web layer(controller) and your service layer separately.

For testing your web layer you can use MockMvc and you can mock your service layer.

For testing your service layer which in turn talks to mongo, you can use a Fongo and nosqlunit.

Some examples here

https://arthurportas.wordpress.com/2017/01/21/sample-project-using-spring-boot-and-mongodbfongo-and-test-repository-with-nosqlunit/

https://github.com/JohnathanMarkSmith/spring-fongo-demo

Title: Spring Web Service Test with MongoDB

Body:
I'm writing service tests for my Spring Boot Web application that acts as an interface to MongoDB. Ideally, my service test will test each component of my Spring application before finally hitting a Mocked MongoTemplate. The following code uses a MockMvc to hit my web endpoints.

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@AutoConfigureDataMongo
public class MyControllerServiceTest {

  @Autowired
  private MockMvc mvc;

  @Autowired
  private MongoTemplate mongoTemplate

  @SpyBean
  private MyMongoRepository myMongoRepository;

  @Test
  public void createTest() {
    MyObject create = new MyObject()

    given(this.myMongoRepository.insert(create));

    this.mvc.perform(post("localhost:8080/myService")...)...;
  }
}

MyController contains an @Autowired MyMongoRepository, which in turn implements MongoRepository and necessitates a mongoTemplate bean. This code executes properly only if a running MongoDB instance can be found (this example is more of an integration test between my service and MongoDB).

How can I mock out MongoTemplate while still using my MockMvc?


问:
Write reliably to same file from different processes
I did create a small C++ Tracing solution which works very well. Within one process all is well but when I open the output file from diferent processes the data gets not correctly written. I did open the file with FILE_SHARE_WRITE to be able to write to the file when it is already open. Then I did create a named mutex to ensure proper synchronisation between processes. But it appears that this is not enough. According to the MSDN this does work within one process but not between different processes.
Next I tried to call FlushFileBuffers after every write while the mutex was still held but data was still distorted like this

The format is time process id/Thread id method enter/leave/severity namespace+method and then the message text.

```<code>10:29:42.994 7448/2236       }} Dll2.Test.fndll2 L1 -> Duration: 0.094s
10:29:43.040 7448/2236 {{       Dll2.DllMain L1
10:29:43.134 7448/2236 Info     Dll2.DllMain L1 Process detach
10:29:43.181 7448/2236       }} Dll2.DllMain L1 -> Duration: 0.141s
     }} Dll2.DllMain L1 -10:29:42.681 7448/2236 Info     Dll1.DllMain L1 Process attach
10:29:42.728 7448/2236       }} Dll1.DllMain L1 -10:29:42.744 2216/5510:29:42.775 7448/2236 {{       Dll1.Test.fndll1 10:210:29:42.822 7448/2236 Info     Dll1.Test.fndll1 10:29:42.837 2216/557610:29:42.853 7448/2236       }} Dll1.Test.fndll1 L110:29:42.884 2216/557610:29:43.306 7448/2236 {{       Dll1.DllMain L1
10:29:43.353 7448/2236 Info     Dll1.DllMain L1 Process detach
10:29:43.400 7448/2236       }} Dll1.DllMain L1 -> Duration: 0.094s
</code>```

I have looked at FILE_FLAG_NO_BUFFERING but it has severe limitations and it seems not easy to use.

Does anybody know the right way to write synchronized to the same file without distoriting the output?

Yours,

Alois Kraus

答: SQLite uses file locks to ensure this doesn't happen to its database file when accessing it from multiple processes. Have you tried using LockFile? (example).  I have, in the past, used an SQLite database for logging from multiple processes, but then that's probably a bit too much in this case.</p>

ContentLicense: CC BY-SA 2.5

Body:
I did create a small C++ Tracing solution which works very well. Within one process all is well but when I open the output file from diferent processes the data gets not correctly written. I did open the file with FILE_SHARE_WRITE to be able to write to the file when it is already open. Then I did create a named mutex to ensure proper synchronisation between processes. But it appears that this is not enough. According to the MSDN this does work within one process but not between different processes.
Next I tried to call FlushFileBuffers after every write while the mutex was still held but data was still distorted like this

The format is time process id/Thread id method enter/leave/severity namespace+method and then the message text.

10:29:42.994 7448/2236       }} Dll2.Test.fndll2 L1 -> Duration: 0.094s
10:29:43.040 7448/2236 {{       Dll2.DllMain L1
10:29:43.134 7448/2236 Info     Dll2.DllMain L1 Process detach
10:29:43.181 7448/2236       }} Dll2.DllMain L1 -> Duration: 0.141s
     }} Dll2.DllMain L1 -10:29:42.681 7448/2236 Info     Dll1.DllMain L1 Process attach
10:29:42.728 7448/2236       }} Dll1.DllMain L1 -10:29:42.744 2216/5510:29:42.775 7448/2236 {{       Dll1.Test.fndll1 10:210:29:42.822 7448/2236 Info     Dll1.Test.fndll1 10:29:42.837 2216/557610:29:42.853 7448/2236       }} Dll1.Test.fndll1 L110:29:42.884 2216/557610:29:43.306 7448/2236 {{       Dll1.DllMain L1
10:29:43.353 7448/2236 Info     Dll1.DllMain L1 Process detach
10:29:43.400 7448/2236       }} Dll1.DllMain L1 -> Duration: 0.094s

I have looked at FILE_FLAG_NO_BUFFERING but it has severe limitations and it seems not easy to use.

Does anybody know the right way to write synchronized to the same file without distoriting the output?

Yours,

Alois Kraus


问:
how to sum data array in javascript
i have data from json this data json

```<code>var someObject = {
 "exam":
 [
   {
     "re": [[{"result": "3"}],[{"result": "1"}],[{"result": "2"}]]
   },
   {
     "re": [[{"result": "4"}],[{"result": "4"}],[{"result": "4"}]]
   }
   ,
   {
     "re": [[{"result": "2"}],[{"result": "1"}],[{"result": "3"}]]
   }
 ]
};
</code>```

and the problem is how to sum the result?

and I've tried in code like this

```<code>for (var i = 0; i<someObject.exam.length; i++){
    for (var y = 0; y < someObject.exam[i].re.length; y++){

         $scope.RESS = parseInt(someObject.exam[i].re[y][0].result) +
                       parseInt(someObject.exam[i].re[y][0].result)
  }
}
</code>```

why the results not same like

```<code> 3 + 4 + 2; // 9
 1 + 4 + 1; // 6
 2 + 4 + 3; // 9
</code>```

this xample from plunk xamplle

I've spent 2 days for something like this, and now I'm tired help me pleasse

答:
This is how you should calculate it:

```<code>someObject.exam[0].re.forEach(function(o, i) {
  results.push(parseInt(someObject.exam[0].re[i][0].result) + parseInt(someObject.exam[1].re[i][0].result) + parseInt(someObject.exam[2].re[i][0].result));
});
</code>```

Demo:

var someObject = {
  "exam": [{
      "re": [
        [{
          "result": "3"
        }],
        [{
          "result": "1"
        }],
        [{
          "result": "2"
        }]
      ]
    },
    {
      "re": [
        [{
          "result": "4"
        }],
        [{
          "result": "4"
        }],
        [{
          "result": "4"
        }]
      ]
    },
    {
      "re": [
        [{
          "result": "2"
        }],
        [{
          "result": "1"
        }],
        [{
          "result": "3"
        }]
      ]
    }
  ]
};

var results = [];

someObject.exam[0].re.forEach(function(o, i) {
  results.push(parseInt(someObject.exam[0].re[i][0].result) + parseInt(someObject.exam[1].re[i][0].result) + parseInt(someObject.exam[2].re[i][0].result));
});
console.log(results);```

Title: how to sum data array in javascript

Body:
i have data from json this data json

var someObject = {
 "exam":
 [
   {
     "re": [[{"result": "3"}],[{"result": "1"}],[{"result": "2"}]]
   },
   {
     "re": [[{"result": "4"}],[{"result": "4"}],[{"result": "4"}]]
   }
   ,
   {
     "re": [[{"result": "2"}],[{"result": "1"}],[{"result": "3"}]]
   }
 ]
};

and the problem is how to sum the result?

and I've tried in code like this

for (var i = 0; i<someObject.exam.length; i++){
    for (var y = 0; y < someObject.exam[i].re.length; y++){

         $scope.RESS = parseInt(someObject.exam[i].re[y][0].result) +
                       parseInt(someObject.exam[i].re[y][0].result)
  }
}

why the results not same like

 3 + 4 + 2; // 9
 1 + 4 + 1; // 6
 2 + 4 + 3; // 9

this xample from plunk xamplle

I've spent 2 days for something like this, and now I'm tired help me pleasse

Body:
This is how you should calculate it:

someObject.exam[0].re.forEach(function(o, i) {
  results.push(parseInt(someObject.exam[0].re[i][0].result) + parseInt(someObject.exam[1].re[i][0].result) + parseInt(someObject.exam[2].re[i][0].result));
});

Demo:

var someObject = {
  "exam": [{
      "re": [
        [{
          "result": "3"
        }],
        [{
          "result": "1"
        }],
        [{
          "result": "2"
        }]
      ]
    },
    {
      "re": [
        [{
          "result": "4"
        }],
        [{
          "result": "4"
        }],
        [{
          "result": "4"
        }]
      ]
    },
    {
      "re": [
        [{
          "result": "2"
        }],
        [{
          "result": "1"
        }],
        [{
          "result": "3"
        }]
      ]
    }
  ]
};

var results = [];

someObject.exam[0].re.forEach(function(o, i) {
  results.push(parseInt(someObject.exam[0].re[i][0].result) + parseInt(someObject.exam[1].re[i][0].result) + parseInt(someObject.exam[2].re[i][0].result));
});
console.log(results);


问:
Unity Editor Can't Edit Multiple Objects
I want to build a custom inspector for one of my classes... and well... I thought I would start simple ... and I still can't get it to draw the basic inspector:

My editor script is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(AbilityBluePrint))]
[CanEditMultipleObjects]
public class AbilityBluePrintEditor : Editor
{

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        // Show default inspector property editor
        DrawDefaultInspector();
    }
}
```

<p>And the class I want to edit is:</p>

<pre class="lang-c# prettyprint-override"><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "New Ability BluePrint", menuName = "Ability BluePrint")]
public class AbilityBluePrint : ScriptableObject {
    public AbilityName abilityName;
    public Characteristic[] characteritics;
    public Effect[] effects;
    public float coolDown;
    public Sprite icon;
    public string description;
}
</code>```

Any suggestions, on how to solve the "multi-object editing not supported" message I get instead of my beautiful custom editor ??

答:
You need to use Serialized properties if like to use Multiple object edition.

[CustomEditor(typeof(AbilityBluePrint))]
[CanEditMultipleObjects]
public class AbilityBluePrintEditor : Editor
{
    var AbilityName : SerializedProperty;

    function OnEnable ()
    {
    // Setup the SerializedProperties
    AbilityName = serializedObject.FindProperty ("Ability");

    }

    function OnInspectorGUI()
    {
    // Update the serializedProperty - always do this in the beginning of OnInspectorGUI.
    serializedObject.Update ();
    ...
```

Body:
I want to build a custom inspector for one of my classes... and well... I thought I would start simple ... and I still can't get it to draw the basic inspector:

My editor script is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(AbilityBluePrint))]
[CanEditMultipleObjects]
public class AbilityBluePrintEditor : Editor
{

    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        // Show default inspector property editor
        DrawDefaultInspector();
    }
}

And the class I want to edit is:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[CreateAssetMenu(fileName = "New Ability BluePrint", menuName = "Ability BluePrint")]
public class AbilityBluePrint : ScriptableObject {
    public AbilityName abilityName;
    public Characteristic[] characteritics;
    public Effect[] effects;
    public float coolDown;
    public Sprite icon;
    public string description;
}

Any suggestions, on how to solve the "multi-object editing not supported" message I get instead of my beautiful custom editor ??


问:
Convert int 20171116101856 to yyyymmddhhmmss format to be used in datediff function
So I have this table that has date columns in int type.

```<code>last_run_date | last_run_time
   20171116   | 100234
</code>```

Im trying to convert this two values into a datetime to be used in datediff statement.

this is my statement

```<code>SELECT 1
FROM V_Jobs_All_Servers vjas
WHERE JobName='DailyReports_xxxx' and Step_Name='xxxx'
and DATEDIFF(hour, Convert(varchar,STUFF(STUFF(STUFF(STUFF(STUFF(cast(
Convert(varchar(100),vjas.last_run_date) +  Convert(varchar(100),vjas.last_run_time) as varchar)
,5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':')), Getdate()) <3
</code>```

This works but only when the last_run_time value is in two digits hour format
101216, but whenever its one digit hour 91316 it fails with the following error,

```<code>The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
</code>```

I am on SQL Server 2005

答:
If you're getting this value from msdb.dbo.sysjobsteps, there's a built-in function, msdb.dbo.agent_datetime(), to convert last_run_date and last_run_time to a datetime already:

```<code>select job_id,
    step_id,
    step_name,
    msdb.dbo.agent_datetime(nullif(last_run_date,0),nullif(last_run_time,0)) as last_run_datetime
from msdb.dbo.sysjobsteps
</code>```

It is an undocumented function.  However, at least in my version of SQL Server (2012), that function has this definition:

```<code>CREATE FUNCTION agent_datetime(@date int, @time int)
RETURNS DATETIME
AS
BEGIN
 RETURN
  (
    CONVERT(DATETIME,
          CONVERT(NVARCHAR(4),@date / 10000) + N'-' +
          CONVERT(NVARCHAR(2),(@date % 10000)/100)  + N'-' +
          CONVERT(NVARCHAR(2),@date % 100) + N' ' +
          CONVERT(NVARCHAR(2),@time / 10000) + N':' +
          CONVERT(NVARCHAR(2),(@time % 10000)/100) + N':' +
          CONVERT(NVARCHAR(2),@time % 100),
    120)
  )
END
</code>```

Body:
So I have this table that has date columns in int type.

last_run_date | last_run_time
   20171116   | 100234

Im trying to convert this two values into a datetime to be used in datediff statement.

this is my statement

SELECT 1
FROM V_Jobs_All_Servers vjas
WHERE JobName='DailyReports_xxxx' and Step_Name='xxxx'
and DATEDIFF(hour, Convert(varchar,STUFF(STUFF(STUFF(STUFF(STUFF(cast(
Convert(varchar(100),vjas.last_run_date) +  Convert(varchar(100),vjas.last_run_time) as varchar)
,5,0,'-'),8,0,'-'),11,0,' '),14,0,':'),17,0,':')), Getdate()) <3

This works but only when the last_run_time value is in two digits hour format
101216, but whenever its one digit hour 91316 it fails with the following error,

The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.

I am on SQL Server 2005

Body:
If you're getting this value from msdb.dbo.sysjobsteps, there's a built-in function, msdb.dbo.agent_datetime(), to convert last_run_date and last_run_time to a datetime already:

select job_id,
    step_id,
    step_name,
    msdb.dbo.agent_datetime(nullif(last_run_date,0),nullif(last_run_time,0)) as last_run_datetime
from msdb.dbo.sysjobsteps

It is an undocumented function.  However, at least in my version of SQL Server (2012), that function has this definition:

CREATE FUNCTION agent_datetime(@date int, @time int)
RETURNS DATETIME
AS
BEGIN
 RETURN
  (
    CONVERT(DATETIME,
          CONVERT(NVARCHAR(4),@date / 10000) + N'-' +
          CONVERT(NVARCHAR(2),(@date % 10000)/100)  + N'-' +
          CONVERT(NVARCHAR(2),@date % 100) + N' ' +
          CONVERT(NVARCHAR(2),@time / 10000) + N':' +
          CONVERT(NVARCHAR(2),(@time % 10000)/100) + N':' +
          CONVERT(NVARCHAR(2),@time % 100),
    120)
  )
END


问:
When resolving conflicts during a rebase, is there a native command for accepting both changes?
A merge conflict occurred during a rebase, and Git is now asking me to resolve the patch. In cases where both changes are acceptable, how do I tell Git to accept both changes without having to modify the file myself?

E.g. when both changes are acceptable:

```<code><<<<<<< HEAD
const foo = require('./foo');
=======
const bar = require('./bar');
>>>>>>> some commit message
</code>```

git: can I accept both changes in a merge conflict without editing files? suggests a way to do this for a very specific case without using Git, but I'm looking to do this with native Git commands. A comment mentions doing a union merge, but I couldn't find docs around how to do this in this scenario.

答:
To do a union merge, you must first extract all three inputs:

```<code>git show :1:$path > base
git show :2:$path > ours
git show :3:$path > theirs
</code>```

(these file names are purely for illustration—in practice you would need to generate a unique temporary file name for most of these file), then run git merge-file:

```<code>git merge-file --union ours base theirs
</code>```

The merged result is now in the file named ours; base and theirs may be discarded.

(Git probably should include a script that does the three extractions, runs git merge-file with any of the ours, theirs, or union options, and puts the result into the work-tree for inspection.  It doesn't, but I think it should.)

You must be very careful with union-merge, as it always thinks it succeeded, even if it made a mess of the result.

Body:
A merge conflict occurred during a rebase, and Git is now asking me to resolve the patch. In cases where both changes are acceptable, how do I tell Git to accept both changes without having to modify the file myself?

E.g. when both changes are acceptable:

<<<<<<>>>>>> some commit message

git: can I accept both changes in a merge conflict without editing files? suggests a way to do this for a very specific case without using Git, but I'm looking to do this with native Git commands. A comment mentions doing a union merge, but I couldn't find docs around how to do this in this scenario.

Body:
To do a union merge, you must first extract all three inputs:

git show :1:$path > base
git show :2:$path > ours
git show :3:$path > theirs

(these file names are purely for illustration—in practice you would need to generate a unique temporary file name for most of these file), then run git merge-file:

git merge-file --union ours base theirs

The merged result is now in the file named ours; base and theirs may be discarded.

(Git probably should include a script that does the three extractions, runs git merge-file with any of the ours, theirs, or union options, and puts the result into the work-tree for inspection.  It doesn't, but I think it should.)

You must be very careful with union-merge, as it always thinks it succeeded, even if it made a mess of the result.


问:
Meaning of "open_file:" in c?
I was going through some code demonstrating error handling in file operations.
I can't understand what does open_file: mean and what does the colon after "open_file" signify ?

```<code>#include  <stdio.h>

main()
{
   char  *filename;
    FILE  *fp1, *fp2;
    int   i, number;

    fp1 = fopen("TEST", "w");
    for(i = 10; i <= 100; i += 10)
       putw(i, fp1);

    fclose(fp1);

    printf("\nInput filename\n");

open_file:                           //What does this mean ?
    scanf("%s", filename);

    if((fp2 = fopen(filename,"r")) == NULL)
    {
       printf("Cannot open the file.\n");
       printf("Type filename again.\n\n");
       goto open_file;
    }
    elsefor(i = 1; i <= 20; i++)
    {  number = getw(fp2);
       if(feof(fp2))
       {
          printf("\nRan out of data.\n");
          break;
       }
       else
          printf("%d\n", number);
    }

    fclose(fp2);
}
</code>```

答: It's a label to which the goto a few lines later jumps..

Title: Meaning of "open_file:" in c?

Body:
I was going through some code demonstrating error handling in file operations.
I can't understand what does open_file: mean and what does the colon after "open_file" signify ?

#include  <stdio.h>

main()
{
   char  *filename;
    FILE  *fp1, *fp2;
    int   i, number;

    fp1 = fopen("TEST", "w");
    for(i = 10; i <= 100; i += 10)
       putw(i, fp1);

    fclose(fp1);

    printf("\nInput filename\n");

open_file:                           //What does this mean ?
    scanf("%s", filename);

    if((fp2 = fopen(filename,"r")) == NULL)
    {
       printf("Cannot open the file.\n");
       printf("Type filename again.\n\n");
       goto open_file;
    }
    elsefor(i = 1; i <= 20; i++)
    {  number = getw(fp2);
       if(feof(fp2))
       {
          printf("\nRan out of data.\n");
          break;
       }
       else
          printf("%d\n", number);
    }

    fclose(fp2);
}


问:
Is there AzMan 64bit?
Is there 64 bit version of AzMan?

We have an app that uses Microsoft.Interop.Security.AzRoles.dll.Is there a 64 version of this ?

答: I'm not sure about Windows 7 as I don't have a box to check but as far as Server 2008 R2 goes, the answer you're looking for is here: Where is microsoft.interop.security.azroles on Server 2008 R2?  (but to save you clicking, it's in the GAC in 32-bit and 64-bit forms).</p>

Title: Is there AzMan 64bit?


问:
Empty DataFrame doesn't admit its empty
I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty.

Here I've made a dataframe:

```<code>>>> df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
>>> df
     1    2    3
0  1.0  2.0  3.0
1  1.0  NaN  3.0
2  NaN  NaN  NaN
3  3.0  2.0  1.0
4  4.0  5.0  6.0
5  NaN  NaN  NaN
6  NaN  NaN  NaN
</code>```

Then I know row '2' is full of  nothing so I check for that...

```<code>>>> df[2:3].empty
    False
</code>```

Odd. So I split it out into its own dataframe:

```<code>>>> df1 = df[2:3]
>>> df1
    1   2   3
2 NaN NaN NaN

>>> df1.empty
False
</code>```

How do I check for emptiness (all the elements in a row being None or NaN?)

http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html

答:
I guess you have to use isnull() instead of empty().

```<code>import pandas
df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
df[2:3].isnull()
1   2   3
True    True    True
</code>```

Title: Empty DataFrame doesn't admit its empty

Body:
I must not understand something about emptiness when it comes to pandas DataFrames. I have a DF with empty rows but when I isolate one of these rows its not empty.

Here I've made a dataframe:

>>> df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
>>> df
     1    2    3
0  1.0  2.0  3.0
1  1.0  NaN  3.0
2  NaN  NaN  NaN
3  3.0  2.0  1.0
4  4.0  5.0  6.0
5  NaN  NaN  NaN
6  NaN  NaN  NaN

Then I know row '2' is full of  nothing so I check for that...

>>> df[2:3].empty
    False

Odd. So I split it out into its own dataframe:

>>> df1 = df[2:3]
>>> df1
    1   2   3
2 NaN NaN NaN

>>> df1.empty
False

How do I check for emptiness (all the elements in a row being None or NaN?)

http://pandas.pydata.org/pandas-docs/version/0.18/generated/pandas.DataFrame.empty.html

Body:
I guess you have to use isnull() instead of empty().

import pandas
df = pandas.DataFrame(columns=[1,2,3], data=[[1,2,3],[1,None,3],[None, None, None],[3,2,1],[4,5,6],[None,None,None],[None,None,None]])
df[2:3].isnull()
1   2   3
True    True    True

ContentLicense: CC BY-SA 4.0


问:
Getting 404 not found using path() in Django
I was just checking out django, and was trying a view to list the books by passing id as an argument to the URL books/urls.py. But getting 404 page not found error. I'm not getting whats wrong in the url when I typed this url in the browser:

```<code> http://192.168.0.106:8000/books/list/21/
</code>```

bookstore/urls.py

```<code>urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', include("books.urls"))
]
</code>```

settings.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books'
   ]
...
...
...
ROOT_URLCONF = 'bookstore.urls'
</code>```

books/urls.py

```<code>urlpatterns = [
     path('home/', create),
     path('list/(?P<id>\d+)', list_view),
]
</code>```

books/views.py

```<code>def create(request):
    form = CreateForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "Book Created")
        return redirect('/books/list', kwargs={"id":instance.id})
    return render(request, "home.html", {"form":form})

def list_view(request, id=None):
    books = Book.objects.filter(id=id)
    return render(request, "list.html", {"books": books})
</code>```

Project Structure:

```<code>├── books
│   ├── admin.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── urls.py
│   └── views.py
├── bookstore
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
</code>```

Here is the screenshot -

EDIT - As addressed in the comments - Tried by appending / in the url expression of thebooks.urls but no luck :(

答:
You are using the new path from Django 2.0 incorrectly. You shouldn't use a regex like \d+. Try changing it to:

```<code> path('list/<int:id>/', list_view, name='list_view'),
</code>```

The name is required if you want to reverse the URL.

If you want to stick with regexes, then use re_path (or url() still works if you want to be compatible with older versions of Django). See the URL dispatcher docs for more info.

Note the trailing slash as well - otherwise your path matches http://192.168.0.106:8000/books/list/21 but not http://192.168.0.106:8000/books/list/21/.

Body:
I was just checking out django, and was trying a view to list the books by passing id as an argument to the URL books/urls.py. But getting 404 page not found error. I'm not getting whats wrong in the url when I typed this url in the browser:

 http://192.168.0.106:8000/books/list/21/

bookstore/urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path('books/', include("books.urls"))
]

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'books'
   ]
...
...
...
ROOT_URLCONF = 'bookstore.urls'

books/urls.py

urlpatterns = [
     path('home/', create),
     path('list/(?P<id>\d+)', list_view),
]

books/views.py

def create(request):
    form = CreateForm(request.POST or None, request.FILES or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        messages.success(request, "Book Created")
        return redirect('/books/list', kwargs={"id":instance.id})
    return render(request, "home.html", {"form":form})

def list_view(request, id=None):
    books = Book.objects.filter(id=id)
    return render(request, "list.html", {"books": books})

Project Structure:

├── books
│   ├── admin.py
│   ├── forms.py
│   ├── __init__.py
│   ├── models.py
│   ├── urls.py
│   └── views.py
├── bookstore
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py

Here is the screenshot -

EDIT - As addressed in the comments - Tried by appending / in the url expression of thebooks.urls but no luck :(

Body:
You are using the new path from Django 2.0 incorrectly. You shouldn't use a regex like \d+. Try changing it to:

 path('list/<int:id>/', list_view, name='list_view'),

The name is required if you want to reverse the URL.

If you want to stick with regexes, then use re_path (or url() still works if you want to be compatible with older versions of Django). See the URL dispatcher docs for more info.

Note the trailing slash as well - otherwise your path matches http://192.168.0.106:8000/books/list/21 but not http://192.168.0.106:8000/books/list/21/.


问:
Need help to find previous year using windows Batch Script
Hi need some help in finding the previous year, using windows batch code

the code I am using is

```<code>:: This is Code for D3
@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^&
right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
SET "PREVYEAR=%result:~0,4%-%1%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
SET YEAR=%DATE:~-4%
set "filename=%mm%%dd%%yyyy%"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%YYYY%_%filename%.QVD"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%PREVYEAR%_%filename%.QVD"
pause
</code>```

this gives an output

```<code>"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017_11152017.QVD"
"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017-_11152017.QVD"
</code>```

I need some advice how can I find previous year, the output of variable PREVYEAR should be 2016

答:
You don't need Vbscript to do this at all. While it does help and even Powershell is a good idea you can do this all with WMIC and Batch.</p>

```<code>@echo off

REM Get Date and Time regardless of regional setttings
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"

REM Set year month and day into its own variables.
set "yyyy=%dt:~0,4%"
set "mm=%dt:~4,2%"
set "dd=%dt:~6,2%"

REM Subtract year
set /a "yyyy-=1"
</code>```

Body:
Hi need some help in finding the previous year, using windows batch code

the code I am using is

:: This is Code for D3
@echo off
set day=-1
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^&
right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
SET "PREVYEAR=%result:~0,4%-%1%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
SET YEAR=%DATE:~-4%
set "filename=%mm%%dd%%yyyy%"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%YYYY%_%filename%.QVD"
echo "E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*%PREVYEAR%_%filename%.QVD"
pause

this gives an output

"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017_11152017.QVD"
"E:\Data Loads Folder\SafetyAndSecurity\D3\QVD\*2017-_11152017.QVD"

I need some advice how can I find previous year, the output of variable PREVYEAR should be 2016

Body:
You don't need Vbscript to do this at all. While it does help and even Powershell is a good idea you can do this all with WMIC and Batch.

@echo off

REM Get Date and Time regardless of regional setttings
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"

REM Set year month and day into its own variables.
set "yyyy=%dt:~0,4%"
set "mm=%dt:~4,2%"
set "dd=%dt:~6,2%"

REM Subtract year
set /a "yyyy-=1"


问:
Capybara Selenium Chrome opens About Google Chrome
I have an issue with testing in Chrome. When I run the test it opens the chrome://settings/help page in a new tab. This causes my tests to fail as it can't find the buttons it should click on. I was debugging in Chrome in normal mode when I saw what happend.

Can I prevent this from happening? Or can I keep the tab where I'm testing in focussed in some way?

答: To add to Germain's comment, since I had a hard time remembering how to update the chromedriver -- I'm on a mac and originally installed it using brew, so now I had to do a 'brew upgrade chromedriver'.  Also probably a good idea to restart spring if you're using that for your tests.</p>


问:
Hyperledger Composer Error Identity has not been registered once issued
I have been following this Tutorial and I am able to complete it. I issue a new identity, to an existing participant and I create a business card for this identity with the following command:

composer identity issue --card admin@tutorial-network -f usr001@tutorial-network.card -u usr001 -a "resource:org.acme.biznet.Trader#usr001" -x true

Then, I import that business card via POST /wallet/import and I am able to call different REST API operations. After that, I stop the composer-rest-server and after a few minutes I start the composer-rest-server again with the command composer-rest-server -c admin@tutorial-network -m true -a true

Then, I authenticate to the REST API using the configured authentication mechanism (in this case passport-github strategy) and if I try to call one operation fro REST API it throws a A business network card has not been specified error message, then I import the previous business card via POST /wallet/import getting a no content which is supposed to be correct.

Finally, when I try to call another REST API operation I get the following error:

```<code>{
  "error": {
"statusCode": 500,
"name": "Error",
"message": "Error trying to ping. Error: Error trying to query business network. Error: chaincode error (status: 500, message: Error: The current identity has not been registered: usr001)",
"stack": "Error: Error trying to ping. Error: Error trying to query business network. Error: chaincode error (status: 500, message: Error: The current identity has not been registered: usr001)\n    at _checkRuntimeVersions.then.catch (/home/username/.npm-global/lib/node_modules/composer-rest-server/node_modules/composer-connector-hlfv1/lib/hlfconnection.js:679:34)\n    at <anonymous>"
  }
}
</code>```

This is the main issue, I don't know why my identity is not being recongized by the REST API if I used it previously to call some operations.

答:
the problem is one of persistence as captured here ->  https://hyperledger.github.io/composer/v0.16/integrating/enabling-multiuser.html and the link for persisting identities (ie instructions) is captured here -> https://hyperledger.github.io/composer/v0.16/integrating/deploying-the-rest-server.html

All user information is persisted in a LoopBack data source by using a LoopBack connector. By default, the REST server uses the LoopBack "memory" connector to persist user information, which is lost when the REST server is terminated. The REST server should be configured with a LoopBack connector that stores data in a highly available data source, for example a database.

Body:
I have been following this Tutorial and I am able to complete it. I issue a new identity, to an existing participant and I create a business card for this identity with the following command:

composer identity issue --card admin@tutorial-network -f usr001@tutorial-network.card -u usr001 -a "resource:org.acme.biznet.Trader#usr001" -x true

Then, I import that business card via POST /wallet/import and I am able to call different REST API operations. After that, I stop the composer-rest-server and after a few minutes I start the composer-rest-server again with the command composer-rest-server -c admin@tutorial-network -m true -a true

Then, I authenticate to the REST API using the configured authentication mechanism (in this case passport-github strategy) and if I try to call one operation fro REST API it throws a A business network card has not been specified error message, then I import the previous business card via POST /wallet/import getting a no content which is supposed to be correct.

Finally, when I try to call another REST API operation I get the following error:

{
  "error": {
"statusCode": 500,
"name": "Error",
"message": "Error trying to ping. Error: Error trying to query business network. Error: chaincode error (status: 500, message: Error: The current identity has not been registered: usr001)",
"stack": "Error: Error trying to ping. Error: Error trying to query business network. Error: chaincode error (status: 500, message: Error: The current identity has not been registered: usr001)\n    at _checkRuntimeVersions.then.catch (/home/username/.npm-global/lib/node_modules/composer-rest-server/node_modules/composer-connector-hlfv1/lib/hlfconnection.js:679:34)\n    at <anonymous>"
  }
}

This is the main issue, I don't know why my identity is not being recongized by the REST API if I used it previously to call some operations.


问:
Trigger executes first than function?
I have a problem. My current code doesn't get the data until a change occurs in the select element. That's why I'm trying to force the select when the tab is changed (because my .change function needs a parameter from selectorMRPC();. But my code somehow the $('#selectMRPC').trigger('change'); executes first than selectorMRPC(); and I get error of mrpc undefined even tho the .trigger is after the function selectorMRPC();

How can I force a update on the selector for the first item?? It needs to be triggered after I run the function selectorMRPC();

```<code>  function selectorMRPC() {
    $.ajax({
        type: 'post',
        url: 'IndividualSimulator',
        success: function (result) {
            $('#selectMRPC').empty();
            JSON.parse(result).forEach(function (mrpc) {
                var option = $('<option>', {
                    value: mrpc.name,
                    text: mrpc.name
                });

                //Persist data with option
                option.data('mrpc', mrpc);
                console.log(mrpc);

                $('#selectMRPC').append(option);
            });
        },
        error: function () {

        }
    });
    return false;
}

   //Execute MRPC
$('#runMRPC').click(function (e) {
    e.preventDefault();
    //Get data
    var data = $('#mrpcData').serialize();
    $.ajax({
        type: 'post',
        url: 'jdbcMRPC',
        data: data,
        success: function (result) {
            //Change to result tab
            showResult(result);
        },
        error: function (xhr) {
            showError(xhr.responseText);
        }
    });
});

$('#selectMRPC').change(function () {
    //fetch data
    var mrpc = $(this).find('option:selected').data('mrpc');

    $('#paramBody').empty();
    for (var i = 1; i <= 10; i++) {
        var field = mrpc["field" + i];

        if (field !== undefined) {
            var parsedField = field.split('_');
            var value = parsedField[0];
            var type = parsedField[1];

            switch (type) {
                case  "S":
                    type = "text";
                    if (value === '""')
                        value = null;
                    break;
                case "B":
                    type = "checkbox";
                    break;
                case "N":
                    type = "number";
                    value = parseInt(value);
                    break;
                case "D":
                    type = "number";
                    value = parseInt(value);
                    if (value === '""')
                        value = null;
                    break;
            }
            //else use checkbox
            if(type === "checkbox")
            {
                $('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><div class="checkbox checkbox-primary">' +
                    '<input class="text-center" id="field'+i+'" name="Fields" type="checkbox" value="' +value + '"><label for="field'+i+'"></label></div></tr>');
            }
            else
            {
                $('#paramBody').append('<tr><td>' + i + '</td><td>' + type + '</td><td><input class="text-center" name="Fields" type="' + type + '" value="' +value + '"></tr>');
            }
        }
    }
});

  $(".next-step").click(function (e) {

    var $active = $('.wizard .nav-tabs li.active');
    $active.next().removeClass('disabled');
    nextTab($active);

    //if it's the second tab, refresh it
    var liID = $('#menu').find('.active').attr('id');
    if(liID === "parametersTab") {
        $("#selectMRPC").val($("#selectMRPC option:first").val());
        selectorMRPC();
        $('#selectMRPC').trigger('change');
    }

});
</code>```

答:
you can return result of $.ajax from selectorMRPC and then in

```<code>selectorMRPC().then(function(){
    $('#selectMRPC').trigger('change');
});
</code>```

or use callback function if the trigger is still before select is populated

```<code>selectorMRPC(function(){
    $('#selectMRPC').trigger('change');
});
</code>```

Title: Trigger executes first than function?

Body:
I have a problem. My current code doesn't get the data until a change occurs in the select element. That's why I'm trying to force the select when the tab is changed (because my .change function needs a parameter from selectorMRPC();. But my code somehow the $('#selectMRPC').trigger('change'); executes first than selectorMRPC(); and I get error of mrpc undefined even tho the .trigger is after the function selectorMRPC();

How can I force a update on the selector for the first item?? It needs to be triggered after I run the function selectorMRPC();

  function selectorMRPC() {
    $.ajax({
        type: 'post',
        url: 'IndividualSimulator',
        success: function (result) {
            $('#selectMRPC').empty();
            JSON.parse(result).forEach(function (mrpc) {
                var option = $('<option>', {
                    value: mrpc.name,
                    text: mrpc.name
                });

                //Persist data with option
                option.data('mrpc', mrpc);
                console.log(mrpc);

                $('#selectMRPC').append(option);
            });
        },
        error: function () {

        }
    });
    return false;
}

   //Execute MRPC
$('#runMRPC').click(function (e) {
    e.preventDefault();
    //Get data
    var data = $('#mrpcData').serialize();
    $.ajax({
        type: 'post',
        url: 'jdbcMRPC',
        data: data,
        success: function (result) {
            //Change to result tab
            showResult(result);
        },
        error: function (xhr) {
            showError(xhr.responseText);
        }
    });
});

$('#selectMRPC').change(function () {
    //fetch data
    var mrpc = $(this).find('option:selected').data('mrpc');

    $('#paramBody').empty();
    for (var i = 1; i <= 10; i++) {
        var field = mrpc["field" + i];

        if (field !== undefined) {
            var parsedField = field.split('_');
            var value = parsedField[0];
            var type = parsedField[1];

            switch (type) {
                case  "S":
                    type = "text";
                    if (value === '""')
                        value = null;
                    break;
                case "B":
                    type = "checkbox";
                    break;
                case "N":
                    type = "number";
                    value = parseInt(value);
                    break;
                case "D":
                    type = "number";
                    value = parseInt(value);
                    if (value === '""')
                        value = null;
                    break;
            }
            //else use checkbox
            if(type === "checkbox")
            {
                $('#paramBody').append('
' + i + '	' + type + '
' +
                    '<input class="text-center" id="field'+i+'" name="Fields" type="checkbox" value="' +value + '">

');
            }
            else
            {
                $('#paramBody').append('
' + i + '	' + type + '	<input class="text-center" name="Fields" type="' + type + '" value="' +value + '">
');
            }
        }
    }
});

  $(".next-step").click(function (e) {

    var $active = $('.wizard .nav-tabs li.active');
    $active.next().removeClass('disabled');
    nextTab($active);

    //if it's the second tab, refresh it
    var liID = $('#menu').find('.active').attr('id');
    if(liID === "parametersTab") {
        $("#selectMRPC").val($("#selectMRPC option:first").val());
        selectorMRPC();
        $('#selectMRPC').trigger('change');
    }

});

Body:
you can return result of $.ajax from selectorMRPC and then in

selectorMRPC().then(function(){
    $('#selectMRPC').trigger('change');
});

or use callback function if the trigger is still before select is populated

selectorMRPC(function(){
    $('#selectMRPC').trigger('change');
});


问:
Young people using Emacs?
I am a college student that has fallen in love with Emacs. I have used IDEs in the past, and although features like Intellisense made the switch to Emacs very hard, I now think that Emacs is much more powerful, and features like Intellisense can be pretty closely matched by various modes depending on language (and I am not referring to M-/). I am happily writing Elisp code for everything that I need that isn't provided by modes or by Emacs itself and I love the way that it adapts and molds to my needs.

However, I do think that its main disadvantage is the fact that it has a pretty steep learning curve and that most new programmers will not even begin to learn it out of many common misconceptions.

So, I want to know the opinions of young people (or any person who didn't start using Emacs before there were IDEs) that are Emacs users. Just to get some reassurance that Emacs is not dead within our Eclipse-loving generation =). (Opinions of users of any other highly extensible editor like Jedit are also welcome)

答:
I code J2me in Windows, where my company doesn't impose me on certain IDE. And guess what, I return to my Old friend, Emacs...

I am 31 now, and I first learning emacs ca 23. But, the situation makes me change IDE alots : Netbeans, VS.NET, Eclipse, etc.

You know, Emacs still beat other, in some perspective :)

OwnerDisplayName: bigmonachus

Title: Young people using Emacs?

LastEditorDisplayName: Harleqin


问:
Combining python's multiprocessing module with a prime number function
I am using the python multiprocessing/pool module to compare program running times of a function that checks if a number is a prime. I can get the prime function to work by itself, but can't seem to merge the two so they work together. The pool function below:

```<code>import math import time
import multiprocessing from multiprocessing import Pool

def pool_process(f,data,pool_size):

    tp1 = time.time()
    pool = Pool(processes = pool_size)
    result = pool.map(f, data)
    pool.close()
    pool.join()
    #enter code here
    print("Results", result)
    print("Overall Time:", (time.time()-tp1))
</code>```

The function I am using to check if a number is a prime is the following:

```<code>def check_prime(num):

    t1 = time.time()
    res = False

    if num > 0:

        for i in range(2,num):
            if (num % i) == 0:
                print(num,"is not a prime number")
                print(i,"times",num//i,"is",num)
                print("Time:", (time.time()-t1))
                break
        else:
            print(num,"is a prime number")
            print("Time:", time.time()-t1)
            res = True

    return res
</code>```

Then I am calling the pool_process function

```<code>data = 15488801
pool_process(check_prime, data, 1)
</code>```

And I am getting the following error:

```<code>'int' object is not iterable
</code>```

答:
data in the third code snippet needs to be a list.

The variable data is fed into pool_process as second argument.

```<code>data = [15488801]
pool_process(check_prime, data, 1)
</code>```

In there it is given to Pool.map as argument to iterate over.

```<code>def pool_process(f,data,pool_size):
    # ...
    result = pool.map(f, data)
</code>```

After I put that integer into a list (and correcting the import statements) the code runs fine on my machine.

Body:
I am using the python multiprocessing/pool module to compare program running times of a function that checks if a number is a prime. I can get the prime function to work by itself, but can't seem to merge the two so they work together. The pool function below:

import math import time
import multiprocessing from multiprocessing import Pool

def pool_process(f,data,pool_size):

    tp1 = time.time()
    pool = Pool(processes = pool_size)
    result = pool.map(f, data)
    pool.close()
    pool.join()
    #enter code here
    print("Results", result)
    print("Overall Time:", (time.time()-tp1))

The function I am using to check if a number is a prime is the following:

def check_prime(num):

    t1 = time.time()
    res = False

    if num > 0:

        for i in range(2,num):
            if (num % i) == 0:
                print(num,"is not a prime number")
                print(i,"times",num//i,"is",num)
                print("Time:", (time.time()-t1))
                break
        else:
            print(num,"is a prime number")
            print("Time:", time.time()-t1)
            res = True

    return res

Then I am calling the pool_process function

data = 15488801
pool_process(check_prime, data, 1)

And I am getting the following error:

'int' object is not iterable

Body:
data in the third code snippet needs to be a list.

The variable data is fed into pool_process as second argument.

data = [15488801]
pool_process(check_prime, data, 1)

In there it is given to Pool.map as argument to iterate over.

def pool_process(f,data,pool_size):
    # ...
    result = pool.map(f, data)

After I put that integer into a list (and correcting the import statements) the code runs fine on my machine.


答:
I've tried Rajan Twanabashu solution, but it was almost the good one. Maybe it has changed since, I don't know.

Here's what I've done, after I found the groupWidth function in the BarDataChart file from Charts.

groupWidth function declaration

let groupSpace = 1 - n * (barWidth + barSpace)

Hope it could help

Title: How to make a grouped BarChart with ios-charts?

Body:
I am using ios-charts library.

I would like to group my inverter values so that each year is one group. Unfortunately, the number of monthly values per year may vary.

My data json looks like this:

{"monthlyData":[{"ERTRAG":"30.2989999055862","MONAT":"2","JAHR":"2016"},{"ERTRAG":"154.897000223398","MONAT":"1","JAHR":"2016"},{"ERTRAG":"141.996000155807","MONAT":"12","JAHR":"2015"},{"ERTRAG":"135.449000149965","MONAT":"11","JAHR":"2015"},{"ERTRAG":"319.437000751495","MONAT":"10","JAHR":"2015"},{"ERTRAG":"483.369997739792","MONAT":"9","JAHR":"2015"},{"ERTRAG":"698.112997770309","MONAT":"8","JAHR":"2015"},{"ERTRAG":"771.764000892639","MONAT":"7","JAHR":"2015"},{"ERTRAG":"736.611003398895","MONAT":"6","JAHR":"2015"},{"ERTRAG":"737.237999916077","MONAT":"5","JAHR":"2015"},{"ERTRAG":"720.181995391846","MONAT":"4","JAHR":"2015"},{"ERTRAG":"484.979001283646","MONAT":"3","JAHR":"2015"},{"ERTRAG":"249.974001646042","MONAT":"2","JAHR":"2015"},{"ERTRAG":"92.8830004036427","MONAT":"1","JAHR":"2015"},{"ERTRAG":"52.7970000207424","MONAT":"12","JAHR":"2014"},{"ERTRAG":"181.025999426842","MONAT":"11","JAHR":"2014"},{"ERTRAG":"332.789002537727","MONAT":"10","JAHR":"2014"},{"ERTRAG":"482.244999885559","MONAT":"9","JAHR":"2014"},{"ERTRAG":"602.811999320984","MONAT":"8","JAHR":"2014"},{"ERTRAG":"699.872003316879","MONAT":"7","JAHR":"2014"},{"ERTRAG":"828.212007522583","MONAT":"6","JAHR":"2014"},{"ERTRAG":"679.010004997253","MONAT":"5","JAHR":"2014"},{"ERTRAG":"635.115998744965","MONAT":"4","JAHR":"2014"},{"ERTRAG":"559.617002010345","MONAT":"3","JAHR":"2014"},{"ERTRAG":"265.135001063347","MONAT":"2","JAHR":"2014"},{"ERTRAG":"165.272998273373","MONAT":"1","JAHR":"2014"},{"ERTRAG":"134.578999936581","MONAT":"12","JAHR":"2013"},{"ERTRAG":"153.774000287056","MONAT":"11","JAHR":"2013"},{"ERTRAG":"321.733997344971","MONAT":"10","JAHR":"2013"},{"ERTRAG":"482.768000483513","MONAT":"9","JAHR":"2013"},{"ERTRAG":"692.864000797272","MONAT":"8","JAHR":"2013"},{"ERTRAG":"846.429007053375","MONAT":"7","JAHR":"2013"},{"ERTRAG":"709.758005619049","MONAT":"6","JAHR":"2013"},{"ERTRAG":"532.493996858597","MONAT":"5","JAHR":"2013"},{"ERTRAG":"462.539998054504","MONAT":"4","JAHR":"2013"},{"ERTRAG":"419.105004012585","MONAT":"3","JAHR":"2013"},{"ERTRAG":"143.189998820424","MONAT":"2","JAHR":"2013"},{"ERTRAG":"78.720000628382","MONAT":"1","JAHR":"2013"},{"ERTRAG":"90.1430006623268","MONAT":"12","JAHR":"2012"},{"ERTRAG":"155.483000457287","MONAT":"11","JAHR":"2012"},{"ERTRAG":"348.231998205185","MONAT":"10","JAHR":"2012"},{"ERTRAG":"598.037001848221","MONAT":"9","JAHR":"2012"},{"ERTRAG":"729.740003108978","MONAT":"8","JAHR":"2012"},{"ERTRAG":"676.923998832703","MONAT":"7","JAHR":"2012"},{"ERTRAG":"694.879002094269","MONAT":"6","JAHR":"2012"},{"ERTRAG":"811.281997680664","MONAT":"5","JAHR":"2012"},{"ERTRAG":"489.765002369881","MONAT":"4","JAHR":"2012"},{"ERTRAG":"538.866001605988","MONAT":"3","JAHR":"2012"},{"ERTRAG":"277.856996208429","MONAT":"2","JAHR":"2012"},{"ERTRAG":"155.854999214411","MONAT":"1","JAHR":"2012"},{"ERTRAG":"148.157999750227","MONAT":"12","JAHR":"2011"},{"ERTRAG":"230.409998774529","MONAT":"11","JAHR":"2011"}]}

I tried the following:

var months = Array<String>()
var years = Array<String>()
var dataEntries: [BarChartDataEntry] = []
var dataSets: [BarChartDataSet] = []
var overallSum = 0.0
var year = 2010 //monthlyValues[0].year
var count = 0
var chartDataSet: BarChartDataSet?

for i in 0..<monthlyValues.count {
  // if year is different, create new barchartdataset
  if monthlyValues[i].year != year {
    years.append("\(monthlyValues[i].year)")
    chartDataSet = BarChartDataSet(yVals: dataEntries, label: "\(year)")
    chartDataSet!.colors = [UIColor.whiteColor()]
    dataSets.append(chartDataSet!)
    year = monthlyValues[i].year
    dataEntries = []
    //months = []
    count = 0
  }
  months.append("\(monthlyValues[i].month)")
  overallSum += monthlyValues[i].amount

  let dataEntry = BarChartDataEntry(value: monthlyValues[i].amount, xIndex: count)
  count++
  dataEntries.append(dataEntry)
}
let chartData = BarChartData(xVals: months, dataSets: dataSets)
self.barChartView.data = chartData

This results in five series with the right year labels in the legend but there is no group separator in the chart and also the number of bars per year is either 4 or 5 (expected = 12).

Thanks for any hint on this!


问:
how to merge a collection of Maps using streams
I have a collection of maps:

```<code>Collection<Map<String,Double>> myCol = table.values();
</code>```

I would like to transform this into a Map

```<code>Map<String, Double>
</code>```

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

```<code>Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}
</code>```

and mergeMaps() is defined as

```<code>mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}
</code>```

However, I would like to use streams to get a map from collection. I have tried as follows:

```<code>Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;
</code>```

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?

答:
```<code> myCol.stream()
        .flatMap(x -> x.entrySet().stream())
        .collect(Collectors.groupingBy(
                Entry::getKey,
                TreeMap::new,
                Collectors.summingDouble(Entry::getValue)));
</code>```

Body:
I have a collection of maps:

Collection<Map<String,Double>> myCol = table.values();

I would like to transform this into a Map

Map<String, Double>

such that, for a matching key, values are summed up. Using a for loop, it is rather simple:

Map<String, Double> outMap = new HashMap<>();
for (Map<String, Double> map : myCol) {
    outMap =  mergeMaps(outMap, map);
}

and mergeMaps() is defined as

mergeMaps(Map<String, Double> m1, Map<String, Double> m2){
    Map<String, Double> outMap = new TreeMap<>(m1);
    m2.forEach((k,v) -> outMap.merge(k,v,Double::sum)); /*sum values if key exists*/
    return outMap;
}

However, I would like to use streams to get a map from collection. I have tried as follows:

Map<String, Double> outMap = new HashMap<>();
myCol.stream().forEach(e-> outMap.putAll(mergeMaps(outMap,e)));
return outMap;

This works without a problem. However, can I still improve it? I mean, how can I use collectors in it?


问:
XSL how to exclude some children in output?
Beginner XSL question..and I know there are similar questions and answers posted, but I can't figure out how to apply them to my XSLT...

My source XML looks like (this is just a fragment of a much larger XML file)

```<code><?xml version="1.0" encoding="UTF-8"?>
<COLLECTION><Release NAME="Release" TYPE="Unknown" STATUS="0">
<Transaction>
    <TransactionNumber>4</TransactionNumber>
    <ReleaseNumber>4</ReleaseNumber>
    <PrimaryObjectID>OR:wt.part.WTPart:121581:416986630-1502721046884-982634822-1-0-0-127@ODIGettingStarted.tri.co.uk</PrimaryObjectID>
    <CreatedBy>orgadmin</CreatedBy>
    <CreatedDate>2017-09-27 08:34:31 EDT</CreatedDate>
    <Locale>en_US</Locale>
    <Destination>CRP1</Destination>
</Transaction>
</Release>
</code>```

I want to exclude the Locale and Destination nodes from the output.
My complete solution will be more complex that requires me to split the XML into three, hence my use of  but the relevant code I have so far is :-

```<code><?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "2.0"
    xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

    <xsl:param name ="outputFileDir" select="'file:///D:/workspace/TPHMOT_xsl/TPHMOT_xsl/xsl_output'"/>

    <xsl:template match ="/">
        <xsl:result-document href="{$outputFileDir}/ESI_ItemMasters_1.xml" method="xml" indent="yes">
            <COLLECTION>
                <xsl:apply-templates select="COLLECTION/Release"/>
            </COLLECTION>
        </xsl:result-document>
        <xsl:result-document href="{$outputFileDir}/ESI_ConfigurableItem_1.xml" method="xml" indent="yes">
            <COLLECTION>
                <xsl:apply-templates select="COLLECTION/Release"/>
            </COLLECTION>
        </xsl:result-document>
        <xsl:result-document href="{$outputFileDir}/ESI_GenericBOM_1.xml" method="xml" indent="yes">
            <COLLECTION>
                <xsl:apply-templates select="COLLECTION/Release"/>
            </COLLECTION>
        </xsl:result-document>
    </xsl:template>

    <xsl:template match="Release">
        <xsl:copy-of select="self::node()"/>
    </xsl:template>

</xsl:stylesheet>
</code>```

This outputs

```<code><?xml version="1.0" encoding="UTF-8"?>
<COLLECTION>
   <Release NAME="Release" TYPE="Unknown" STATUS="0">
      <Transaction>
         <TransactionNumber>4</TransactionNumber>
         <ReleaseNumber>4</ReleaseNumber>
         <PrimaryObjectID>OR:wt.part.WTPart:121581:416986630-1502721046884-982634822-1-0-0-127@ODIGettingStarted.tri.co.uk</PrimaryObjectID>
         <CreatedBy>orgadmin</CreatedBy>
         <CreatedDate>2017-09-27 08:34:31 EDT</CreatedDate>
         <Locale>en_US</Locale>
         <Destination>CRP1</Destination>
      </Transaction>
   </Release>
</COLLECTION>
</code>```

How can I adapt my XSL to exclude Locale and Destination child nodes?

Many thanks in advance for any help offered!

答:
Instead of copying your complete element in

```<code><xsl:template match="Release">
    <xsl:copy-of select="self::node()"/>
</xsl:template>
</code>```

you only need to use the identity transformation

```<code><xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>
</code>```

and then empty template(s) to prevent the elements you don't want from being copied:

```<code><xsl:template match="Locale | Destination"/>
</code>```

Body:
Beginner XSL question..and I know there are similar questions and answers posted, but I can't figure out how to apply them to my XSLT...

My source XML looks like (this is just a fragment of a much larger XML file)

<?xml version="1.0" encoding="UTF-8"?>
<COLLECTION><Release NAME="Release" TYPE="Unknown" STATUS="0">
<Transaction>
    <TransactionNumber>4</TransactionNumber>
    <ReleaseNumber>4</ReleaseNumber>
    <PrimaryObjectID>OR:wt.part.WTPart:121581:416986630-1502721046884-982634822-1-0-0-127@ODIGettingStarted.tri.co.uk</PrimaryObjectID>
    <CreatedBy>orgadmin</CreatedBy>
    <CreatedDate>2017-09-27 08:34:31 EDT</CreatedDate>
    <Locale>en_US</Locale>
    <Destination>CRP1</Destination>
</Transaction>
</Release>

I want to exclude the Locale and Destination nodes from the output.
My complete solution will be more complex that requires me to split the XML into three, hence my use of  but the relevant code I have so far is :-

<?xml version = "1.0" encoding = "UTF-8"?>
<xsl:stylesheet version = "2.0"
    xmlns:xsl = "http://www.w3.org/1999/XSL/Transform">

    <xsl:param name ="outputFileDir" select="'file:///D:/workspace/TPHMOT_xsl/TPHMOT_xsl/xsl_output'"/>

    <xsl:template match ="/">
        <xsl:result-document href="{$outputFileDir}/ESI_ItemMasters_1.xml" method="xml" indent="yes">
            <COLLECTION>
                <xsl:apply-templates select="COLLECTION/Release"/>
            </COLLECTION>
        </xsl:result-document>
        <xsl:result-document href="{$outputFileDir}/ESI_ConfigurableItem_1.xml" method="xml" indent="yes">
            <COLLECTION>
                <xsl:apply-templates select="COLLECTION/Release"/>
            </COLLECTION>
        </xsl:result-document>
        <xsl:result-document href="{$outputFileDir}/ESI_GenericBOM_1.xml" method="xml" indent="yes">
            <COLLECTION>
                <xsl:apply-templates select="COLLECTION/Release"/>
            </COLLECTION>
        </xsl:result-document>
    </xsl:template>

    <xsl:template match="Release">
        <xsl:copy-of select="self::node()"/>
    </xsl:template>

</xsl:stylesheet>

This outputs

<?xml version="1.0" encoding="UTF-8"?>
<COLLECTION>
   <Release NAME="Release" TYPE="Unknown" STATUS="0">
      <Transaction>
         <TransactionNumber>4</TransactionNumber>
         <ReleaseNumber>4</ReleaseNumber>
         <PrimaryObjectID>OR:wt.part.WTPart:121581:416986630-1502721046884-982634822-1-0-0-127@ODIGettingStarted.tri.co.uk</PrimaryObjectID>
         <CreatedBy>orgadmin</CreatedBy>
         <CreatedDate>2017-09-27 08:34:31 EDT</CreatedDate>
         <Locale>en_US</Locale>
         <Destination>CRP1</Destination>
      </Transaction>
   </Release>
</COLLECTION>

How can I adapt my XSL to exclude Locale and Destination child nodes?

Many thanks in advance for any help offered!

Body:
Instead of copying your complete element in

<xsl:template match="Release">
    <xsl:copy-of select="self::node()"/>
</xsl:template>

you only need to use the identity transformation

<xsl:template match="@* | node()">
  <xsl:copy>
    <xsl:apply-templates select="@* | node()"/>
  </xsl:copy>
</xsl:template>

and then empty template(s) to prevent the elements you don't want from being copied:

<xsl:template match="Locale | Destination"/>


问:
Cannot assign to property: 'actions' is a get-only property
I am making my first app and here is my biggest problem. I would like to make a notification in which i can add actions to it based of user input. I have made a category with no actions at first and then with a for loop I try to create actions and at the same time add it to the category but here is the problem where it shows:
Cannot assign to property: 'actions' is a get-only property

Here is my code:

```<code>var category5 = UNNotificationCategory(identifier: "category.5", actions: [], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "placeholdertext", options: [])

    for index in 0..<workingDays[3].subjects!.count {
         let action = UNNotificationAction(identifier: "\(workingDays[3].subjects![index + 1].subjectName).5", title: workingDays[3].subjects![index + 1].subjectName, options: .foreground)

                category5.actions += [action]  // here I get the error
                // category5.actions.append(action) // I tried this as well but I get the same error
            }
</code>```

How can i fix my problem and is there another way of doing this? I would like the actions array to be mutable so I can also later remove some actions from it.

Any help would be much much appreciated and It for me that would mean dream come true !

答:
As the error shows, the UNNotificationCategory.actions array is read only and can be modified through the  UNNotificationCategory constructor method, so try this way must work for you

```<code>var actionsToAdd : [UNNotificationAction] = []
    for index in 0..<workingDays[3].subjects!.count {
         let action = UNNotificationAction(identifier: "\(workingDays[3].subjects![index + 1].subjectName).5", title: workingDays[3].subjects![index + 1].subjectName, options: .foreground)

                actionsToAdd.append(action)
            }

var category5 = UNNotificationCategory(identifier: "category.5", actions: actionsToAdd, intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "placeholdertext", options: [])
</code>```

Body:
I am making my first app and here is my biggest problem. I would like to make a notification in which i can add actions to it based of user input. I have made a category with no actions at first and then with a for loop I try to create actions and at the same time add it to the category but here is the problem where it shows:
Cannot assign to property: 'actions' is a get-only property

Here is my code:

var category5 = UNNotificationCategory(identifier: "category.5", actions: [], intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "placeholdertext", options: [])

    for index in 0..<workingDays[3].subjects!.count {
         let action = UNNotificationAction(identifier: "\(workingDays[3].subjects![index + 1].subjectName).5", title: workingDays[3].subjects![index + 1].subjectName, options: .foreground)

                category5.actions += [action]  // here I get the error
                // category5.actions.append(action) // I tried this as well but I get the same error
            }

How can i fix my problem and is there another way of doing this? I would like the actions array to be mutable so I can also later remove some actions from it.

Any help would be much much appreciated and It for me that would mean dream come true !

Body:
As the error shows, the UNNotificationCategory.actions array is read only and can be modified through the  UNNotificationCategory constructor method, so try this way must work for you

var actionsToAdd : [UNNotificationAction] = []
    for index in 0..<workingDays[3].subjects!.count {
         let action = UNNotificationAction(identifier: "\(workingDays[3].subjects![index + 1].subjectName).5", title: workingDays[3].subjects![index + 1].subjectName, options: .foreground)

                actionsToAdd.append(action)
            }

var category5 = UNNotificationCategory(identifier: "category.5", actions: actionsToAdd, intentIdentifiers: [], hiddenPreviewsBodyPlaceholder: "placeholdertext", options: [])


问:
Font size too large while retrieving the screen from history
When I retrieve the screen from history, I get the font size of the text as so large,
I use VFM within screen and i use custom component within it, which uses Graphics class to draw text.

When i press back button, it switches to history page, which shows up, with bigFont as well as some images from the previous page also shows up.

Where could be the problem?

答:
you mean to say that when you press back button of blackberry device then the screen that was present below the current screen in the stack appears some what distorted.

Usually it(below screen) appears the same as it was before any other screen was pushed over it.

Did u tried calling invalidate method in the onExposed method of the distorted screen.

May be it helps!!!!


问:
Python 2.7: check if default argument passed with a decorator
I am looking for something i'm not sure how to accompish and can't find an answer.

Lets say I have a function with unknown number of arguments except arg2. Also arg2 doesn't have a fixed argument location:

```<code>def some_func(arg1, arg2=None, maybe_arg3=None, maybe_not_arg4=None):
    # Do some stuff
</code>```

Now I want to check if arg2 has been passed by the user and replace it from a decorator, eg:

```<code>def some_dec(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # Do some stuff
        # check if arg2 is passed and replace
        rv = func(*args, **kwargs)
        return rv
    return wrapper
</code>```

If it's passed as key/value then it's no problem to get it from kwargs BUT how do I get it if it's passed to args? (Since IDK the number of arguments the function requires)

答:
You can first check the kwargs dict for the argument, if it's missing, it's likely going to be the second argument in args; check if args contains more than two arguments and :

```<code>def some_dec(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'args2' in kwargs:
             kwargs['args2'] = 'new value' # update value
        elif len(args) > 1:
             args = (args[0], 'new value') + args[2:] # rebuild args with new value
        rv = func(*args, **kwargs)
        return rv
    return wrapper
</code>```

Body:
I am looking for something i'm not sure how to accompish and can't find an answer.

Lets say I have a function with unknown number of arguments except arg2. Also arg2 doesn't have a fixed argument location:

def some_func(arg1, arg2=None, maybe_arg3=None, maybe_not_arg4=None):
    # Do some stuff

Now I want to check if arg2 has been passed by the user and replace it from a decorator, eg:

def some_dec(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # Do some stuff
        # check if arg2 is passed and replace
        rv = func(*args, **kwargs)
        return rv
    return wrapper

If it's passed as key/value then it's no problem to get it from kwargs BUT how do I get it if it's passed to args? (Since IDK the number of arguments the function requires)

Body:
You can first check the kwargs dict for the argument, if it's missing, it's likely going to be the second argument in args; check if args contains more than two arguments and :

def some_dec(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if 'args2' in kwargs:
             kwargs['args2'] = 'new value' # update value
        elif len(args) > 1:
             args = (args[0], 'new value') + args[2:] # rebuild args with new value
        rv = func(*args, **kwargs)
        return rv
    return wrapper


问:
How to validate a HTML input for a phone number
Brief

Validate a UK Mobile Phone Number field in a HTML Form to take into account the following rules:

Phone Number must begin 07

Phone Number must not exceed 11 Digits

Spaces are allowed (ignored). I've found that Auto-Fill features sometimes save numbers like 0123456789 or 01234 456 789. I'd rather not cause the inconvenience to the user to reformat their auto-fill input.

Valid Input Examples

07234567890

07234 567 895

07 23 45 78 90

Where I am

So far, I've only been able to validate my second point using:

<input id="phonenum" type="tel" pattern="^\d{11}$" required >

答:
```<code>function validatePhoneNumber(){
    var e = document.getElementById('phonenum');
    var phoneNo;
    var firstLetter;
    var secondLetter;
    if(!e){
        return false;
    }

    phoneNo = e.value.replace(/ /g, ''); // remove spaces
    if(phoneNo.length != 11 ){
        return false;
    }

    firstLetter = phoneNo[0];
    secondLetter = phoneNo[1];
    if(firstLetter != "0" || secondLetter != "7"){
        return false;
    }

    return true;
}
</code>```


问:
How to enable create / insert in a AxGridView in Enterprise Portal (Dynamics AX 2009)
There must be a way to enable creation and insertion of a record from a AxGridView without using the Tunnel and Wizard approach. From what I have found on the Internet so far, the only example is using a Wizard, and I honestly don't find that to be a user friendly approach.

Has anyone tried to enable insertion of records directly from a AxGridView?

答:
Yes it is possible to enter data through AxGridView. Just enable Editing, deleting for that control. And one more thing to make new row - you have to make addditional button - create new line, and code behind:</p>

```<code>protected void NewLine_Click(object sender, EventArgs e)
{
    int editIdx = AxGridView1.EditIndex;

    try
    {
        // Save the last unsaved line if any
        if (AxGridView1.EditIndex != -1 && AxGridView1.Rows.Count > 0)
        {
            this.AxGridView1.UpdateRow(AxGridView1.EditIndex, true);
        }

        DataSetViewRow dsvr = this.dsv.AddNew();
    }
    catch (System.Exception ex)
    {
        AxExceptionCategory exceptionCategory;

        if (!AxControlExceptionHandler.TryHandleException(this, ex, out exceptionCategory))
        {
            // Throw the fatal exception
            throw;
        }
        if (exceptionCategory == AxExceptionCategory.NonFatal)
        {
            AxGridView1.EditIndex = editIdx;
        }
    }
}

private DataSetView dsv //get dataset view
    {
        get
        {
            DataSet dataSet = this.AxDataSource1.GetDataSet();
            return dataSet.DataSetViews[this.AxGridView1.DataMember];
        }
    }
</code>```

Body:
Yes it is possible to enter data through AxGridView. Just enable Editing, deleting for that control. And one more thing to make new row - you have to make addditional button - create new line, and code behind:

protected void NewLine_Click(object sender, EventArgs e)
{
    int editIdx = AxGridView1.EditIndex;

    try
    {
        // Save the last unsaved line if any
        if (AxGridView1.EditIndex != -1 && AxGridView1.Rows.Count > 0)
        {
            this.AxGridView1.UpdateRow(AxGridView1.EditIndex, true);
        }

        DataSetViewRow dsvr = this.dsv.AddNew();
    }
    catch (System.Exception ex)
    {
        AxExceptionCategory exceptionCategory;

        if (!AxControlExceptionHandler.TryHandleException(this, ex, out exceptionCategory))
        {
            // Throw the fatal exception
            throw;
        }
        if (exceptionCategory == AxExceptionCategory.NonFatal)
        {
            AxGridView1.EditIndex = editIdx;
        }
    }
}

private DataSetView dsv //get dataset view
    {
        get
        {
            DataSet dataSet = this.AxDataSource1.GetDataSet();
            return dataSet.DataSetViews[this.AxGridView1.DataMember];
        }
    }


问:
Dilemma with Toast message
I'm developing a simple app, the user will have to fill in their name, email, rate the app, and describe their experience(optional). If their is an empty field(name and email), an error message will pop up. I'm having trouble with Toast.LENGTH_LONG() at the end of the code. It keep saying 'method call expected'.

MainActivity.java

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

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //Create an array adapter
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.rate_array, android.R.layout.simple_spinner_dropdown_item);

    //Specify the layout for the drop down menu
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    final EditText name = (EditText) findViewById(R.id.Name);
    final EditText e_mail = (EditText) findViewById(R.id.email);
    final Button submit = (Button) findViewById(R.id.submit);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(name.getText().length() == 0){
                name.setError("Please fill in your name");
            }
            else{
                if(e_mail.getText().length() == 0){
                    e_mail.setError("Please fill in your email");
                }
                else{
                    Toast.makeText(this, "Validation successful",
                    Toast.LENGTH_LONG()).show();
                }
            }
        }
    });

 }
}
</code>```

activity_main.xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.infinite_space.myapplication.MainActivity"
android:orientation="vertical"
android:weightSum="1">

<TextView
    android:id="@+id/textView"
    android:layout_width="292dp"
    android:layout_height="37dp"
    android:text="Enter Feedback details to b sent to the developers"
    android:visibility="visible"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_weight="0.18" />

<EditText
    android:id="@+id/Name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your Name"
    android:inputType="textPersonName"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="67dp" />

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="35dp"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"
    tools:layout_editor_absoluteY="176dp"
    tools:layout_editor_absoluteX="16dp"
    android:prompt="@string/rate_level"
    android:entries="@array/rate_array" />

<EditText
    android:id="@+id/email"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your email"
    android:inputType="textEmailAddress"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="122dp" />

<EditText
    android:id="@+id/details"
    android:layout_width="fill_parent"
    android:layout_height="103dp"
    android:ems="10"
    android:hint="Details..."
    android:inputType="text"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="227dp" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Would you like an email respond ?"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="343dp" />

<Button
    android:id="@+id/submit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Feedback"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="385dp" />
</LinearLayout>
</code>```

答: Toast.LENGTH_LONG is a (constant) field and not a method. Change LENGTH_LONG() to LENGTH_LONG.

Title: Dilemma with Toast message

Body:
I'm developing a simple app, the user will have to fill in their name, email, rate the app, and describe their experience(optional). If their is an empty field(name and email), an error message will pop up. I'm having trouble with Toast.LENGTH_LONG() at the end of the code. It keep saying 'method call expected'.

MainActivity.java

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

    Spinner spinner = (Spinner) findViewById(R.id.spinner1);

    //Create an array adapter
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.rate_array, android.R.layout.simple_spinner_dropdown_item);

    //Specify the layout for the drop down menu
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

    //Apply the adapter to the spinner
    spinner.setAdapter(adapter);

    final EditText name = (EditText) findViewById(R.id.Name);
    final EditText e_mail = (EditText) findViewById(R.id.email);
    final Button submit = (Button) findViewById(R.id.submit);

    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(name.getText().length() == 0){
                name.setError("Please fill in your name");
            }
            else{
                if(e_mail.getText().length() == 0){
                    e_mail.setError("Please fill in your email");
                }
                else{
                    Toast.makeText(this, "Validation successful",
                    Toast.LENGTH_LONG()).show();
                }
            }
        }
    });

 }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.infinite_space.myapplication.MainActivity"
android:orientation="vertical"
android:weightSum="1">

<TextView
    android:id="@+id/textView"
    android:layout_width="292dp"
    android:layout_height="37dp"
    android:text="Enter Feedback details to b sent to the developers"
    android:visibility="visible"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="16dp"
    android:layout_weight="0.18" />

<EditText
    android:id="@+id/Name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your Name"
    android:inputType="textPersonName"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="67dp" />

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="fill_parent"
    android:layout_height="35dp"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"
    tools:layout_editor_absoluteY="176dp"
    tools:layout_editor_absoluteX="16dp"
    android:prompt="@string/rate_level"
    android:entries="@array/rate_array" />

<EditText
    android:id="@+id/email"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ems="10"
    android:hint="Your email"
    android:inputType="textEmailAddress"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="122dp" />

<EditText
    android:id="@+id/details"
    android:layout_width="fill_parent"
    android:layout_height="103dp"
    android:ems="10"
    android:hint="Details..."
    android:inputType="text"
    tools:layout_editor_absoluteX="16dp"
    tools:layout_editor_absoluteY="227dp" />

<CheckBox
    android:id="@+id/checkBox"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Would you like an email respond ?"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="343dp" />

<Button
    android:id="@+id/submit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Send Feedback"
    tools:layout_editor_absoluteX="0dp"
    tools:layout_editor_absoluteY="385dp" />
</LinearLayout>


问:
Multiple Case Statements With Identical Expressions
I'm trying to evaluate a specific column to return five different columns - but the columns are based off the same expression in the CASE statements.

```<code>     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 1
          ELSE 0
     END AS [Invalid] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validMICcode] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validSerialNumber] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validFormat] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validProductionYear] ,
</code>```

I feel like is causing the table / column in question to be searched for the pattern five times, but I cannot figure out how rewrite it - or if it is even possible - to have one pattern search and define the columns based on the one search.

I'm trying different variations, but I cannot come up with the correct syntax for this issue:

```<code>CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 1
          ELSE 0
            CASE WHEN 1 THEN 1 END AS [Invalid]
            CASE WHEN 0 THEN 0 END AS [validMICode]
            CASE WHEN 0 THEN 0 END AS AS [validSerialNumber]
            CASE WHEN 0 THEN 0 END AS AS [validFormat]
            CASE WHEN 0 THEN 0 END AS AS [validProductionYear]
    END
</code>```

答:
One way would be a sub query and Bitwise NOT.</p>

```<code>select
    result Invalid,
    ~result validMICcode,
    ~result validSerialNumber,
    ~result validFormat,
    ~result validProductionYear
from
(

   select
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%'
       THEN CAST(1 As bit)
       ELSE CAST(0 As bit)
     End result
   from ...
) tbl
</code>```

Body:
I'm trying to evaluate a specific column to return five different columns - but the columns are based off the same expression in the CASE statements.

     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 1
          ELSE 0
     END AS [Invalid] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validMICcode] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validSerialNumber] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validFormat] ,
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 0
          ELSE 1
     END AS [validProductionYear] ,

I feel like is causing the table / column in question to be searched for the pattern five times, but I cannot figure out how rewrite it - or if it is even possible - to have one pattern search and define the columns based on the one search.

I'm trying different variations, but I cannot come up with the correct syntax for this issue:

CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%' THEN 1
          ELSE 0
            CASE WHEN 1 THEN 1 END AS [Invalid]
            CASE WHEN 0 THEN 0 END AS [validMICode]
            CASE WHEN 0 THEN 0 END AS AS [validSerialNumber]
            CASE WHEN 0 THEN 0 END AS AS [validFormat]
            CASE WHEN 0 THEN 0 END AS AS [validProductionYear]
    END

Body:
One way would be a sub query and Bitwise NOT.

select
    result Invalid,
    ~result validMICcode,
    ~result validSerialNumber,
    ~result validFormat,
    ~result validProductionYear
from
(

   select
     CASE WHEN va.HIN LIKE '%[-=!@#$%^&*()<>?:|\;./,]%'
       THEN CAST(1 As bit)
       ELSE CAST(0 As bit)
     End result
   from ...
) tbl