问:
Rounding views with Auto Layout?
I want to create circular views when using Auto Layout, due to this, I can't set specific radius values in my view.

I thought I had resolved this with the following code, but it doesn't execute on the view's first load for some reason and the view appears square until I push the view of the screen and bring it back (for example raising the keyboard and lowering it). Any idea why or how I can approach a fix?

```<code> override func viewWillLayoutSubviews() {
    self.myProfileView.userImage.layer.cornerRadius = self.myProfileView.userImage.frame.size.width * 0.5
    self.myProfileView.userImage.layer.borderWidth = 2
    self.myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
}
</code>```

Constraints:

```<code>userImage.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).multipliedBy(0.25)
            userImage.heightAnchor.constraint(equalTo: userImage.widthAnchor).isActive = true
            userImage.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.40).isActive = true
        }
</code>```

Before pushing the view on the screen when it first loads:

After I open and close the keyboard pushing the view off and back on screen:

答:
You should run the rounding code in viewDidLayoutSubviews instead, which runs after the layout has correct frames.

Also, execute layoutIfNeeded() for myProfileView before accessing its size.

```<code>override func viewDidLayoutSubviews() {
    myProfileView.layoutIfNeeded()

    myProfileView.userImage.layer.cornerRadius = myProfileView.userImage.frame.size.width * 0.5
    myProfileView.userImage.layer.borderWidth = 2
    myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
}
</code>```

Title: Rounding views with Auto Layout?

Body:
I want to create circular views when using Auto Layout, due to this, I can't set specific radius values in my view.

I thought I had resolved this with the following code, but it doesn't execute on the view's first load for some reason and the view appears square until I push the view of the screen and bring it back (for example raising the keyboard and lowering it). Any idea why or how I can approach a fix?

 override func viewWillLayoutSubviews() {
    self.myProfileView.userImage.layer.cornerRadius = self.myProfileView.userImage.frame.size.width * 0.5
    self.myProfileView.userImage.layer.borderWidth = 2
    self.myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
}

Constraints:

userImage.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).multipliedBy(0.25)
            userImage.heightAnchor.constraint(equalTo: userImage.widthAnchor).isActive = true
            userImage.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.40).isActive = true
        }

Before pushing the view on the screen when it first loads:

After I open and close the keyboard pushing the view off and back on screen:

Body:
You should run the rounding code in viewDidLayoutSubviews instead, which runs after the layout has correct frames.

Also, execute layoutIfNeeded() for myProfileView before accessing its size.

override func viewDidLayoutSubviews() {
    myProfileView.layoutIfNeeded()

    myProfileView.userImage.layer.cornerRadius = myProfileView.userImage.frame.size.width * 0.5
    myProfileView.userImage.layer.borderWidth = 2
    myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
}


来源: stackexchange

问:
Angular, setInterval cause component to non-stop update its UI
I need to have a setInterval in one of my child components to check one of my DIV height. Problem is I found out that this setInterval cause my component UI non-stop update itself. Event the parent component also non-stop update itself.

```<code>@Component({
  selector: 'app-test-comp',
  template: `
    <ul>
      <li *ngFor="let num of [1,2,3]">
        {{ print(num) }}
      </li>
    </ul>
  `,
})
class TestComponent {
  private attr: Date;
  constructor() {
    setInterval(() => {}, 1000)
  }
  print(num) {
    return num + ' ' + new Date();
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <ul>
      <li *ngFor="let num of [1,2,3,4]">{{ test(num) }}</li>
      </ul>
      <app-test-comp></app-test-comp>
    </div>
  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
  test(num) {
    return num + ' ' + new Date()
  }
}
</code>```

PlunkerLink

Refer to plunker link above, it clearly shows that root component and its child component keep on updating its UI. If I remove that setInterval in app.ts line 18, it will behave as normal.

I wish to know what causes the non-stop update UI problem and how to prevent that.

答:
The async methods like setInterval are monkey patched by zone.js, a library used by angular to
update the view after model has changed. Monkey patching means extending functionality of a method.
So whenever the setInterval is called, the angular change detection is fired to update the view.

You can run your code outside of angular to avoid running change detection:

```<code>constructor(
    private zone: NgZone
) {
    this.zone.runOutsideAngular(() => {
        setInterval(() => {}, 1000)
    })
}
</code>```

I have updated your plnkr with above example

ContentLicense: CC BY-SA 3.0

Body:
I need to have a setInterval in one of my child components to check one of my DIV height. Problem is I found out that this setInterval cause my component UI non-stop update itself. Event the parent component also non-stop update itself.

@Component({
  selector: 'app-test-comp',
  template: `

        {{ print(num) }}

  `,
})
class TestComponent {
  private attr: Date;
  constructor() {
    setInterval(() => {}, 1000)
  }
  print(num) {
    return num + ' ' + new Date();
  }
}

@Component({
  selector: 'my-app',
  template: `

Hello {{name}}

{{ test(num) }}

      <app-test-comp></app-test-comp>

  `,
})
export class App {
  name:string;
  constructor() {
    this.name = `Angular! v${VERSION.full}`
  }
  test(num) {
    return num + ' ' + new Date()
  }
}

PlunkerLink

Refer to plunker link above, it clearly shows that root component and its child component keep on updating its UI. If I remove that setInterval in app.ts line 18, it will behave as normal.

I wish to know what causes the non-stop update UI problem and how to prevent that.

Body:
The async methods like setInterval are monkey patched by zone.js, a library used by angular to
update the view after model has changed. Monkey patching means extending functionality of a method.
So whenever the setInterval is called, the angular change detection is fired to update the view.

You can run your code outside of angular to avoid running change detection:

constructor(
    private zone: NgZone
) {
    this.zone.runOutsideAngular(() => {
        setInterval(() => {}, 1000)
    })
}

I have updated your plnkr with above example


问:
Update Table A from loop data on table B
I want to update table qcard with data every record from q_id table

q_id table field and have 5 record

```<code>---------------
q_id  groupcode
----  ---------
1     A01
2     A02
3     A03
4     A05
5     A06
</code>```

qcard table now have data in field qcard 10001-2000
field loop q_id groupcode not data

```<code>qcard    loop  q_id    groupcode
-----    ----  ----    ---------
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
</code>```

I need to update qcard table with all record from q_id table for each loop (loop I set from 01,02,03,....to 99) if finish each loop have all record from q_id table

if works qcard table this data

```<code>-------------------------------
qcard   loop  q_id    groupcode
 -----   ----  ----    ---------
 10001   01   1      A01
 10002   01   2      A02
 10003   01   3      A03
 10004   01   4      A04
 10005   01   5      A05
 10006   02   1      A01
 10007   02   2      A02
 10008   02   3      A03
 10009   02   4      A04
 10010   02   5      A05
 ...... untill
 1xxxx   99    1     A01
 1xxxx   99    2     A02
 1xxxx   99    3     A03
 1xxxx   99    4     A04
 1xxxx   99    5     A05
</code>```

答:
Try this Answer,</p>

```<code>CREATE TABLE #Numbers(N INT)

INSERT INTO #NUMBERS(N)
SELECT TOP 495 ROW_NUMBER() OVER(ORDER BY T1.NUMBER) AS N
FROM   MASTER..spt_values T1
       CROSS JOIN MASTER..spt_values t2

SELECT N,CASE WHEN LEN(CAST((N+4)/5 as VARCHAR))<2 THEN '0'+CAST((N+4)/5 as VARCHAR) ELSE CAST((N+4)/5 as VARCHAR) END[Loop]
    ,CASE WHEN N%10 in(1,6) THEN 1 WHEN N%10 in(2,7) THEN 2 WHEN N%10 in(3,8) THEN 3 WHEN N%10 in(4,9) THEN 4 WHEN N%10 in(5,0) THEN 5 END q_id
from #Numbers

UPDATE A SET A.Loop=B.Loop, AND A.q_id=B.q_id
FROM qcard A,#Numbers B
WHERE (A.qcard%10000)=B.N

UPDATE B
SET B.groupcode=A.groupcode
FROM q_id A,qcard B
WHERE A.q_id=B.q_id

DROP TABLE #Numbers
</code>```

Body:
I want to update table qcard with data every record from q_id table

q_id table field and have 5 record

---------------
q_id  groupcode
----  ---------
1     A01
2     A02
3     A03
4     A05
5     A06

qcard table now have data in field qcard 10001-2000
field loop q_id groupcode not data

qcard    loop  q_id    groupcode
-----    ----  ----    ---------
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010

I need to update qcard table with all record from q_id table for each loop (loop I set from 01,02,03,....to 99) if finish each loop have all record from q_id table

if works qcard table this data

-------------------------------
qcard   loop  q_id    groupcode
 -----   ----  ----    ---------
 10001   01   1      A01
 10002   01   2      A02
 10003   01   3      A03
 10004   01   4      A04
 10005   01   5      A05
 10006   02   1      A01
 10007   02   2      A02
 10008   02   3      A03
 10009   02   4      A04
 10010   02   5      A05
 ...... untill
 1xxxx   99    1     A01
 1xxxx   99    2     A02
 1xxxx   99    3     A03
 1xxxx   99    4     A04
 1xxxx   99    5     A05

Body:
Try this Answer,

CREATE TABLE #Numbers(N INT)

INSERT INTO #NUMBERS(N)
SELECT TOP 495 ROW_NUMBER() OVER(ORDER BY T1.NUMBER) AS N
FROM   MASTER..spt_values T1
       CROSS JOIN MASTER..spt_values t2

SELECT N,CASE WHEN LEN(CAST((N+4)/5 as VARCHAR))<2 THEN '0'+CAST((N+4)/5 as VARCHAR) ELSE CAST((N+4)/5 as VARCHAR) END[Loop]
    ,CASE WHEN N%10 in(1,6) THEN 1 WHEN N%10 in(2,7) THEN 2 WHEN N%10 in(3,8) THEN 3 WHEN N%10 in(4,9) THEN 4 WHEN N%10 in(5,0) THEN 5 END q_id
from #Numbers

UPDATE A SET A.Loop=B.Loop, AND A.q_id=B.q_id
FROM qcard A,#Numbers B
WHERE (A.qcard%10000)=B.N

UPDATE B
SET B.groupcode=A.groupcode
FROM q_id A,qcard B
WHERE A.q_id=B.q_id

DROP TABLE #Numbers


问:
In place insertion into list (or array)
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

```<code>original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])
</code>```

Results in:

```<code>[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]
</code>```

whereas I want:

```<code>[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]
</code>```

答:
less elegant, but working too: use numpy ndarray, to increment indice each time:</p>

```<code>import numpy as np

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = np.array([[insertion_indices[i], new_numbers[i]] for i in range(len(insertion_indices))])

for pair in pairs:
    original_list.insert(pair[0], pair[1])
    pairs[:, 0] += 1
</code>```

Title: In place insertion into list (or array)

Body:
I'm running a script in Python, where I need to insert new numbers into an array  (or list) at certain index locations. The problem is that obviously as I insert new numbers, the index locations are invalidated. Is there a clever way to insert the new values at the index locations all at once? Or is the only solution to increment the index number (first value of the pair) as I add?

Sample test code snippets:

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = [(insertion_indices[i], new_numbers[i]) for i in range(len(insertion_indices))]

for pair in pairs:
    original_list.insert(pair[0], pair[1])

Results in:

[0, 8, 1, 2, 9, 10, 3, 4, 5, 6, 7]

whereas I want:

[0, 8, 1, 2, 3, 9, 4, 10, 5, 6, 7]

Body:
less elegant, but working too: use numpy ndarray, to increment indice each time:

import numpy as np

original_list = [0, 1, 2, 3, 4, 5, 6, 7]
insertion_indices = [1, 4, 5]
new_numbers = [8, 9, 10]
pairs = np.array([[insertion_indices[i], new_numbers[i]] for i in range(len(insertion_indices))])

for pair in pairs:
    original_list.insert(pair[0], pair[1])
    pairs[:, 0] += 1


问:
MySQL count value by ID
Not sure if the title explains what I am trying to do correctly however I was unable to word it.

I am trying to create an output for a some graphs. The output I am aiming for is just the total value of some rows in a mySQL table grouped by a category ID. My tables are as follows:

```<code>Transactions:

TransactiondID | TransactionName |TransactionCategory| Value
*************************************************************
       1       |  GenericText1   |      1            | 30
       2       |  GenericText2   |      1            | 38
       3       |  GenericText2   |      2            | 38
</code>```

And my Reference Data for TransactionCategory

```<code>TranCatID | TransCatName
*************************
    1     | Tranportation
    2     | Petrol
</code>```

So what I want to do is do is a SUM of the value field by each category. So I would get an output of.

```<code>Category       | Value
****************************
Transportation | 68
Petrol         | 30
</code>```

I got this but it does not work. I think it is completely incorrect but wanted to show my attempt.

```<code>SELECT SUM( `TransactionValue`) AS Value,
transaction_category.transaction_category
FROM Transactions
JOIN transaction_category on Transactions.TransactionID = transaction_category_id
</code>```

答:
This should do the trick</p>

```<code>SELECT TransactionCategory.TransCatName,
    SUM(Transactions.Value) as Value
FROM Transactions
    LEFT JOIN TransactionCategory ON TransactionCategory.TranCatID = Transaction.TransactionCategory
</code>```

Title: MySQL count value by ID

Body:
Not sure if the title explains what I am trying to do correctly however I was unable to word it.

I am trying to create an output for a some graphs. The output I am aiming for is just the total value of some rows in a mySQL table grouped by a category ID. My tables are as follows:

Transactions:

TransactiondID | TransactionName |TransactionCategory| Value
*************************************************************
       1       |  GenericText1   |      1            | 30
       2       |  GenericText2   |      1            | 38
       3       |  GenericText2   |      2            | 38

And my Reference Data for TransactionCategory

TranCatID | TransCatName
*************************
    1     | Tranportation
    2     | Petrol

So what I want to do is do is a SUM of the value field by each category. So I would get an output of.

Category       | Value
****************************
Transportation | 68
Petrol         | 30

I got this but it does not work. I think it is completely incorrect but wanted to show my attempt.

SELECT SUM( `TransactionValue`) AS Value,
transaction_category.transaction_category
FROM Transactions
JOIN transaction_category on Transactions.TransactionID = transaction_category_id

Body:
This should do the trick

SELECT TransactionCategory.TransCatName,
    SUM(Transactions.Value) as Value
FROM Transactions
    LEFT JOIN TransactionCategory ON TransactionCategory.TranCatID = Transaction.TransactionCategory


问:
How to get no error, if a String value is entered or the number not related to the cases
How to get no error, if a String value is entered or the number not related to the cases.</p>

```<code>switch(optionIssues) {
   case 1 : healthIssues = "Dental Problem"; ;break;
   case 2 : healthIssues = "Respiratory Diphtheria";;break;
   case 3 : healthIssues = "Mosquitoes Infections";;break;
}
</code>```

答:
You should add a default case like that:

```<code>switch(optionIssues){
            case 1 : healthIssues = "Dental Problem";break;
            case 2 : healthIssues = "Respiratory Diphtheria";break;
            case 3 : healthIssues = "Mosquitoes Infections";break;
            default : break;
        }
</code>```

You can see more about it here

Body:
How to get no error, if a String value is entered or the number not related to the cases.

switch(optionIssues) {
   case 1 : healthIssues = "Dental Problem"; ;break;
   case 2 : healthIssues = "Respiratory Diphtheria";;break;
   case 3 : healthIssues = "Mosquitoes Infections";;break;
}

Body:
You should add a default case like that:

switch(optionIssues){
            case 1 : healthIssues = "Dental Problem";break;
            case 2 : healthIssues = "Respiratory Diphtheria";break;
            case 3 : healthIssues = "Mosquitoes Infections";break;
            default : break;
        }

You can see more about it here


问:
Interpreting results from contiki's powertrace app
I am using contiki's powertrace (that in turn uses ENERGEST) to get power consumption. I came across the formula for that to be= ((rxon)*(RXi)*Vcc)/(cpu+lpm).
Where rxon, cpu and lpm are obtained from powertrace (i.e. times the mote spends in these states) and RXi (current) and Vcc (voltage) from datasheet.

My question is if I need to obtain total current consumption do I just remove the Vcc or do i need to remove Vcc and divide the whole thing by RTIMER_ARCH_SECOND. Since i read somewhere that powertrace results time in Rtimer ticks.

Thank you,
Avijit

答:
The following link explains in detail and with examples how to use powertrace. It provides the formula that you need:

http://thingschat.blogspot.de/2015/04/contiki-os-using-powertrace-and.html


问:
Windows Media Player in ASP.NET C#
First attempt at this: I created the Windows Media Player programmatically by adding the WMPLib as a reference in my project. I am trying to play a playlist using Windows Media Player in a ASP.Net web page (Visual Studio 2015). I cannot use the video tag used in examples for HTML 5 as I need to display .wmv, .mp4, .jpg formats in the control. When I run the code, no errors are displayed and I see an empty browser, what am I missing?
Here is my sample code:

```<code>    WMPLib.WindowsMediaPlayer Player;

    protected void Page_Load(object sender, EventArgs e)
    {
        FileNames();
    }

    public void FileNames()
    {
        String[] extentions = { "*.wmv", "*.mp4", "*.jpg" };
        List<string> files = new List<string>();
        foreach (string filter in extentions)
        {
            files.AddRange(System.IO.Directory.GetFiles(@"C:\Documents\", filter));
        }

        foreach (string ss in files)
        {
            String name = System.IO.Path.GetFileName(ss);
            Player = new WMPLib.WindowsMediaPlayer();

            WMPLib.IWMPPlaylist playList = Player.newPlaylist("myPlayList", "");
            playList.appendItem(Player.newMedia(name));
            Player.currentPlaylist = playList;
            Player.controls.play();
        }
    }
</code>```

I am aware of the hard coded path which is not good practice, however I just need to get this displaying on my local machine.
Thanks!

答:
After two more weeks of research we managed to come up with a solution by toggling between different types of controls based on the content that needs to be displayed. To display PowerPoint slideshows, we converted all slides to images and then looped through the collection. Here is a snippet of the code in case someone else needs a bit of guidance with a similar issue:

```<code> <body>
<form id="form1" runat="server">

    <%-- Video DIV --%>
    <div runat="server" id="VidDiv" class="fullscreen-bg">
    </div>
    <%-- IMAGE DIV --%>
    <div runat="server" id="container">
        <div runat="server" id="containers">
        </div>
        <%-- this is where the code gets dynamically created --%>
    </div>
</form>
 </body>
   <script src="Scripts/jquery-3.1.1.js"></script>
  <script id="CallMyFunction" type="text/javascript">
          var index = 1;
    document.getElementById("VidDiv").style.display = "none";

var ImageCount = 1;
autoSlide();

function autoSlide() {

    var x = document.getElementsByClassName("Images");
    var video_player = document.getElementsByClassName("fullscreen-bd__video");
    var count;
    var video;
    var videoSource = new Array(), vids, i;

    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    if (index > x.length) {
        index = 1
    }

    x[index - 1].style.display = "block";

    count = x.length;

    if (ImageCount <= count) {
        index++;
        ImageCount = 1 + ImageCount;
        setTimeout(autoSlide, 8000);
    }
    else {
        //this is where we should switch from image div to video div
        document.getElementById("container").style.display = "none";
        document.getElementById("VidDiv").style.display = "block";

        //create a counter to check the number of video tags
        video = document.getElementsByTagName('video'), numVideos = video.length;

        for (i = 0; i < numVideos; i++) {

            videoSource[i] = video.item(i).src;
            document.getElementById("myVideo" + i).style.display = "none";
        }

        var videoCount = 0;
        if (videoCount <= numVideos -1) {

            function videoPlay(videoNum) {
                if (videoCount > 0)
                {
                    document.getElementById("myVideo" + (videoCount - 1)).style.display = "none";
                }
                document.getElementById("myVideo" + videoCount).style.display = "block";

                document.getElementById("myVideo" + videoCount).setAttribute("src", "" + videoSource[videoCount] + "");
                document.getElementById("myVideo" + videoCount).load();
                document.getElementById("myVideo" + videoCount).play();
                onEndedVid = document.getElementById("myVideo" + videoCount);

                var onEndedVid;
                onEndedVid.onended = function () {
                    //at the end of the video, close full screen
                    myHandler();
                };

                videoCount = videoCount + 1;

            }

            function myHandler() {

                if (videoCount == numVideos) {
                    //this is where we should switch from image div to video div
                    document.getElementById("container").style.display = "none";
                    document.getElementById("VidDiv").style.display = "none";

                    location.reload();
                }
                else {
                    videoPlay(videoCount);
                }
            }
            myHandler();

        }
        else
        {
            ///back to images
            //refresh the page
            location.reload();
        }
    }
}
</code>```

Code behind:

```<code>// this will be a watcher that checks if is new content... if there is, delete the existing .wpl file and recreate the .wpl with new content links included
    private void CreateNewPlayList(string folder)
    {
        try
        {
            System.Threading.Thread.Sleep(5000);
            fileName = getDrive(folder) + @"\" + folder + "Playlist.wpl";
            FileInfo fileInfo = new FileInfo(fileName);

            String f = @"<?wpl version=""1.0""?>
           <smil>
           <head><meta name=""Generator"" content=""Microsoft Windows Media
         Player -- 10.0.0.3646""/>
           <author/>
          <title> a title goes here </title>
          </head>
          <body>
          <seq> ";
              String ff = @"
         </seq>
         </body>
         </smil>";
               using (FileStream fs = fileInfo.Create())
            {
                Byte[] txt = new UTF8Encoding(true).GetBytes(f);
                fs.Write(txt, 0, txt.Length);

                ////write paths and load only certain file types according to requirements into array
                String[] extentions = { "*.mp4", "*.wmv", "*.JPG".ToLower(), "*.ppt", "*.png" };

                List<string> files = new List<string>();

                foreach (string filter in extentions)
                {
                    files.AddRange(System.IO.Directory.GetFiles(getDrive(folder) + @"\", filter));
                }

                int filecount = files.Count;
                string[] video_lists = new string[files.Count];

                int counts = 0;
                foreach (string file in files)
                {
                    video_lists[counts] = file.ToString();
                    string PathfileName = Path.GetFileName(file);
                    Byte[] author;
                    //use the ppt to be able to go into the folder and add each slide as part of the playlist
                    if (Path.GetExtension(PathfileName) == ".ppt" || Path.GetExtension(PathfileName) == ".pptx")
                    {
                        //create a loop to loop through the folder that has the same name as ppt/pptx(PathFileName)
                        string pptDrive = getDrive(folder) + @"\" + Path.GetFileNameWithoutExtension(PathfileName) + @"\";
                        if (Directory.Exists(pptDrive))
                        {
                            string[] pptFilesFolder = Directory.GetFiles(pptDrive);
                            int counter = 1;
                            while (counter <= pptFilesFolder.Length)
                            {
                                foreach (string pptFile in pptFilesFolder)
                                {
                                    string pptFileName = Path.GetFileName(pptFile);
                                    string pptFileNameNoExt = Path.GetFileNameWithoutExtension(pptFile);

                                    int i = pptFilesFolder.Length;
                                    int ss = Convert.ToInt16(new String(pptFileNameNoExt.Where(Char.IsDigit).ToArray()));
                                    if (ss <= i && ss == counter)
                                    {
                                        author = new UTF8Encoding(true).GetBytes(@"<media src=""" + pptDrive + @"\" + pptFileName + "\"/>");
                                        fs.Write(author, 0, author.Length);
                                        counter++;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //do something...
                        }

                    }
                    else
                    {
                        author = new UTF8Encoding(true).GetBytes(@"<media src=""" + getDrive(folder) + @"\" + PathfileName + "\"/>");
                        fs.Write(author, 0, author.Length);
                    }
                    counts = counts + 1;
                }

                Byte[] toptxt = new UTF8Encoding(true).GetBytes(ff);
                fs.Write(toptxt, 0, toptxt.Length);

            }

        }
        catch (IOException io)
        {
            //error handling....

            return;
        }
        catch (Exception ex)
        {
            //error handling...
            return;
        }
    }
</code>```

The code can obviously be improved and optimized, but this is the base we used to get our app working. Thanks for all the advice and input!

Title: Windows Media Player in ASP.NET C#

Body:
First attempt at this: I created the Windows Media Player programmatically by adding the WMPLib as a reference in my project. I am trying to play a playlist using Windows Media Player in a ASP.Net web page (Visual Studio 2015). I cannot use the video tag used in examples for HTML 5 as I need to display .wmv, .mp4, .jpg formats in the control. When I run the code, no errors are displayed and I see an empty browser, what am I missing?
Here is my sample code:

    WMPLib.WindowsMediaPlayer Player;

    protected void Page_Load(object sender, EventArgs e)
    {
        FileNames();
    }

    public void FileNames()
    {
        String[] extentions = { "*.wmv", "*.mp4", "*.jpg" };
        List<string> files = new List<string>();
        foreach (string filter in extentions)
        {
            files.AddRange(System.IO.Directory.GetFiles(@"C:\Documents\", filter));
        }

        foreach (string ss in files)
        {
            String name = System.IO.Path.GetFileName(ss);
            Player = new WMPLib.WindowsMediaPlayer();

            WMPLib.IWMPPlaylist playList = Player.newPlaylist("myPlayList", "");
            playList.appendItem(Player.newMedia(name));
            Player.currentPlaylist = playList;
            Player.controls.play();
        }
    }

I am aware of the hard coded path which is not good practice, however I just need to get this displaying on my local machine.
Thanks!

Body:
After two more weeks of research we managed to come up with a solution by toggling between different types of controls based on the content that needs to be displayed. To display PowerPoint slideshows, we converted all slides to images and then looped through the collection. Here is a snippet of the code in case someone else needs a bit of guidance with a similar issue:

 <body>
<form id="form1" runat="server">

    <%-- Video DIV --%>
    <div runat="server" id="VidDiv" class="fullscreen-bg">
    </div>
    <%-- IMAGE DIV --%>
    <div runat="server" id="container">
        <div runat="server" id="containers">
        </div>
        <%-- this is where the code gets dynamically created --%>
    </div>
</form>
 </body>
   <script src="Scripts/jquery-3.1.1.js"></script>
  <script id="CallMyFunction" type="text/javascript">
          var index = 1;
    document.getElementById("VidDiv").style.display = "none";

var ImageCount = 1;
autoSlide();

function autoSlide() {

    var x = document.getElementsByClassName("Images");
    var video_player = document.getElementsByClassName("fullscreen-bd__video");
    var count;
    var video;
    var videoSource = new Array(), vids, i;

    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    if (index > x.length) {
        index = 1
    }

    x[index - 1].style.display = "block";

    count = x.length;

    if (ImageCount <= count) {
        index++;
        ImageCount = 1 + ImageCount;
        setTimeout(autoSlide, 8000);
    }
    else {
        //this is where we should switch from image div to video div
        document.getElementById("container").style.display = "none";
        document.getElementById("VidDiv").style.display = "block";

        //create a counter to check the number of video tags
        video = document.getElementsByTagName('video'), numVideos = video.length;

        for (i = 0; i < numVideos; i++) {

            videoSource[i] = video.item(i).src;
            document.getElementById("myVideo" + i).style.display = "none";
        }

        var videoCount = 0;
        if (videoCount <= numVideos -1) {

            function videoPlay(videoNum) {
                if (videoCount > 0)
                {
                    document.getElementById("myVideo" + (videoCount - 1)).style.display = "none";
                }
                document.getElementById("myVideo" + videoCount).style.display = "block";

                document.getElementById("myVideo" + videoCount).setAttribute("src", "" + videoSource[videoCount] + "");
                document.getElementById("myVideo" + videoCount).load();
                document.getElementById("myVideo" + videoCount).play();
                onEndedVid = document.getElementById("myVideo" + videoCount);

                var onEndedVid;
                onEndedVid.onended = function () {
                    //at the end of the video, close full screen
                    myHandler();
                };

                videoCount = videoCount + 1;

            }

            function myHandler() {

                if (videoCount == numVideos) {
                    //this is where we should switch from image div to video div
                    document.getElementById("container").style.display = "none";
                    document.getElementById("VidDiv").style.display = "none";

                    location.reload();
                }
                else {
                    videoPlay(videoCount);
                }
            }
            myHandler();

        }
        else
        {
            ///back to images
            //refresh the page
            location.reload();
        }
    }
}

Code behind:

// this will be a watcher that checks if is new content... if there is, delete the existing .wpl file and recreate the .wpl with new content links included
    private void CreateNewPlayList(string folder)
    {
        try
        {
            System.Threading.Thread.Sleep(5000);
            fileName = getDrive(folder) + @"\" + folder + "Playlist.wpl";
            FileInfo fileInfo = new FileInfo(fileName);

            String f = @"<?wpl version=""1.0""?>
           <smil>
           <head><meta name=""Generator"" content=""Microsoft Windows Media
         Player -- 10.0.0.3646""/>
           <author/>
          <title> a title goes here </title>
          </head>
          <body>
          <seq> ";
              String ff = @"
         </seq>
         </body>
         </smil>";
               using (FileStream fs = fileInfo.Create())
            {
                Byte[] txt = new UTF8Encoding(true).GetBytes(f);
                fs.Write(txt, 0, txt.Length);

                ////write paths and load only certain file types according to requirements into array
                String[] extentions = { "*.mp4", "*.wmv", "*.JPG".ToLower(), "*.ppt", "*.png" };

                List<string> files = new List<string>();

                foreach (string filter in extentions)
                {
                    files.AddRange(System.IO.Directory.GetFiles(getDrive(folder) + @"\", filter));
                }

                int filecount = files.Count;
                string[] video_lists = new string[files.Count];

                int counts = 0;
                foreach (string file in files)
                {
                    video_lists[counts] = file.ToString();
                    string PathfileName = Path.GetFileName(file);
                    Byte[] author;
                    //use the ppt to be able to go into the folder and add each slide as part of the playlist
                    if (Path.GetExtension(PathfileName) == ".ppt" || Path.GetExtension(PathfileName) == ".pptx")
                    {
                        //create a loop to loop through the folder that has the same name as ppt/pptx(PathFileName)
                        string pptDrive = getDrive(folder) + @"\" + Path.GetFileNameWithoutExtension(PathfileName) + @"\";
                        if (Directory.Exists(pptDrive))
                        {
                            string[] pptFilesFolder = Directory.GetFiles(pptDrive);
                            int counter = 1;
                            while (counter <= pptFilesFolder.Length)
                            {
                                foreach (string pptFile in pptFilesFolder)
                                {
                                    string pptFileName = Path.GetFileName(pptFile);
                                    string pptFileNameNoExt = Path.GetFileNameWithoutExtension(pptFile);

                                    int i = pptFilesFolder.Length;
                                    int ss = Convert.ToInt16(new String(pptFileNameNoExt.Where(Char.IsDigit).ToArray()));
                                    if (ss <= i && ss == counter)
                                    {
                                        author = new UTF8Encoding(true).GetBytes(@"<media src=""" + pptDrive + @"\" + pptFileName + "\"/>");
                                        fs.Write(author, 0, author.Length);
                                        counter++;
                                    }
                                }
                            }
                        }
                        else
                        {
                            //do something...
                        }

                    }
                    else
                    {
                        author = new UTF8Encoding(true).GetBytes(@"<media src=""" + getDrive(folder) + @"\" + PathfileName + "\"/>");
                        fs.Write(author, 0, author.Length);
                    }
                    counts = counts + 1;
                }

                Byte[] toptxt = new UTF8Encoding(true).GetBytes(ff);
                fs.Write(toptxt, 0, toptxt.Length);

            }

        }
        catch (IOException io)
        {
            //error handling....

            return;
        }
        catch (Exception ex)
        {
            //error handling...
            return;
        }
    }

The code can obviously be improved and optimized, but this is the base we used to get our app working. Thanks for all the advice and input!


问:
What is react-native component doing when the component is in background
What is react-native component doing when the component is in background?

And What will react-native do when component re-active to foreground?

Like Page A navigate to Page B.
And Page B back to Page A.What happened to A and B?

Is there any ui update like onResume on Android or something?

Edit:

I have a TabNavagation with four tab.One of the tabs renders an Android UI Component which is a custom frameLayout(a listview is in the frameLayout).

When the frameLayout first rendered, the listview position is not correct(position is -4 item height).But when I navigate to a child page and goback, I found that the frameLayout is correct now and does't enter any android lifecycle.

So I'm wondering is it doing something background?

答:
It is hard to tell without detail information on what type of navigation you are using but I can explain it considering you are using common navigation packages.

If your navigation is some sort of stack navigation, when you navigate/push a new screen to view the previous screen lays under the stack and doesn't un-mount. It is much like dealing a deck of card to a pile. It doesn't re-render unless the props or state of that specific component changes. When you navigate back the new screen un-mounts and the previous screen shows back.

Common packages lets you to pass props to the next screen and if you need to re-render a previous component a easy hack to achieve this by sending a function from the previous component and running it on componentWillUnmount life-cycle event of the current screen. I explained this sort of usage in this answer.


问:
while creating a class in java ,why we use class keyword not type?
a class in java (or in other oops languages) represent a data structure. every data structure has a type. so why one use CLASS keyword ? why can't TYPE keyword ?

i.e

we define new data structure in java like below -

```<code>public class CustomDataType {
    //bla bla
}
</code>```

why cant it be defined as below -

```<code>public type CustomDataType {
//bla bla
}
</code>```

Please explain.

答:
First answer: It's just a name. When you learn a (natural or programming) language, you have to accept the vocabulary that's in use.

Second answer: In my opinion, choosing the word "class" over "type" was a good decision. Pre-OOP languages like PASCAL or C already had "types", meaning static, open data structures. The OOP idea is that the data structure used to implement the type is just an implementation detail, but the operations you can do with the objects are the important aspect. And inheritance was rarely found / used in pre-OOP programming, but is at the very core of OOP.

So choosing a new term "class" made people aware that there were some really new concepts in the new languages.

And still today there are developers that didn't get it and use classes just like structures from the old days...

Body:
a class in java (or in other oops languages) represent a data structure. every data structure has a type. so why one use CLASS keyword ? why can't TYPE keyword ?

i.e

we define new data structure in java like below -

public class CustomDataType {
    //bla bla
}

why cant it be defined as below -

public type CustomDataType {
//bla bla
}

Please explain.


问:
Get AZ of a subnet through cloudformation script
I need to do something like...

"echo  --zones ",
     {
         "Ref": "az_of_subnet"
     },
" >> aws_details.txt\n"

in the user-data of an EC2 instance which is being created through the cloudformation script. The Subnet ID of an EXISTING subnet is known. Is there a way to get the availability zone of the subnet? Currently I'm taking this as an input (az_of_subnet) from the user, which seems redundant/not right, since I already know the subnet-id.

答:
EDIT:

Looks like AP wanted to use existing subnet which is not created in that cloud formation. So this is not currently supported in CloudFormation , so there might be 2 options(may be more)
1. Call APIs in user data script to get the AZ
2. Use terrform which supports this functionality


问:
How to convert IQueryable complex type to generic list in entity framework
```<code> IQueryable<SystemGroup> systemGroupQuery;

 systemGroupQuery = dbContext.SystemGroups.Select(x => new SystemGroup()
                    {
                        Id = x.Id,
                        Name = x.Name,
                        SmsAccountId = x.SmsAccountId,
                        SmsAccount = dbContext.SmsAccounts.Where(g => g.Id
 == x.SmsAccountId).SingleOrDefault()
                    });

 var systemGroups = systemGroupQuery.ToList();
</code>```

While converting to list i am getting the error "The entity or complex type 'Models.Context.SystemGroup' cannot be constructed in a LINQ to Entities query."

答:
Add .ToList() before .Select
or
use anonymous object and map it after .ToList()

Linq to entities doesnt allow constructing complex typed objects in the fly

Body:
 IQueryable<SystemGroup> systemGroupQuery;

 systemGroupQuery = dbContext.SystemGroups.Select(x => new SystemGroup()
                    {
                        Id = x.Id,
                        Name = x.Name,
                        SmsAccountId = x.SmsAccountId,
                        SmsAccount = dbContext.SmsAccounts.Where(g => g.Id
 == x.SmsAccountId).SingleOrDefault()
                    });

 var systemGroups = systemGroupQuery.ToList();

While converting to list i am getting the error "The entity or complex type 'Models.Context.SystemGroup' cannot be constructed in a LINQ to Entities query."


问:
Zipping multiple Files in C++
I need a zip library (or a function) that can zip\unzip a few files, i tried zlib or gzip I can't find a solution to archive more than one file in a single .zip (or .tar, or .gzip).

Does anyone have ideas?

答:
zlib can't on it's own, there is minizip in the contrib dir

Or you can use the newer zzlib library

ContentLicense: CC BY-SA 2.5

Title: Zipping multiple Files in C++


问:
How do I turn off PHP Notices?
```<code>Notice: Constant DIR_FS_CATALOG already defined
</code>```

I've already commented out display_errors in php.ini, but is not working.

How do I make PHP to not output such things to browsers?

UPDATE

I put display_errors = Off there but it's still reporting such notices,

Is this an issue with PHP 5.3?

Reporting numerous Call Stack too..

答:
Used This Line In Your Code

```<code>error_reporting(E_ALL ^ E_NOTICE);
</code>```

I think its helf full to you.

Title: How do I turn off PHP Notices?

Body:
Notice: Constant DIR_FS_CATALOG already defined

I've already commented out display_errors in php.ini, but is not working.

How do I make PHP to not output such things to browsers?

UPDATE

I put display_errors = Off there but it's still reporting such notices,

Is this an issue with PHP 5.3?

Reporting numerous Call Stack too..

Body:
Used This Line In Your Code

error_reporting(E_ALL ^ E_NOTICE);

I think its helf full to you.


问:
Using Bing Custom Search API with Drupal 7
We are planning to use Hosted UI version of Bing Search and have found it only supports query parameter 'q'. This parameter cannot be used with Drupal as it clashes with Drupal standard parameter which is also 'q'.

Is there anyway we can still use Bing Search Hosted UI without changing Drupal parameter 'q'?

Thanks

答:
Try using Bing search module.

It provides a search tab which pulls results from the Bing web service. The search query can be limited to a set of sites, and various advanced search query strings can be used (or appended to all search queries).


问:
Angularjs 1.5 localstorage getting overwrite when i open application in new tab with some other credentials
In angularjs 1.5 I have used local storage to store session related information.
But when I open new tab with some other credentials, initial information is getting erased and getting replaced by the new one, is there any way to prevent this ?</p>

答:
Yes there is, What you are doing is replacing the same key with new data that is why it is getting replaced. What you should be doing is create new 'Key' for each session.

Example

```<code>//localStorage.setItem('key', 'value' )
//What you should do is for each login user create a new key

//sessionId can be any id you want for new session, this way you won't overwrite the previous session data
  localStorage.setItem(sessionId, loginSessionData);
</code>```

Body:
Yes there is, What you are doing is replacing the same key with new data that is why it is getting replaced. What you should be doing is create new 'Key' for each session.

Example

//localStorage.setItem('key', 'value' )
//What you should do is for each login user create a new key

//sessionId can be any id you want for new session, this way you won't overwrite the previous session data
  localStorage.setItem(sessionId, loginSessionData);


问:
Setting Image Button via it's id into a 8x8 2d array. Android. Xamarin
I have made a 2d array of size 8 and 8 respectively, and i have made 64 image buttons, each with a b1, b2 b3 id. I would love to set the id into the array.

An example would be:

buttons[0, 0] = FindViewById(Resource.Id.b1);

buttons[0, 1] = FindViewById(Resource.Id.b2);

.

.

.

buttons[1, 0] = FindViewById(Resource.Id.b9);

Since I have 64 image button, do i have to write 64 lines to initialize each Resource.Id to be parsed into the 2d button array? I know I can do a double for loop for each row and column such as:

buttons[x, y] = FindViewById(Resource.Id.b1);

However I have to hardcode the resource.id of the image button to specify. Any way to shorten this? Thanks

答:
Yes, you can get the ID of the button dynamicaly and fill your array: </p>

```<code>    int overallCounter = 1;
    for (int i = 0 i < 8; i ++) {
       for (int j = 0;j < 8; j++ ) {
           buttons[i, j] = FindViewById(Resources.GetIdentifier("b" + overallCounter, "id", this.PackageName));
           overallCounter++;
       }
    }
</code>```

Body:
Yes, you can get the ID of the button dynamicaly and fill your array:

    int overallCounter = 1;
    for (int i = 0 i < 8; i ++) {
       for (int j = 0;j < 8; j++ ) {
           buttons[i, j] = FindViewById(Resources.GetIdentifier("b" + overallCounter, "id", this.PackageName));
           overallCounter++;
       }
    }


问:
Asynchronous Web Request, EntityFramework, and DI, how does it work?
I searched a lot about these subjects, but I'm still not sure it works as expected. And why.

What I understand:

While processing a web request, you are using one of IIS thread from its pool. Within that request if you use an async call to, for example, query some data from a database, you free up that thread, so that IIS can use that same thread to process another call. That’s good. Probably.

Sometime later when the database finally gives the awaited data, the code resumes. The async documentation mention that you now COULD be in another thread. Or not. DotNet's decision. If it's in the same thread as before, that’s ok.

I use Dependency Injection to inject and close the context on a PerRequest lifetime (using Microsoft Unity). Closing is my main concern here. It works perfectly in my synchronous world: the dbcontext is closed at the end of my web request.

EntityFramework is known to have its DbContext NOT thread safe

Question 1: Now if the resuming code is in another thread, is it from the same thread pool IIS has to process all requests or Is it from another side-pool?

Question 2: If the code runs in another thread, what about the WebRequest context? Will the DI track correctly the end of that deferred call and not call Dispose() before the async code is really over?

Question 3: If I use the async methods of EntityFramework, like ToListAsync or FirstOrDefaultAsync I read everywhere that "It should be ok". Can someone elaborate on that? Does EF track specifically the web request or the initial thread? Is there some sort of capture happening? Will my dbcontext be mixed up with another web request reusing my initial thread?

Question 4: If I use the normal (sync) methods of EntityFramework but wrapped within a Task. Whats gonna happen? Is it still "It should be ok"?

Sorry, that’s a lot of questions, its been bothering me for a long time now.

答:
Well, i can now try to answer my own questions.

Question 1:
From Do asynchronous operations in ASP.NET MVC use a thread from ThreadPool on .NET 4

Yes - all threads come from the thread-pool. Your MVC app is already multi-threaded, when a request comes in a new thread will be taken from the pool and used to service the request. That thread will be 'locked' (from other requests) until the request is fully serviced and completed. If there is no thread available in the pool the request will have to wait until one is available.
  If you have async controllers they still get a thread from the pool but while servicing the request they can give up the thread, while waiting for something to happen (and that thread can be given to another request) and when the original request needs a thread again it gets one from the pool.

Question 2: If the code runs in another thread, what about the WebRequest context?

From  ewk and http://vegetarianprogrammer.blogspot.fr/2012/12/understanding-synchronizationcontext-in.html
And https://msdn.microsoft.com/en-us/magazine/gg598924.aspx

The SynchronisationContext will make sure the Web Request (HttpContext.Current) is properly set on the current thread while resuming execution. This is part of ASP.NET background work.

Will the DI track correctly the end of that deferred call and not call Dispose() before the async code is really over?

Since the Web request flows on possibly multiple threads, and does not end with the initial thread, I don't see any reason why the EndRequest event would fire before the total flow is completed anymore. Thus, I see no reason anymore why a PerRequestLifeTimeManager or another PerRequest strategy would fail by calling some Dispose() before it's needed.

Question 3 à 4 : Async and EF. As ewk mentionned, Entity Framework is safe as long as you don't use it in different thread at the same time. As question 3 and 4 all shows different ways of hitting the DbContext, the answer is : To be safe, there should be only one simultaneous access to the DbContext whatever the way of runnning the tasks. As ewk mentionned, explicitely spinning 2 tasks using the same dbcontext is NOT safe.


问:
Loading localStorage is not updating my variables
I got these variables

```<code>var moneycount = 0;
var b1 = document.createElement("IMG");

function update() {
  document.getElementById('money').innerHTML = moneycount;
}
</code>```

And functions for saving/loading

```<code>function save() {
  localStorage.setItem("moneycount", moneycount);
};

function load() {
  moneycount = localStorage.getItem("moneycount");
  moneycount = parseInt(moneycount);
  update();
};
</code>```

This function works as intended but wont update with localStorage

```<code>function add() {
  moneycount = moneycount + 1
  if (moneycount >= 1) {
    document.getElementById('badge1').appendChild(b1);
  }
  update();
}
</code>```

It seems like var moneycount = 0 still is 0 after I load localStorage because if (moneycount >= 1) is not working. The document element is still displaying a bigger number after loading localStorage. Any ideas on how I can store my add() function?

Edit:

Found a temporary solution with setting setInterval(save, 5000); and adding  and calling it on refresh.

答:
The reason is (like mentioned in the comments) that your load() function also saves the localStorage instead of retrieving the value.

Your load() function should look like this:

```<code>function load() {
  moneycount = localStorage.getItem("moneycount");
  update();
};
</code>```

Body:
I got these variables

var moneycount = 0;
var b1 = document.createElement("IMG");

function update() {
  document.getElementById('money').innerHTML = moneycount;
}

And functions for saving/loading

function save() {
  localStorage.setItem("moneycount", moneycount);
};

function load() {
  moneycount = localStorage.getItem("moneycount");
  moneycount = parseInt(moneycount);
  update();
};

This function works as intended but wont update with localStorage

function add() {
  moneycount = moneycount + 1
  if (moneycount >= 1) {
    document.getElementById('badge1').appendChild(b1);
  }
  update();
}

It seems like var moneycount = 0 still is 0 after I load localStorage because if (moneycount >= 1) is not working. The document element is still displaying a bigger number after loading localStorage. Any ideas on how I can store my add() function?

Edit:

Found a temporary solution with setting setInterval(save, 5000); and adding  and calling it on refresh.

Body:
The reason is (like mentioned in the comments) that your load() function also saves the localStorage instead of retrieving the value.

Your load() function should look like this:

function load() {
  moneycount = localStorage.getItem("moneycount");
  update();
};


问:
Is there a name for this type of popular footer?
Screenshot of a footer:

I'm unsure if there is a particular name for that kind of footer or if it's a widget for a certain framework. That particular example was taken from buffalonews.com

After I know the name I can refine my searching for implementing it. Thank you for your input.

答: The part that lists the content of your website is called "sitemap" AFAIK</p>


问:
Kotlin convert TimeStamp to DateTime
I'm trying to find out how I can convert timestamp to datetime in Kotlin, this is very simple in Java but I cant find any equivalent of it in Kotlin.

For example: epoch timestamp (seconds since 1970-01-01) 1510500494 ==> DateTime object 2017-11-12 18:28:14.

Is there any solution for this in Kotlin or do I have to use Java syntax in Kotlin? Please give me a simple sample to show how I can resolve this problem.

this link is not an answer to my question

答:
```<code>private fun getDateTime(s: String): String? {
    try {
        val sdf = SimpleDateFormat("MM/dd/yyyy")
        val netDate = Date(Long.parseLong(s) * 1000)
        return sdf.format(netDate)
    } catch (e: Exception) {
        return e.toString()
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Kotlin convert TimeStamp to DateTime


问:
Is it beneficial to use ForkJoinPool as usual ExecutorService
Let's say I have a code like that:

```<code>class Foo {
    private final ExecutorService executor;

    public Foo(ExecutorService executor) {
        this.executor = executor;
    }

    public void doSomething() {
        executor.execute(() -> {/* Do important task */});
    }
}
</code>```

Can I gain better performance if instead of passing ThreadPoolExecutor in constructor I use ForkJoinPool. If yes then why and should I prefer use it in any circumstances instead of ThreadPoolExecutor.

Update 1

My question is about usage of ForkJoinPool through ExecutorService API and doesn't suppose recursive task splitting using ForkJoinPool specific API.

答:
Yes you can if you have recursive non-blocking tasks.

Here is great explanation from Cay S. Horstmann from recent Joker conference.

Body:
Let's say I have a code like that:

class Foo {
    private final ExecutorService executor;

    public Foo(ExecutorService executor) {
        this.executor = executor;
    }

    public void doSomething() {
        executor.execute(() -> {/* Do important task */});
    }
}

Can I gain better performance if instead of passing ThreadPoolExecutor in constructor I use ForkJoinPool. If yes then why and should I prefer use it in any circumstances instead of ThreadPoolExecutor.

Update 1

My question is about usage of ForkJoinPool through ExecutorService API and doesn't suppose recursive task splitting using ForkJoinPool specific API.


问:
Django filter by month and year
I am trying to filter a datetime field by month and year. For some unknown reason when entering both month and year I get back an empty set returned.

Model:

```<code>class SomePost(model.Models):
    timestamp = models.DateTimeField(auto_now_add=True)
</code>```

Query:

```<code>p = SomePost.objects.filter(timestamp__year=2014, timestamp__month=1)
</code>```

I think it is something to do with the month but I just cannot see what i am doing wrong.

Edit

Okay so I converted the model datetimefield into a datefield and the query worked.

The resulting sql was something like this:

```<code>SELECT
`a_post`.`id`,
`a_post`.`title`,
`a_post`.`slug`,
`a_post`.`text`,
`a_post`.`timestamp`,
`a_post`.`published` FROM `a_post`
WHERE EXTRACT(MONTH FROM `a_post`.`timestamp`) = 2
ORDER BY `a_post`.`timestamp` DESC;
</code>```

But when i converted it back into a datetimefield the sql was:

```<code>SELECT
`a_post`.`id`,
`a_post`.`title`,
`a_post`.`slug`,
`a_post`.`text`,
`a_post`.`timestamp`,
 `a_post`.`published` FROM `a_post`
WHERE EXTRACT(MONTH FROM CONVERT_TZ(`a_post`.`timestamp`, 'UTC', UTC)) = 1
ORDER BY `a_post`.`timestamp` DESC
</code>```

It appears as though the conver_tz is causing the issue. If I was to remove the convert_tz function when the query will return results.

Any ideas on whats going on here?

答:
I had the same issue in MySQL Ver 14.14 Distrib 5.6.33.

It was caused by empty time zone tables. I have fixed it by populating them:

```<code>shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql
</code>```

It's useful to read answers on MySQL CONVERT_TZ().

Title: Django filter by month and year

Body:
I am trying to filter a datetime field by month and year. For some unknown reason when entering both month and year I get back an empty set returned.

Model:

class SomePost(model.Models):
    timestamp = models.DateTimeField(auto_now_add=True)

Query:

p = SomePost.objects.filter(timestamp__year=2014, timestamp__month=1)

I think it is something to do with the month but I just cannot see what i am doing wrong.

Edit

Okay so I converted the model datetimefield into a datefield and the query worked.

The resulting sql was something like this:

SELECT
`a_post`.`id`,
`a_post`.`title`,
`a_post`.`slug`,
`a_post`.`text`,
`a_post`.`timestamp`,
`a_post`.`published` FROM `a_post`
WHERE EXTRACT(MONTH FROM `a_post`.`timestamp`) = 2
ORDER BY `a_post`.`timestamp` DESC;

But when i converted it back into a datetimefield the sql was:

SELECT
`a_post`.`id`,
`a_post`.`title`,
`a_post`.`slug`,
`a_post`.`text`,
`a_post`.`timestamp`,
 `a_post`.`published` FROM `a_post`
WHERE EXTRACT(MONTH FROM CONVERT_TZ(`a_post`.`timestamp`, 'UTC', UTC)) = 1
ORDER BY `a_post`.`timestamp` DESC

It appears as though the conver_tz is causing the issue. If I was to remove the convert_tz function when the query will return results.

Any ideas on whats going on here?

Body:
I had the same issue in MySQL Ver 14.14 Distrib 5.6.33.

It was caused by empty time zone tables. I have fixed it by populating them:

shell> mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root mysql

It's useful to read answers on MySQL CONVERT_TZ().


问:
Set hostname of service container to host's hostname
I run a docker swarm with docker swarm mode. Let's say I have 4 nodes, 1 manager, 3 worker. The hostnames are:

manager0

worker0

worker1

worker2

I start the service in global mode, so every node runs the service once.
Let's say the command looks like this:

```<code>docker service create --name myservice --mode global --network mynetwork ubuntu wait 3600
</code>```

mynetwork is an overlay network.

Now I am trying to access the hostname of the docker host in the containers, so I can pass the hostname to an application in the container.

I tried to pass the hostname with the environment variables (--env hostname=$(hostname)), but actually ${hostname} is only executed on the manager and the hostname is set to manager0 for all nodes.

Is there a way to access the hostname or pass the hostname to the containers?

答:
Here is the feature request, that has been implemented in docker version 17.10

https://github.com/moby/moby/issues/30966

Body:
I run a docker swarm with docker swarm mode. Let's say I have 4 nodes, 1 manager, 3 worker. The hostnames are:

manager0

worker0

worker1

worker2

I start the service in global mode, so every node runs the service once.
Let's say the command looks like this:

docker service create --name myservice --mode global --network mynetwork ubuntu wait 3600

mynetwork is an overlay network.

Now I am trying to access the hostname of the docker host in the containers, so I can pass the hostname to an application in the container.

I tried to pass the hostname with the environment variables (--env hostname=$(hostname)), but actually ${hostname} is only executed on the manager and the hostname is set to manager0 for all nodes.

Is there a way to access the hostname or pass the hostname to the containers?


问:
Apps manually installed in simulator crashes upon load
I'm installing MyApp on the iOS simulator (Xcode 7, iOS 9) using xcrun simctl install booted MyPath/MyApp.app.

This works as expected and the app is installed on the simulator.

However, launching the app either manually or using xcrun simctl launch booted com.company.MyApp fails. Giving back the error:

An error was encountered processing the command
  (domain=FBSOpenApplicationErrorDomain, code=1): The operation couldn’t
  be completed. (FBSOpenApplicationErrorDomain error 1.)

The app is exported from Xcode (note that running the app from Xcode or re-building the app from its source code is not a liable solution).

It's not app specific, as any app install in this manner crashes with the same error.

The system log reports the same error, but with some additional information.

com.apple.CoreSimulator.SimDevice.CA35ED48-DDAA-4CF0-8C69-C206CC55A6EB.launchd_sim[4200]
  (UIKitApplication:com.company.MyApp[0xe9ec][4281]): Program specified
  by service does not contain one of the requested architectures: R

SpringBoard[4217]: Unable to get pid for
  'UIKitApplication:com.company.MyApp[0xe9ec]': No such process (err 3)

SpringBoard[4217]: Bootstrapping failed for

SpringBoard[4217]: Application
  'UIKitApplication:com.company.MyApp[0xe9ec]' exited voluntarily.

SpringBoard[4217]: CGContextSaveGState: invalid context 0x0. If you
  want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE
  environmental variable.

SpringBoard[4217]: CGContextTranslateCTM: invalid context 0x0. If you
  want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE
  environmental variable.

SpringBoard[4217]: CGContextRestoreGState: invalid context 0x0. If you
  want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE
  environmental variable.

SpringBoard[4217]: CGContextSaveGState: invalid context 0x0. If you
  want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE
  environmental variable.

SpringBoard[4217]: CGContextTranslateCTM: invalid context 0x0. If you
  want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE
  environmental variable.

SpringBoard[4217]: CGContextRestoreGState: invalid context 0x0. If you
  want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE
  environmental variable.

com.apple.CoreSimulator.SimDevice.CA35ED48-DDAA-4CF0-8C69-C206CC55A6EB.launchd_sim[4200]
  (UIKitApplication:com.company.MyApp[0xc82f][4282]): Program specified
  by service does not contain one of the requested architectures: R

SpringBoard[4217]: Unable to get pid for
  'UIKitApplication:com.company.MyApp[0xc82f]': No such process (err 3)

SpringBoard[4217]: Bootstrapping failed for

SpringBoard[4217]: Application
  'UIKitApplication:com.company.MyApp[0xc82f]' exited voluntarily.

The architectures error varies the variable. R, f, etc.

What's the causing this issue? How may I resolve it?

答:
This can happen if you use the wrong sdk. If the project is built using the physical device sdk it crashes on start up when you try to open it on the simulator.

If you are building it from the command line with xcrun xcodebuild check thet the sdk is "iphonesimulator" not "iphoneos"

e.g

xcrun xcodebuild -scheme <yourScheme> -configuration Debug -project <yourProject>.xcodeproj -sdk iphonesimulator build


问:
Highlight few different text in UILabel
Hi I would like to know how to display uilabel text in this form?

```<code>let str = value as? String
let updatedStr = str?.replacingOccurrences(of: ",", with: "     ")
self.myInterestsLbl.text = updatedStr

//Highlight Text
let string = self.myInterestsLbl.text

if string?.range(of:"Fashion") != nil {
let fashion = "Fashion"
let range = (string! as NSString).range(of: fashion)
let attributedText = NSMutableAttributedString.init(string: string!)                                     attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 0.98, green: 0.84, blue: 0.04, alpha: 1.0) , range: range)
self.myInterestsLbl.attributedText = attributedText
 }

if string?.range(of:"Gadgets") != nil {
let fashion = "Gadgets"
let range = (string! as NSString).range(of: fashion)
let attributedText = NSMutableAttributedString.init(string: string!)                                         attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 0.98, green: 0.84, blue: 0.04, alpha: 1.0) , range: range)
self.myInterestsLbl.attributedText = attributedText
 }
</code>```

During the actual debuging the updatedStr = "Fashion     Gadgets     Travel" but the highlight text doest not highlight all as shown at the picture below. The result I want is the above image.

答:
```<code>@IBOutlet weak var myInterestsLbl:UILabel?

    let str = "Fashion Gadgets Travel";

    let updatedStr = str.replacingOccurrences(of: ",", with: "     ");
    self.myInterestsLbl!.text = updatedStr;

    //Highlight Text
    let string = self.myInterestsLbl!.text;

    if string?.range(of:"Fashion") != nil {
        let fashion = "Fashion";
        let range = (string! as NSString).range(of: fashion);

        let attributedText = NSMutableAttributedString.init(string: string!);
        attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 0.98, green: 0.84, blue: 0.04, alpha: 1.0) , range: range);
        self.myInterestsLbl!.attributedText = attributedText;
    }

    if string?.range(of:"Gadgets") != nil {
        let fashion = "Gadgets";
        let range = (string! as NSString).range(of: fashion);
        let attributedText = self.myInterestsLbl!.attributedText as? NSMutableAttributedString;  // You did mistake here. You were initialising it via String variable instead of changed attributed string.
        attributedText?.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 0.98, green: 0.84, blue: 0.04, alpha: 1.0) , range: range);
        self.myInterestsLbl!.attributedText = attributedText;
    }
</code>```

Title: Highlight few different text in UILabel

Body:
Hi I would like to know how to display uilabel text in this form?

let str = value as? String
let updatedStr = str?.replacingOccurrences(of: ",", with: "     ")
self.myInterestsLbl.text = updatedStr

//Highlight Text
let string = self.myInterestsLbl.text

if string?.range(of:"Fashion") != nil {
let fashion = "Fashion"
let range = (string! as NSString).range(of: fashion)
let attributedText = NSMutableAttributedString.init(string: string!)                                     attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 0.98, green: 0.84, blue: 0.04, alpha: 1.0) , range: range)
self.myInterestsLbl.attributedText = attributedText
 }

if string?.range(of:"Gadgets") != nil {
let fashion = "Gadgets"
let range = (string! as NSString).range(of: fashion)
let attributedText = NSMutableAttributedString.init(string: string!)                                         attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor(red: 0.98, green: 0.84, blue: 0.04, alpha: 1.0) , range: range)
self.myInterestsLbl.attributedText = attributedText
 }

During the actual debuging the updatedStr = "Fashion     Gadgets     Travel" but the highlight text doest not highlight all as shown at the picture below. The result I want is the above image.


问:
How to insert a new line ("\n") character in SQLite?
While trying to insert something like:

```<code>"Hello\nWorld"
</code>```

SQLite throws error something like:

Message: unrecognized token: "'Hello";"  (also few other errors)

Even though I convert above string to "Hello''\nWorld" or "Hello\"\n\"World", these escape characters sequences don't work in this case.

Currently using C++ language, I am inserting this column like any other simple string columns. I tried above escape sequence (even though I read in internet that, they don't work with \n).

How to insert new line and other such special characters in SQLite DB?

答:
Specific to Qt

To make the Qn generalised, I didn't mention about Qt. For those who use Qt, the multi-line handling is done in following way:

```<code>void InsertToDB (QString contents)
{
  contents.replace("\n", "<br>"); // ... rest will be taken care by Qt
  sqlite.insert<wherever>(contents);
}
</code>```

Note: We observe that even typing
 in a text box of Qt, inserts a new line!

Body:
While trying to insert something like:

"Hello\nWorld"

SQLite throws error something like:

Message: unrecognized token: "'Hello";"  (also few other errors)

Even though I convert above string to "Hello''\nWorld" or "Hello\"\n\"World", these escape characters sequences don't work in this case.

Currently using C++ language, I am inserting this column like any other simple string columns. I tried above escape sequence (even though I read in internet that, they don't work with \n).

How to insert new line and other such special characters in SQLite DB?

Body:
Specific to Qt

To make the Qn generalised, I didn't mention about Qt. For those who use Qt, the multi-line handling is done in following way:

void InsertToDB (QString contents)
{
  contents.replace("\n", "<br>"); // ... rest will be taken care by Qt
  sqlite.insert<wherever>(contents);
}

Note: We observe that even typing <br> in a text box of Qt, inserts a new line!


问:
How can I create a android swipe up menu? Please refer to the attached images
I want my home screen to look like this

When i click on the center button or swipe up a menu should appear

答:
Look at this library in GitHub.

SlideUp is a small library that allows you to add sweet slide effect
  to any view. Slide your views up, down, left or right with SlideUp!

https://github.com/mancj/SlideUp-Android


问:
Parrallelize filter and collect
How do we parallelize filter and add into a single collect operation - something like

```<code>List<Employee> result= emps.parallelStream().collect(new ArrayList<Employee>(),
                  a.add(emps.filter(e -> e.getSalary() > 30))//conceptually,
                  (a,b) -> a.addAll(b));
</code>```

Is this possible?

答:
After parallelStream() is called filter and collect called on this stream will be executed in parallel.

```<code>List<Employee> result= emps.parallelStream()
   .filter(e -> e.getSalary() > 30)
   .collect(Collectors.toList());
</code>```

Title: Parrallelize filter and collect

Body:
How do we parallelize filter and add into a single collect operation - something like

List<Employee> result= emps.parallelStream().collect(new ArrayList<Employee>(),
                  a.add(emps.filter(e -> e.getSalary() > 30))//conceptually,
                  (a,b) -> a.addAll(b));

Is this possible?

Body:
After parallelStream() is called filter and collect called on this stream will be executed in parallel.

List<Employee> result= emps.parallelStream()
   .filter(e -> e.getSalary() > 30)
   .collect(Collectors.toList());


问:
How to specify an `order by` on ambiguous column using spring batch and postgres?
I'm extending a JdbcPagingItemReader to do a query that sorts by a column, but it is not working, it seems spring batch and postgres create incompatible constraints.

In essence, the query (created using a SqlPagingQueryProviderFactoryBean) is:

```<code>select ta.my_id as i
from table_a ta join table_b tb on ta.my_id = tb.my_id
where ta.unrelated_field = 42
order by i;
</code>```

but this fails on the second page of results because the PostgresPagingQueryProvider modifies it here (called from here) to where (ta.unrelated_field = 42) AND ((i > the_last_value_in_the_previous_page)), and postgres does not allow putting column aliases (i) in the where clause.

I have tried other ways to specify the sorting key, but I don't see how any way could work because of the next constraints:

Postgres does not allow aliases in the where clause, such as i.

Postgres does not allow ambiguous columns in the order by clause, such as my_id, as it can refer to the column from 2 tables.

JdbcPagingItemReader assumes here that the sort key and the column in the select clause are called exactly the same

That call to ResultSet.getObject will compare the key with a list of column names without the table qualifier, so getObject("ta.my_id") won't work.

So, how can I make my initial query work? did I miss something? or is this a bug in spring batch? I can not rename my_id so that it is different in each table.

Edit

This question faces the exact same issue, but in his case he could use the unqualified column name, which doesn't work in my case, because the column appears in several tables.

More details:

To provide actual code and error messages, below there's the actual error I get when I use the alias in the order by clause (the i in the example is ss_id in the code, and my_id is subsnp_id, the code is here):

```<code>org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT distinct sub.subsnp_id AS ss_id,loc.snp_id AS rs_id,hgvs.hgvs_c AS hgvs_c_string,hgvs.start_c+1 AS hgvs_c_start,hgvs.stop_c+1 AS hgvs_c_stop,hgvs.ref_allele_c AS reference_c,hgvs.hgvs_t AS hgvs_t_string,hgvs.start_t+1 AS hgvs_t_start,hgvs.stop_t+1 AS hgvs_t_stop,hgvs.ref_allele_t AS reference_t,hgvs.var_allele AS alternate,obsvariation.pattern AS alleles,ctg.contig_name AS contig_name,loc.asn_from +1 AS contig_start,loc.asn_to +1 AS contig_end,loc.loc_type AS loc_type,ctg.contig_chr AS chromosome,loc.phys_pos_from + 1 AS chromosome_start,loc.phys_pos_from + 1 + loc.asn_to - loc.asn_from AS chromosome_end,batch.loc_batch_id_upp AS batch_name,CASE    WHEN hgvs.orient_c = 2 THEN -1 ELSE 1 END AS hgvs_c_orientation,CASE    WHEN hgvs.orient_t = 2 THEN -1 ELSE 1 END AS hgvs_t_orientation,CASE    WHEN loc.orientation = 1 THEN -1 ELSE 1 END AS snp_orientation,CASE    WHEN ctg.orient = 1 THEN -1 ELSE 1 END AS contig_orientation,CASE    WHEN link.substrand_reversed_flag = 1 THEN -1 ELSE 1 END AS subsnp_orientation FROM b150_snpcontigloc loc JOIN b150_contiginfo ctg ON ctg.ctg_id = loc.ctg_id JOIN snpsubsnplink link ON loc.snp_id = link.snp_id JOIN subsnp sub ON link.subsnp_id = sub.subsnp_id JOIN batch on sub.batch_id = batch.batch_id JOIN b150_snphgvslink hgvs ON hgvs.snp_link = loc.snp_id JOIN dbsnp_shared.obsvariation ON obsvariation.var_id = sub.variation_id WHERE (batch.batch_id = ? AND ctg.group_term IN (?) AND ctg.group_label LIKE ?) AND ((ss_id > ?)) ORDER BY ss_id ASC LIMIT 100]; nested exception is org.postgresql.util.PSQLException: ERROR: column "ss_id" does not exist
  Position: 1472
    at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:711) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:761) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:199) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.batch.item.database.JdbcPagingItemReader.doReadPage(JdbcPagingItemReader.java:218) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar!/:3.0.8.RELEASE]
    at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar!/:3.0.8.RELEASE]
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar!/:3.0.8.RELEASE]
    at uk.ac.ebi.eva.dbsnpimporter.io.readers.SubSnpCoreFieldsReader.read(SubSnpCoreFieldsReader.java:131) ~[classes!/:0.2-SNAPSHOT]
    ... 59 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: column "ss_id" does not exist
  Position: 1472
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:288) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:168) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:116) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:692) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    ... 68 common frames omitted
</code>```

答:
The solution I took was to use JdbcCursorItemReader instead of JdbcPagingItemReader, which solves my problem but does not answer if JdbcPagingItemReader is meant to (not) work in this use case.

The changes I made to our code is here.

Body:
I'm extending a JdbcPagingItemReader to do a query that sorts by a column, but it is not working, it seems spring batch and postgres create incompatible constraints.

In essence, the query (created using a SqlPagingQueryProviderFactoryBean) is:

select ta.my_id as i
from table_a ta join table_b tb on ta.my_id = tb.my_id
where ta.unrelated_field = 42
order by i;

but this fails on the second page of results because the PostgresPagingQueryProvider modifies it here (called from here) to where (ta.unrelated_field = 42) AND ((i > the_last_value_in_the_previous_page)), and postgres does not allow putting column aliases (i) in the where clause.

I have tried other ways to specify the sorting key, but I don't see how any way could work because of the next constraints:

Postgres does not allow aliases in the where clause, such as i.

Postgres does not allow ambiguous columns in the order by clause, such as my_id, as it can refer to the column from 2 tables.

JdbcPagingItemReader assumes here that the sort key and the column in the select clause are called exactly the same

That call to ResultSet.getObject will compare the key with a list of column names without the table qualifier, so getObject("ta.my_id") won't work.

So, how can I make my initial query work? did I miss something? or is this a bug in spring batch? I can not rename my_id so that it is different in each table.

Edit

This question faces the exact same issue, but in his case he could use the unqualified column name, which doesn't work in my case, because the column appears in several tables.

More details:

To provide actual code and error messages, below there's the actual error I get when I use the alias in the order by clause (the i in the example is ss_id in the code, and my_id is subsnp_id, the code is here):

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT distinct sub.subsnp_id AS ss_id,loc.snp_id AS rs_id,hgvs.hgvs_c AS hgvs_c_string,hgvs.start_c+1 AS hgvs_c_start,hgvs.stop_c+1 AS hgvs_c_stop,hgvs.ref_allele_c AS reference_c,hgvs.hgvs_t AS hgvs_t_string,hgvs.start_t+1 AS hgvs_t_start,hgvs.stop_t+1 AS hgvs_t_stop,hgvs.ref_allele_t AS reference_t,hgvs.var_allele AS alternate,obsvariation.pattern AS alleles,ctg.contig_name AS contig_name,loc.asn_from +1 AS contig_start,loc.asn_to +1 AS contig_end,loc.loc_type AS loc_type,ctg.contig_chr AS chromosome,loc.phys_pos_from + 1 AS chromosome_start,loc.phys_pos_from + 1 + loc.asn_to - loc.asn_from AS chromosome_end,batch.loc_batch_id_upp AS batch_name,CASE    WHEN hgvs.orient_c = 2 THEN -1 ELSE 1 END AS hgvs_c_orientation,CASE    WHEN hgvs.orient_t = 2 THEN -1 ELSE 1 END AS hgvs_t_orientation,CASE    WHEN loc.orientation = 1 THEN -1 ELSE 1 END AS snp_orientation,CASE    WHEN ctg.orient = 1 THEN -1 ELSE 1 END AS contig_orientation,CASE    WHEN link.substrand_reversed_flag = 1 THEN -1 ELSE 1 END AS subsnp_orientation FROM b150_snpcontigloc loc JOIN b150_contiginfo ctg ON ctg.ctg_id = loc.ctg_id JOIN snpsubsnplink link ON loc.snp_id = link.snp_id JOIN subsnp sub ON link.subsnp_id = sub.subsnp_id JOIN batch on sub.batch_id = batch.batch_id JOIN b150_snphgvslink hgvs ON hgvs.snp_link = loc.snp_id JOIN dbsnp_shared.obsvariation ON obsvariation.var_id = sub.variation_id WHERE (batch.batch_id = ? AND ctg.group_term IN (?) AND ctg.group_label LIKE ?) AND ((ss_id > ?)) ORDER BY ss_id ASC LIMIT 100]; nested exception is org.postgresql.util.PSQLException: ERROR: column "ss_id" does not exist
  Position: 1472
    at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:99) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:73) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:649) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:684) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:711) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:761) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:192) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.query(NamedParameterJdbcTemplate.java:199) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.batch.item.database.JdbcPagingItemReader.doReadPage(JdbcPagingItemReader.java:218) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar!/:3.0.8.RELEASE]
    at org.springframework.batch.item.database.AbstractPagingItemReader.doRead(AbstractPagingItemReader.java:108) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar!/:3.0.8.RELEASE]
    at org.springframework.batch.item.support.AbstractItemCountingItemStreamItemReader.read(AbstractItemCountingItemStreamItemReader.java:88) ~[spring-batch-infrastructure-3.0.8.RELEASE.jar!/:3.0.8.RELEASE]
    at uk.ac.ebi.eva.dbsnpimporter.io.readers.SubSnpCoreFieldsReader.read(SubSnpCoreFieldsReader.java:131) ~[classes!/:0.2-SNAPSHOT]
    ... 59 common frames omitted
Caused by: org.postgresql.util.PSQLException: ERROR: column "ss_id" does not exist
  Position: 1472
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2455) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2155) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:288) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:430) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:356) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:168) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.postgresql.jdbc.PgPreparedStatement.executeQuery(PgPreparedStatement.java:116) ~[postgresql-9.4.1212.jre7.jar!/:9.4.1212.jre7]
    at org.springframework.jdbc.core.JdbcTemplate$1.doInPreparedStatement(JdbcTemplate.java:692) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) ~[spring-jdbc-4.3.10.RELEASE.jar!/:4.3.10.RELEASE]
    ... 68 common frames omitted


问:
C++ comparing Char to Strings
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.</p>

```<code>#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}
</code>```

答:
You have more than one bug, so I'll just remark on all the code in order.

If you write

```<code>char vocals[7] = {'A' ... 'Y'};
</code>```

you have to manually keep the array size and the initializer in sync - here, for example, you missed one (you have 6 "vocals" in your initializer for a 7-element array).

It's less error-prone to write

```<code>char vowels[] = {'A', 'E', 'I', 'O', 'U'};
</code>```

and let the compiler count it for you. (I renamed it to "vowels" because that's what they're called in English, and removed 'Y' because it's not one - obviously you can stick with whatever works in Swedish.)

Similarly, this loop is wrong:

```<code>for(int v = 0; v < vocals[v]; v++)
</code>```

because you're comparing v (an index into your array) with vocals[v] which is a character value. They're two different types of thing, and comparing doesn't make sense here. The loop over an array would normally be written

```<code>for (int v = 0; v < sizeof(vocals)/sizeof(vocals[0]); ++v)
</code>```

so for some N-element array, the index v ranges from 0 to N-1. A simpler way is to just write

```<code>for (auto v : vocals)
</code>```

where v is now a character, taking the value of each vocal/vowel one-by-one in the loop body. The compiler can figure out the array size for you.

I'd honestly re-write all your loops in this style: you don't need to manage array indices and bounds manually unless you're doing something more complicated.

On top of the loop condition bugs, your character comparisons will anyway mostly fail: the vowel/vocal and consonant arrays both contain only upper-case letters, and your string is mostly lower-case. You need to manage this, for example with

```<code>#include <cctype>

// ...
for (auto c : word) {
  for (auto v : vowels) {
    if (v == std::toupper(c)) {
</code>```

Title: C++ comparing Char to Strings

Body:
I'm trying to loop through a word but only vowels are working for some reason. The other type prints out the amount of words in total. Please excuse my poor choise of words mixed with Swedish and English.

#include <iostream>

using namespace std;

int main()
{
    int vo = 0;
    int ko = 0;

    char vocals[7]
    {
        'A','O','U','E','I','Y'
    };

    char konsonanter[19]
    {
        'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','X','Z'
    };

    string word = "Toysoldier";

    for(int i = 0; i < word.length(); i++)
    {
        for(int v = 0; v < vocals[v]; v++)
        {
            if(vocals[v] == word[i])
                vo++;
        }

        for(int k = 0; k < konsonanter[k]; k++)
        {
            if(konsonanter[k] == word[i])
                ko++;
        }
    }

    cout << "Konsonanter = " << ko << " Vokaler = " << vo << endl;
}

Body:
You have more than one bug, so I'll just remark on all the code in order.

If you write

char vocals[7] = {'A' ... 'Y'};

you have to manually keep the array size and the initializer in sync - here, for example, you missed one (you have 6 "vocals" in your initializer for a 7-element array).

It's less error-prone to write

char vowels[] = {'A', 'E', 'I', 'O', 'U'};

and let the compiler count it for you. (I renamed it to "vowels" because that's what they're called in English, and removed 'Y' because it's not one - obviously you can stick with whatever works in Swedish.)

Similarly, this loop is wrong:

for(int v = 0; v < vocals[v]; v++)

because you're comparing v (an index into your array) with vocals[v] which is a character value. They're two different types of thing, and comparing doesn't make sense here. The loop over an array would normally be written

for (int v = 0; v < sizeof(vocals)/sizeof(vocals[0]); ++v)

so for some N-element array, the index v ranges from 0 to N-1. A simpler way is to just write

for (auto v : vocals)

where v is now a character, taking the value of each vocal/vowel one-by-one in the loop body. The compiler can figure out the array size for you.

I'd honestly re-write all your loops in this style: you don't need to manage array indices and bounds manually unless you're doing something more complicated.

On top of the loop condition bugs, your character comparisons will anyway mostly fail: the vowel/vocal and consonant arrays both contain only upper-case letters, and your string is mostly lower-case. You need to manage this, for example with

#include <cctype>

// ...
for (auto c : word) {
  for (auto v : vowels) {
    if (v == std::toupper(c)) {


问:
How to get no error, if a String value is entered or the number not related to the cases
How to get no error, if a String value is entered or the number not related to the cases.</p>

```<code>switch(optionIssues) {
   case 1 : healthIssues = "Dental Problem"; ;break;
   case 2 : healthIssues = "Respiratory Diphtheria";;break;
   case 3 : healthIssues = "Mosquitoes Infections";;break;
}
</code>```

答:
Adding a default case you will indicate your program what to do when none of the cases are fulfilled.

```<code>switch(optionIssues){
            case 1 : healthIssues = "Dental Problem"; ;break;
            case 2 : healthIssues = "Respiratory Diphtheria";;break;
            case 3 : healthIssues = "Mosquitoes Infections";;break;
            default:
                System.out.println("Introduce an integer between 1 and 3");
                break;
        }
</code>```

If you want to return to the switch when the user does not introduce the right option you can use a while loop with an ending condition like this one:

```<code>boolean exit = false;
System.out.println("Introduce number 4 to finish");

while(!exit) {
    switch(optionIssues){
            case 1 :
                healthIssues = "Dental Problem";
                break;
            case 2 :
                healthIssues = "Respiratory Diphtheria";
                break;
            case 3 :
                healthIssues = "Mosquitoes Infections";
                break;
            case 4 :
                exit = true;
                break;
            default:
                System.out.println("Introduce an integer between 1 and 4, please");
                break;
        }
}
</code>```

This way the swith will be repeated unless the user introduces option 4.
If you only want to repeat it when an incorrect number has been introduced:

```<code>boolean repeat= true;

while(repeat) {
    switch(optionIssues){
            case 1 :
                healthIssues = "Dental Problem";
                repeat = false;
                break;
            case 2 :
                healthIssues = "Respiratory Diphtheria";
                repeat = false;
                break;
            case 3 :
                healthIssues = "Mosquitoes Infections";
                repeat = false;
                break;
            default:
                System.out.println("Introduce an integer between 1 and 4, please");
                break;
        }
}
</code>```

If the user introduce a 5, the boolean repeat is true so it will repeat. But in case of a correct number, repeat is false so it goes out.

Body:
How to get no error, if a String value is entered or the number not related to the cases.

switch(optionIssues) {
   case 1 : healthIssues = "Dental Problem"; ;break;
   case 2 : healthIssues = "Respiratory Diphtheria";;break;
   case 3 : healthIssues = "Mosquitoes Infections";;break;
}

Body:
Adding a default case you will indicate your program what to do when none of the cases are fulfilled.

switch(optionIssues){
            case 1 : healthIssues = "Dental Problem"; ;break;
            case 2 : healthIssues = "Respiratory Diphtheria";;break;
            case 3 : healthIssues = "Mosquitoes Infections";;break;
            default:
                System.out.println("Introduce an integer between 1 and 3");
                break;
        }

If you want to return to the switch when the user does not introduce the right option you can use a while loop with an ending condition like this one:

boolean exit = false;
System.out.println("Introduce number 4 to finish");

while(!exit) {
    switch(optionIssues){
            case 1 :
                healthIssues = "Dental Problem";
                break;
            case 2 :
                healthIssues = "Respiratory Diphtheria";
                break;
            case 3 :
                healthIssues = "Mosquitoes Infections";
                break;
            case 4 :
                exit = true;
                break;
            default:
                System.out.println("Introduce an integer between 1 and 4, please");
                break;
        }
}

This way the swith will be repeated unless the user introduces option 4.
If you only want to repeat it when an incorrect number has been introduced:

boolean repeat= true;

while(repeat) {
    switch(optionIssues){
            case 1 :
                healthIssues = "Dental Problem";
                repeat = false;
                break;
            case 2 :
                healthIssues = "Respiratory Diphtheria";
                repeat = false;
                break;
            case 3 :
                healthIssues = "Mosquitoes Infections";
                repeat = false;
                break;
            default:
                System.out.println("Introduce an integer between 1 and 4, please");
                break;
        }
}

If the user introduce a 5, the boolean repeat is true so it will repeat. But in case of a correct number, repeat is false so it goes out.