问:
how do I access the main class's stage? + Can I pass functions as arguments like this?
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

```<code>
    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}
</code>```

And for the draggable.as:

```<code>
package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}
</code>```

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!

答:
if you need it so much you may:

```<code>private static var _instance: TestAPP;
//...
public function TestAPP(){
    _instance = this;
    //...
}

public static function get instance():TestAPP{
    return _instance;
}

public static function set instance(newVal: TestAPP):void{
    _instance = newVal;
}
</code>```

and you'll be able to reference its stage from any class where your TestAPP will be imported just with TestAPP.instance.stage.

 but _instance is a property of the class TestAPP itself, not its instances

Body:
There are two files in my actionscript project named "TestAPP", TestAPP.as and Draggable.as

TestAPP.as:

    package {
 import flash.display.Sprite;
 import flash.display.Stage;

 public class TestAPP extends Sprite
 {
  var _mainStage:Stage;
  public function TestAPP()//This is where we test the UI components.
  {

   var sp:Sprite = new Sprite();
   _mainStage = stage;
   _mainStage.addChild(sp);
   sp.graphics.beginFill(0x00FF00);
   sp.graphics.drawCircle(0,0,10);
   sp.graphics.endFill();
   sp.x = 50;
   sp.y = 50;
   var draggable1:Draggable = new draggable(sp,_mainStage,limitingfunc);
  }
  public function limitingfunc(x:Number,y:Number):int{
   return 0;
  }

 }
}

And for the draggable.as:

package
{
 import flash.display.Sprite;
 import flash.display.Stage;
 import flash.events.MouseEvent;

 public class Draggable
 {
  private var _limitingFunc:Function;
  private var _which:Sprite;
  private var _MouseSavedX:Number;
  private var _MouseSavedY:Number;

  private var _stage:Stage;
  public function Draggable(which:Sprite,stage:Stage,limitingfunc:Function)
  {
   _limitingFunc = limitingfunc;
   _which = which;
   _stage = stage;
   _which.addEventListener(MouseEvent.MOUSE_DOWN,begin_drag);

  }
  //limiting func: returns 0 when the object is free to move that place.
  //returns -1 when the user wants to block X coordinate changes (but maintain Y free)
  //returns -2 when the user wants to block Y ...
  //returns -3 or less when the user wants to block both X and Y from changing.
  //returns
  private function Return_0(x:Number = 0,y:Number = 0):int{
   return 0;
  }
  private function begin_drag(ev:MouseEvent):void{
   var xTo:Number = _stage.mouseX - _MouseSavedX + _which.x;
   var yTo:Number = _stage.mouseY - _MouseSavedY + _which.y;
   var limitingFuncReturnValue:int = _limitingFunc(xTo,yTo);
   if(limitingFuncReturnValue == 0){//free to move.
    _which.x = xTo;
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -1){//free to move Y
    _which.y = yTo;
   }
   else if(limitingFuncReturnValue == -2){
    _which.y = yTo;
   }
   //else:do nothing.
  }
 }
}

In "my actionscript theory", I'm supposed to see a circle that follows the mouse when I click it. (The draggable is not fully implemented) But the circle doesn't even budge :(

...I've been trying to figure out how to access the main class's stage property. I've googled for it, but still no progress.

Please help this helpless newb!!! I'll really appreciate your help:)
Thank you!

Body:
if you need it so much you may:

private static var _instance: TestAPP;
//...
public function TestAPP(){
    _instance = this;
    //...
}

public static function get instance():TestAPP{
    return _instance;
}

public static function set instance(newVal: TestAPP):void{
    _instance = newVal;
}

and you'll be able to reference its stage from any class where your TestAPP will be imported just with TestAPP.instance.stage.

 but _instance is a property of the class TestAPP itself, not its instances


来源: stackexchange

答:
Try the following</p>

```<code>SELECT
    DATE_FORMAT(created_at, "%Y-%m-%dT%H:00:00") `Time`,
    MAX(CASE WHEN url='url1' THEN ping END) `url1`,
    MAX(CASE WHEN url='url2' THEN ping END) `url2`,
    MAX(CASE WHEN url='url3' THEN ping END) `url3`
FROM ping_history
GROUP BY DATE_FORMAT(created_at, "%Y-%m-%dT%H:00:00")
</code>```

ContentLicense: CC BY-SA 3.0

Title: Select data from MySQL for multi line chart

Body:
I'm struggling for some time now with constructing of data to a model that Google Chart would accept.

Chart requires data like this (json):

[
['Time',               'url1', 'url2', 'url3'   ],
['2017-12-06T12:00:00', 1,      2,       4      ],
['2017-12-06T13:00:00', 3,      6,       5      ],
['2017-12-06T14:00:00', 2,      5,       2      ],
['2017-12-06T15:00:00', 7,      3,       1      ],
]

So it should be extracted in similar manner. There are 3 options - construct all data in PHP/JS or select it with MySQL and then just cleanup.

MySQL database table 'ping_history' looks like this:

|--------|-----------|-------------|---------------------|
| ID     | url       | ping        | created_at          |
|--------|-----------|-------------|---------------------|
| 0      | url1      | 1           | 2017-12-06T12:00:00 |
|--------|-----------|-------------|---------------------|
| 1      | url2      | 2           | 2017-12-06T12:00:00 |
|--------|-----------|-------------|---------------------|
| 2      | url3      | 4           | 2017-12-06T12:00:10 |
|--------|-----------|-------------|---------------------|
| 3      | url1      | 3           | 2017-12-06T13:00:20 |
|--------|-----------|-------------|---------------------|
| 4      | url2      | 6           | 2017-12-06T13:00:30 |
|--------|-----------|-------------|---------------------|
| 5      | url3      | 5           | 2017-12-06T13:00:00 |
|--------|-----------|-------------|---------------------|
| 6      | url1      | 2           | 2017-12-06T14:00:40 |
|--------|-----------|-------------|---------------------|
| 7      | url2      | 5           | 2017-12-06T14:00:00 |
|--------|-----------|-------------|---------------------|
| 8      | url3      | 2           | 2017-12-06T14:00:00 |
|--------|-----------|-------------|---------------------|
| 9      | url1      | 7           | 2017-12-06T15:00:01 |
|--------|-----------|-------------|---------------------|
| 10     | url2      | 3           | 2017-12-06T15:00:02 |
|--------|-----------|-------------|---------------------|
| 11     | url3      | 1           | 2017-12-06T15:00:03 |
|--------|-----------|-------------|---------------------|

Records are grouped by HOUR(created_at), ping selected as MAX(ping).

How to make those grouped url rows appear as column titles or first row and all records for particular url make to go vertically... In case no value for date - we use null.

Maybe I just don't know how this method is called and can't google it. Something like rotating results set :) Please help!

Body:
Try the following

SELECT
    DATE_FORMAT(created_at, "%Y-%m-%dT%H:00:00") `Time`,
    MAX(CASE WHEN url='url1' THEN ping END) `url1`,
    MAX(CASE WHEN url='url2' THEN ping END) `url2`,
    MAX(CASE WHEN url='url3' THEN ping END) `url3`
FROM ping_history
GROUP BY DATE_FORMAT(created_at, "%Y-%m-%dT%H:00:00")


问:
Blank screen when I use FineUI MVC Grid Control
I recently download FineUI free trial package, and try to use their grid control in my new project. I made new project, I didn't have any problem when use traditional MVC framework from asp.net. But I want to use FineuiMVC grid in my project to save some development effort.

I already added Fineuimvc.dll to my project. However, I see error

After some research, I realize adding @using FineuiMvc can resolve above issue. But I still see an empty screen. The view HTML source code looks like below

```<code>  <html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid/CheckAll - My ASP.NET Application</title>
    <!--##FineUIMvc.RenderCssExtension##-->
    <link href="/res/css/common.css" rel="stylesheet" type="text/css" />
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
    <link href="/Content/site.css" rel="stylesheet"/>
    <script src="/Scripts/modernizr-2.6.2.js"></script>
  </head>
  ....
    <!--##FineUIMvc.RenderScriptExtension##-->
    <script src="/Scripts/jquery-1.10.2.js"></script>
    <script src="/Scripts/bootstrap.js"></script>
    <script src="/Scripts/respond.js"></script>
    <script src="/res/js/grid.js"></script>
  ....
  </html>
</code>```

I notice there are two placeholders in the HTML source code, but not sure the root cause. Does any one know this if you are using FineUI control?

答:
using FineUIMvc

To avoid write "using FineUIMvc" on every view, you need update the Views/Web.config to add FineUIMvc namespace under <system.web.webPages.razor> section. One example is

```<code><system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="FineUIMvc" />
  </namespaces>
</pages>
</system.web.webPages.razor>
</code>```

Managed pipeline mode

Please double check your project setting. If you are using Integrated mode, please change the configuration to below

```<code><system.webServer>
<modules>
    <add name="FineUIMvcScriptModule" type="FineUIMvc.ScriptModule, FineUIMvc"/>
</modules>
<handlers>
    <add name="FineUIMvcResourceHandler" verb="GET" path="res.axd" type="FineUIMvc.ResourceHandler, FineUIMvc"/>
</handlers>
</system.webServer>
</code>```

For Classic mode, it is using <system.web> tag.

BTW, http://mvc.fineui.us/ has examples for your reference.

Hope above explanation can help you out.

Body:
I recently download FineUI free trial package, and try to use their grid control in my new project. I made new project, I didn't have any problem when use traditional MVC framework from asp.net. But I want to use FineuiMVC grid in my project to save some development effort.

I already added Fineuimvc.dll to my project. However, I see error

After some research, I realize adding @using FineuiMvc can resolve above issue. But I still see an empty screen. The view HTML source code looks like below

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grid/CheckAll - My ASP.NET Application</title>

    <link href="/res/css/common.css" rel="stylesheet" type="text/css" />
    <link href="/Content/bootstrap.css" rel="stylesheet"/>
    <link href="/Content/site.css" rel="stylesheet"/>

  ....

  ....

I notice there are two placeholders in the HTML source code, but not sure the root cause. Does any one know this if you are using FineUI control?

Body:
using FineUIMvc

To avoid write "using FineUIMvc" on every view, you need update the Views/Web.config to add FineUIMvc namespace under <system.web.webPages.razor> section. One example is

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="FineUIMvc" />
  </namespaces>
</pages>
</system.web.webPages.razor>

Managed pipeline mode

Please double check your project setting. If you are using Integrated mode, please change the configuration to below

<system.webServer>
<modules>
    <add name="FineUIMvcScriptModule" type="FineUIMvc.ScriptModule, FineUIMvc"/>
</modules>
<handlers>
    <add name="FineUIMvcResourceHandler" verb="GET" path="res.axd" type="FineUIMvc.ResourceHandler, FineUIMvc"/>
</handlers>
</system.webServer>

For Classic mode, it is using <system.web> tag.

BTW, http://mvc.fineui.us/ has examples for your reference.

Hope above explanation can help you out.


问:
How to place a button within another button (java)
I have been asked:

If it was possible to place a button within another button in a frame (with JFrame)

What happens when I try to do it (they ask to test if and tell what happens)

I have tried to do it, but I don't know how. The only thing I succeeded in doing was to put two buttons at the same place in BorderLayout (two buttons at "center" position for example, but I don't think it is the same thing as "one button within a button".

If someone knew if it is possible to do it or how to do it it would be great!

答:
Yes, one button can be added to another button. I'll leave you to investigate the second question.

```<code>import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.*;

public class ButtonQuestion {

    private JComponent ui = null;
    JButton button1;
    JButton button2;

    ButtonQuestion() {
        try {
            initUI();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public void initUI() throws MalformedURLException {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        button1 = new JButton("button 1", new ImageIcon(
                new URL("https://i.stack.imgur.com/in9g1.png")));
        button2 = new JButton("button 2", new ImageIcon(
                new URL("https://i.stack.imgur.com/wCF8S.png")));
        ui.add(button1);
        // Yep. One button can indeed be added to another..
        button1.add(button2);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                ButtonQuestion o = new ButtonQuestion();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
</code>```

Body:
Yes, one button can be added to another button. I'll leave you to investigate the second question.

import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.net.*;

public class ButtonQuestion {

    private JComponent ui = null;
    JButton button1;
    JButton button2;

    ButtonQuestion() {
        try {
            initUI();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }

    public void initUI() throws MalformedURLException {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        button1 = new JButton("button 1", new ImageIcon(
                new URL("https://i.stack.imgur.com/in9g1.png")));
        button2 = new JButton("button 2", new ImageIcon(
                new URL("https://i.stack.imgur.com/wCF8S.png")));
        ui.add(button1);
        // Yep. One button can indeed be added to another..
        button1.add(button2);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {
                }
                ButtonQuestion o = new ButtonQuestion();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}


问:
How to do json serialization using C#?
How to do json serialization using C# ?

答:
You can use this code to serialize your object

```<code>var serialized = JsonConvert.SerializeObject(*Your object*);
</code>```

You have to download the Newtonsoft library from here

Title: How to do json serialization using C#?

Body: How to do json serialization using C# ?

Body:
You can use this code to serialize your object

var serialized = JsonConvert.SerializeObject(*Your object*);

You have to download the Newtonsoft library from here

ContentLicense: CC BY-SA 4.0


问:
When analyzing the time complexity of an algorithm why do we drop the constant of the term with the largest degree
Suppose I have the following : T(n) = 5n^2 +2n
The asymtotic tight bound of this is theta n^2. I want to understand the reason behind dropping the 5. I understand why we ignore the lower order terms.</p>

答:
Consult the definition of big-O.

Keeping things simple[*], let's define that a function g is O(f) if there exist constants C and M such that for n > M, 0 <= g(n) < Cf(n).

The presence of a positive constant multiplier in f doesn't affect this, just choose C appropriately. Your example T is O(n^2) by choosing a value of C greater than 5, and a value of M big enough that the +2n is irrelevant. For for example, for n > 2 it's a fact that 5n^2 + 2n < 6n^2 (because n^2 > 2n), so with C= 6 and M = 2 we see that T(n) is O(n^2).

So it's true that T(n) is O(n^2), and also true that it's O(5n^2), and O(5n^2 + 2n). The most interesting of those facts is that it's O(n^2), since it's the simplest expression and the other two are logically equivalent. If we want to compare the complexities of different functions, then we want to use simple expressions.

For big-Theta just note that we can play the same trick when f and g are the other way around. The relation "g is Theta(f)" is an equivalence relation, so what are we going to choose as the representative member of the equivalence class of T? The simplest one.

[*] Keeping things less simple, we cope with negative numbers by using a limsup rather than a plain limit. My definition above is actually sufficient but not necessary.

ContentLicense: CC BY-SA 2.5


问:
How to check if external media player is playing in android?
I want to stop my media player if external media player is playing.

I've implemented following code but it is called even when my app media player is playing.

```<code>if (audioManager.isMusicActive()) {
                    return;
                }
</code>```

How to distinguish between in-app media player and external media player?

Any help would be appreciated.

答:
Two or more Android apps can play audio to the same output stream
  simultaneously. The system mixes everything together. While this is
  technically impressive, it can be very aggravating to a user. To avoid
  every music app playing at the same time, Android introduces the idea
  of audio focus. Only one app can hold audio focus at a time.

Further,

A well-behaved audio app should manage audio focus according to these
  general guidelines:

Call requestAudioFocus() immediately before starting to play and
  verify that the call returns AUDIOFOCUS_REQUEST_GRANTED. If you design
  your app as we describe in this guide, the call to requestAudioFocus()
  should be made in the onPlay() callback of your media session. When
  another app gains audio focus, stop or pause playing, or duck the
  volume down. When playback stops, abandon audio focus. Audio focus is
  handled differently depending on the the version of Android that is
  running:

You can check the more detail from developer link.

Body:
I want to stop my media player if external media player is playing.

I've implemented following code but it is called even when my app media player is playing.

if (audioManager.isMusicActive()) {
                    return;
                }

How to distinguish between in-app media player and external media player?

Any help would be appreciated.


问:
fputcsv() is not adding new row
i'm generating csv file of my attendance report, and i'm using fputcsv() function to generate it to csv file. I looped the list of students but its not retrieving all the students, its only giving me one student.

here's my code:

```<code>    // Fetch Students
    $students = $this->db->table('sys_user')
    ->select('*', DB::raw($gc))
    ->leftjoin('sys_user_student', 'sys_user_student.user_id', '=', 'sys_user.user_id')
    ->leftjoin('sys_mf_section', 'sys_mf_section.section_id', '=', 'sys_user_student.section_id')
    ->leftjoin('sys_mf_grade', 'sys_mf_grade.grade_id', '=', 'sys_user_student.grade_id')
    ->leftjoin('gen_access_control_log', 'gen_access_control_log.user_id', '=', 'sys_user.user_id')
    ->where(function($query) use ($search_from,$search_to){
        $query->whereBetween(DB::raw('Date(gen_access_control_log.created_at)'), [$search_from,$search_to]);
    })
    ->where('sys_user.user_type_id', "4")
    ->where('sys_mf_section.section_id', $section_name)
    ->where('sys_mf_grade.grade_id', $grade_name)
    ->where('gen_access_control_log.status', "entrance")
    ->groupby('gen_access_control_log.user_id')
    ->get()->toArray();

    // ------------------------ EXPORT TO CSV -------------------------//

        // Filename
        $filename = "Attendance ".$search_from." - ".$search_to;

        // Content
        $header = array('Student No.', 'Fullname', 'Gender');
        $head_merge = array_merge($header,$date_array);

        foreach ($students as $key => $value) {
            $id = $value->identification_number;
            $fullname = $value->last_name.", ".$value->first_name;
            $gender = $value->gender;
        }

        $list = array (
            $head_merge,
            array($id,$fullname,$gender)
        );

        // Generate CSV
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename=' . $filename);
        header("Content-Transfer-Encoding: UTF-8");

        $fp = fopen('php://output', 'w');
        foreach ($list as $key => $value) {
            fputcsv($fp, $value);
        }
        fclose($fp);
</code>```

instead of giving me this result:

+---------------------------------------------------+
 | id_no | fullname | gender | dec 1 | dec 2 | dec 3 |
 | 1     | stud1    | male   | A     | P     |  P    |
 | 2     | stud2    | male   | P     | P     |  P    |

this is what i get:

+---------------------------------------------------+
 | id_no | fullname | gender | dec 1 | dec 2 | dec 3 |
 | 1     | stud1    | male   | A     | P     |  P    |

i already dumped $students, it has the records of two students. Thanks guys!

答:
Panther is right in the comment above, it should look more like this:

```<code>$list = [];
$list[]=$head_merge;

foreach ($students as $key => $value) {
    $id = $value->identification_number;
    $fullname = $value->last_name.", ".$value->first_name;
    $gender = $value->gender;
    $list[]=[$id,$fullname,$gender];
}
</code>```

Or you could avoid the array-shorthand syntax, that works too

```<code>$list = array();
array_push($list, $head_merge);

foreach ($students as $key => $value) {
    $id = $value->identification_number;
    $fullname = $value->last_name.", ".$value->first_name;
    $gender = $value->gender;
    array_push($list, array($id,$fullname,$gender));
}
</code>```

Title: fputcsv() is not adding new row

Body:
i'm generating csv file of my attendance report, and i'm using fputcsv() function to generate it to csv file. I looped the list of students but its not retrieving all the students, its only giving me one student.

here's my code:

    // Fetch Students
    $students = $this->db->table('sys_user')
    ->select('*', DB::raw($gc))
    ->leftjoin('sys_user_student', 'sys_user_student.user_id', '=', 'sys_user.user_id')
    ->leftjoin('sys_mf_section', 'sys_mf_section.section_id', '=', 'sys_user_student.section_id')
    ->leftjoin('sys_mf_grade', 'sys_mf_grade.grade_id', '=', 'sys_user_student.grade_id')
    ->leftjoin('gen_access_control_log', 'gen_access_control_log.user_id', '=', 'sys_user.user_id')
    ->where(function($query) use ($search_from,$search_to){
        $query->whereBetween(DB::raw('Date(gen_access_control_log.created_at)'), [$search_from,$search_to]);
    })
    ->where('sys_user.user_type_id', "4")
    ->where('sys_mf_section.section_id', $section_name)
    ->where('sys_mf_grade.grade_id', $grade_name)
    ->where('gen_access_control_log.status', "entrance")
    ->groupby('gen_access_control_log.user_id')
    ->get()->toArray();

    // ------------------------ EXPORT TO CSV -------------------------//

        // Filename
        $filename = "Attendance ".$search_from." - ".$search_to;

        // Content
        $header = array('Student No.', 'Fullname', 'Gender');
        $head_merge = array_merge($header,$date_array);

        foreach ($students as $key => $value) {
            $id = $value->identification_number;
            $fullname = $value->last_name.", ".$value->first_name;
            $gender = $value->gender;
        }

        $list = array (
            $head_merge,
            array($id,$fullname,$gender)
        );

        // Generate CSV
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename=' . $filename);
        header("Content-Transfer-Encoding: UTF-8");

        $fp = fopen('php://output', 'w');
        foreach ($list as $key => $value) {
            fputcsv($fp, $value);
        }
        fclose($fp);

instead of giving me this result:

+---------------------------------------------------+
 | id_no | fullname | gender | dec 1 | dec 2 | dec 3 |
 | 1     | stud1    | male   | A     | P     |  P    |
 | 2     | stud2    | male   | P     | P     |  P    |

this is what i get:

+---------------------------------------------------+
 | id_no | fullname | gender | dec 1 | dec 2 | dec 3 |
 | 1     | stud1    | male   | A     | P     |  P    |

i already dumped $students, it has the records of two students. Thanks guys!

Body:
Panther is right in the comment above, it should look more like this:

$list = [];
$list[]=$head_merge;

foreach ($students as $key => $value) {
    $id = $value->identification_number;
    $fullname = $value->last_name.", ".$value->first_name;
    $gender = $value->gender;
    $list[]=[$id,$fullname,$gender];
}

Or you could avoid the array-shorthand syntax, that works too

$list = array();
array_push($list, $head_merge);

foreach ($students as $key => $value) {
    $id = $value->identification_number;
    $fullname = $value->last_name.", ".$value->first_name;
    $gender = $value->gender;
    array_push($list, array($id,$fullname,$gender));
}


问:
How to return a value from a function
I have an ArangoDB function that queries all the documents in the instanceCollection, inside databasehelper.js:

```<code>listInstances = function listInstances() {
    var instances = db.query(aqlQuery`
    FOR doc in instanceCollection
    RETURN doc
    `).then(
        cursor => cursor.all()
    ).then(
        result => {
            return result;
        }
    )
    return instances;
}
</code>```

Also, I want to use this function to reflect the JSON query to an Express API:

```<code>app.get('/', function(req, res) {
    var allInstances = databasehelper.listInstances();
    res.send(allInstances);
});
</code>```

The api result was nothing but an empty JSON {}.
How can I reflect the result of my ArangoDB query to my Express API call?

答:
Understand how promises work. The following is an idea on how it should be designed.

databasehelper.js => Return a promise

```<code>listInstances = function listInstances() {
    return db.query(`some query`)
    .then(cursor => cursor.all())
}
</code>```

in the route, => fetch the data from the promise

```<code>app.get('/', function(req, res) {
    databasehelper.listInstances()
    .then(result => {
        res.send(result);
    })
});
</code>```

Title: How to return a value from a function

Body:
I have an ArangoDB function that queries all the documents in the instanceCollection, inside databasehelper.js:

listInstances = function listInstances() {
    var instances = db.query(aqlQuery`
    FOR doc in instanceCollection
    RETURN doc
    `).then(
        cursor => cursor.all()
    ).then(
        result => {
            return result;
        }
    )
    return instances;
}

Also, I want to use this function to reflect the JSON query to an Express API:

app.get('/', function(req, res) {
    var allInstances = databasehelper.listInstances();
    res.send(allInstances);
});

The api result was nothing but an empty JSON {}.
How can I reflect the result of my ArangoDB query to my Express API call?

Body:
Understand how promises work. The following is an idea on how it should be designed.

databasehelper.js => Return a promise

listInstances = function listInstances() {
    return db.query(`some query`)
    .then(cursor => cursor.all())
}

in the route, => fetch the data from the promise

app.get('/', function(req, res) {
    databasehelper.listInstances()
    .then(result => {
        res.send(result);
    })
});


问:
In how place(activity/fragment/singleton) I must realise Observable from retrofit?
I use retrofit2 in my project. I have interface:

```<code>public interface ProductService {
    @POST("findProducts")
    Observable<ProductsResponse> getProducts();
}
</code>```

and service method:

```<code>public ProductService getProductService() {
        return getService(ProductService.class);
    }
</code>```

After that I use this service in my fragment. When I click to button I call this method:

```<code>@Override
        public void onClick(View view) {
            if (view.getId() == R.id.button) {
                RestApiFactory.getInstance().getProductService().getProducts()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProductHandler());
            }
        }
</code>```

and realise handler in this fragment:

```<code>private class ProductHandler implements Observer<ProductsResponse> {

        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, "onSubscribe: start");
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onNext(ProductsResponse value) {
           //save to DB in new Thread
        }

        @Override
        public void onError(Throwable e) {
            Log.d(TAG, "onError: "+ e.getMessage());
            price.setVisibility(View.INVISIBLE);
            progressBar.setVisibility(View.INVISIBLE);

        }

        @Override
        public void onComplete() {
            Log.d(TAG, "onComplete: finish");
            price.setVisibility(View.INVISIBLE);
            progressBar.setVisibility(View.INVISIBLE);
        }
    }
</code>```

is it correct to implement ProductHandler implements Observer<ProductsResponse>'s methods

```<code>onSubscribe
onNext
onError
onComplete
</code>```

in fragment?

I'm advised to move this in a singleton:

```<code>MySingleton.getInstanse().getData();
</code>```

and move all to getData :

```<code>public void getData(){
RestApiFactory.getInstance().getProductService().getProducts()
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<ProductsResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            //send broadcast and catch in Fragment
                        }

                        @Override
                        public void onNext(ProductsResponse productsResponse) {
                        //send broadcast and catch in Fragment
                        }

                        @Override
                        public void onError(Throwable e) {
                        //send broadcast and catch in Fragment
                        }

                        @Override
                        public void onComplete() {
                        //send broadcast and catch in Fragment
                        }
                    });
}
</code>```

but I think this is nonsense. who will tell you how to use it (in what place) Observable from retrofit?

答:
there is no need to implement Observer.You can just need to create an observer for the same.Let's see the example.

```<code>service.getProducts()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);
    }
</code>```

the observer should look like and must be initialized in oncreate:

```<code>mObserver = new Observer<ProductsResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposableList.add(d);
            }

            @Override
            public void onNext(ProductsResponse value) {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
            }
        };
</code>```

Body:
I use retrofit2 in my project. I have interface:

public interface ProductService {
    @POST("findProducts")
    Observable<ProductsResponse> getProducts();
}

and service method:

public ProductService getProductService() {
        return getService(ProductService.class);
    }

After that I use this service in my fragment. When I click to button I call this method:

@Override
        public void onClick(View view) {
            if (view.getId() == R.id.button) {
                RestApiFactory.getInstance().getProductService().getProducts()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new ProductHandler());
            }
        }

and realise handler in this fragment:

private class ProductHandler implements Observer<ProductsResponse> {

        @Override
        public void onSubscribe(Disposable d) {
            Log.d(TAG, "onSubscribe: start");
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onNext(ProductsResponse value) {
           //save to DB in new Thread
        }

        @Override
        public void onError(Throwable e) {
            Log.d(TAG, "onError: "+ e.getMessage());
            price.setVisibility(View.INVISIBLE);
            progressBar.setVisibility(View.INVISIBLE);

        }

        @Override
        public void onComplete() {
            Log.d(TAG, "onComplete: finish");
            price.setVisibility(View.INVISIBLE);
            progressBar.setVisibility(View.INVISIBLE);
        }
    }

is it correct to implement ProductHandler implements Observer<ProductsResponse>'s methods

onSubscribe
onNext
onError
onComplete

in fragment?

I'm advised to move this in a singleton:

MySingleton.getInstanse().getData();

and move all to getData :

public void getData(){
RestApiFactory.getInstance().getProductService().getProducts()
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<ProductsResponse>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            //send broadcast and catch in Fragment
                        }

                        @Override
                        public void onNext(ProductsResponse productsResponse) {
                        //send broadcast and catch in Fragment
                        }

                        @Override
                        public void onError(Throwable e) {
                        //send broadcast and catch in Fragment
                        }

                        @Override
                        public void onComplete() {
                        //send broadcast and catch in Fragment
                        }
                    });
}

but I think this is nonsense. who will tell you how to use it (in what place) Observable from retrofit?

Body:
there is no need to implement Observer.You can just need to create an observer for the same.Let's see the example.

service.getProducts()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);
    }

the observer should look like and must be initialized in oncreate:

mObserver = new Observer<ProductsResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposableList.add(d);
            }

            @Override
            public void onNext(ProductsResponse value) {

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onComplete() {
            }
        };


问:
FireBase onChild Added
I am adding a ".push()" method key on a button click.

Every time i add a "Child" to the parent node it always fetches all the child to that particular node.
Here is the database structure.

Supposed there are already 5 child nodes under the "plans" parent node.
I will add one more node and all the 5 will be displayed as well and then the 6th one will be displayed too. So total of 11 nodes will be displayed.

I Researched and saw the "Onchildadded" method will work for this just fine but its doing the same thing as the addValueEventListener.

Here is my code for the on addValueEventListener(The initial method I have attached to the onStart of the activity, So anytime a user opens the app it displays all the nodes at that moment in the recyclerview and cardview.

```<code> q1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
            {

                cardViewPlaninfo card = dataSnapshot1.getValue(cardViewPlaninfo.class);

                    listplans .add(card);
                String TAG = "cardTAG";

                cardViewPlaninfo cvpi = new cardViewPlaninfo(card.getUserKEY(),card.getPlanpostedbyname().toString(),card.getCategory().toString(),card.getLocation().toString(),card.getDateandtime().toString(),card.getContribute().toString(),card.getExtranotes().toString());

                cardViewPlaninfolistobj.add(cvpi);
                adapter.notifyDataSetChanged();

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    super.onStart();

}
</code>```

AND THIS IS the code i'm writing on "Swipe refresh view".

```<code>void refreshItems()
{
    Query q1 = databaseUsers.child("plans");

    q1.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            Log.i("OnChildAdded",dataSnapshot.getKey().toString());

                cardViewPlaninfo card = dataSnapshot.getValue(cardViewPlaninfo.class);

                listplans .add(card);
                String TAG = "cardTAG";

                cardViewPlaninfolistobj.add(card);

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    onItemsLoadComplete();

}

void onItemsLoadComplete()
{

    srl.setRefreshing(false);
    adapter.notifyDataSetChanged();
}
</code>```

So the last idea is that when a user opens the activity "AfterLogin" the onStart() method runs and it shows all the child nodes under the parent node "plans". And When ever another user adds a node that is a child node under the parent node "plans", The other users should be able to swipe and the only child node added is shown with the other 5. So 5 nodes that are already added+ 1 the new node that has been added.

Help!

答:
You need to remove refreshItems() method from your code it is not needed i have try this code hope this will work for you.</p>

```<code>Query query = null;
        query = FirebaseDatabase.getInstance().getReference().child("Parent Node");
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                query.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        cardViewPlaninfo card = dataSnapshot.getValue(cardViewPlaninfo.class);
                        mCardViewPlaninfoRecyclerAdapter.add(card);
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                        Log.d("Unable to get message: " + "child changed");
                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {
                        Log.d("Unable to get message: " + "child removed");
                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.d("Unable to get message: " + databaseError.getMessage());
                    }
                });

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d("Unable to get message:", "Unable to get message: ");

            }
        });

        //add this method to your adapter
        public void add(cardViewPlaninfo card) {
                        mCardViewPlaninfoList.add(card);
                        notifyItemInserted(mCardViewPlaninfoList.size() - 1);
                        }
</code>```

Title: FireBase onChild Added

Body:
I am adding a ".push()" method key on a button click.

Every time i add a "Child" to the parent node it always fetches all the child to that particular node.
Here is the database structure.

Supposed there are already 5 child nodes under the "plans" parent node.
I will add one more node and all the 5 will be displayed as well and then the 6th one will be displayed too. So total of 11 nodes will be displayed.

I Researched and saw the "Onchildadded" method will work for this just fine but its doing the same thing as the addValueEventListener.

Here is my code for the on addValueEventListener(The initial method I have attached to the onStart of the activity, So anytime a user opens the app it displays all the nodes at that moment in the recyclerview and cardview.

 q1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot dataSnapshot1:dataSnapshot.getChildren())
            {

                cardViewPlaninfo card = dataSnapshot1.getValue(cardViewPlaninfo.class);

                    listplans .add(card);
                String TAG = "cardTAG";

                cardViewPlaninfo cvpi = new cardViewPlaninfo(card.getUserKEY(),card.getPlanpostedbyname().toString(),card.getCategory().toString(),card.getLocation().toString(),card.getDateandtime().toString(),card.getContribute().toString(),card.getExtranotes().toString());

                cardViewPlaninfolistobj.add(cvpi);
                adapter.notifyDataSetChanged();

            }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    super.onStart();

}

AND THIS IS the code i'm writing on "Swipe refresh view".

void refreshItems()
{
    Query q1 = databaseUsers.child("plans");

    q1.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {

            Log.i("OnChildAdded",dataSnapshot.getKey().toString());

                cardViewPlaninfo card = dataSnapshot.getValue(cardViewPlaninfo.class);

                listplans .add(card);
                String TAG = "cardTAG";

                cardViewPlaninfolistobj.add(card);

            adapter.notifyDataSetChanged();

        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

    onItemsLoadComplete();

}

void onItemsLoadComplete()
{

    srl.setRefreshing(false);
    adapter.notifyDataSetChanged();
}

So the last idea is that when a user opens the activity "AfterLogin" the onStart() method runs and it shows all the child nodes under the parent node "plans". And When ever another user adds a node that is a child node under the parent node "plans", The other users should be able to swipe and the only child node added is shown with the other 5. So 5 nodes that are already added+ 1 the new node that has been added.

Help!

Body:
You need to remove refreshItems() method from your code it is not needed i have try this code hope this will work for you.

Query query = null;
        query = FirebaseDatabase.getInstance().getReference().child("Parent Node");
        query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                query.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        cardViewPlaninfo card = dataSnapshot.getValue(cardViewPlaninfo.class);
                        mCardViewPlaninfoRecyclerAdapter.add(card);
                    }

                    @Override
                    public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                        Log.d("Unable to get message: " + "child changed");
                    }

                    @Override
                    public void onChildRemoved(DataSnapshot dataSnapshot) {
                        Log.d("Unable to get message: " + "child removed");
                    }

                    @Override
                    public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        Log.d("Unable to get message: " + databaseError.getMessage());
                    }
                });

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.d("Unable to get message:", "Unable to get message: ");

            }
        });

        //add this method to your adapter
        public void add(cardViewPlaninfo card) {
                        mCardViewPlaninfoList.add(card);
                        notifyItemInserted(mCardViewPlaninfoList.size() - 1);
                        }


问:
DataInputStream for input text files?
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?</p>

```<code>import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}
</code>```

答: The DataInputStream class is not for reading text files. it can only be used to read what DataOutput writes. If you have rows of human-readable numbers, you need to use an InputStreamReader and then parse the resulting streams with things like Double.parseDouble

Title: DataInputStream for input text files?

Body:
I am learning to read and write in Java and am stuck with a simple exercise. The program reads from 2 txt files that each contain numbers in rows. It writes to an output file the result of the multiplication of each row of numbers. eg. file 1 row 1 : 10, file 2 row 1: 2 , the program should write 20 to the output file. My code seems to have something missing somewhere. The output file is created but nothing is written to it. Any ideas?

import java.io.*;
import java.util.*;

class ReadWriteData
{
    public static void main(String[] args) throws Exception
    {

        //create ouput file
        PrintWriter output = new PrintWriter("output2.txt");

        DataInputStream file1 = new DataInputStream(new FileInputStream(args[0]));
        DataInputStream file2 = new DataInputStream(new FileInputStream(args[1]));

        try
        {

        // read data from file
        while (true)
        {
            double number1 = file1.readDouble();
            double number2 = file2.readDouble();
            double result = number1 * number2 ;
            output.println(result);

        }

        }

        catch (IOException e)
        {
            System.err.println("Error");
            System.exit(1);
        }

        output.close() ;

    }
}


问:
Heroku: failure to compile node.js in dependecies
So i have tried to figure this out and i am having the hardest time understanding why its failing? I have tried a few of the methods online and I have node_modules in my .gitignore so I don't really understand why its broken.

I have also tried

```<code>git push -f heroku master
</code>```

This failed to work as well although it should be forcing it to work. So it doesn't make very much sense to me.

This is the terminal response

答:
The error "Cannot read property '0' of undefined" looks like npm/npm issue 17858

It requires an update:

I confirm that npm@latest does the trick for me:

```<code>node 9.2.0
npm 5.6.0
</code>```

Body:
So i have tried to figure this out and i am having the hardest time understanding why its failing? I have tried a few of the methods online and I have node_modules in my .gitignore so I don't really understand why its broken.

I have also tried

git push -f heroku master

This failed to work as well although it should be forcing it to work. So it doesn't make very much sense to me.

This is the terminal response

Body:
The error "Cannot read property '0' of undefined" looks like npm/npm issue 17858

It requires an update:

I confirm that npm@latest does the trick for me:

node 9.2.0
npm 5.6.0


问:
Doctrine 2: What does getResult return when there are no rows? null?
I wonder what is returned by functions like get*Result(). It seems like null? Where in the docs can I find such info?

答:
get*Result() methods return an empty array()

getSingle*Result() methods throw a \Doctrine\ORM\NoResultException

Here are direct links to the doctrine API docs

getResult() doctrine API docs

getSingleResult() doctrine API docs

getSingleScalarResult() doctrine API docs

getOneOrNullResult() doctrine API docs

Also important exceptions:

NoResultException doctrine API docs

NonUniqueResultException  doctrine API docs
(must handle for getSingle*() and getOneOrNullResult() methods)

UnexpectedResultException  doctrine API docs (this is parent exception of the two above)

direct links are for 2.6, but you can find there more recent versions at the at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/index.html


问:
How to compare array of dates (Strings) with single date in swift 3
I have array of dates (strings) which are coming from local data base like following.

```<code>datesFromDBArray:["04/12/2017 07:10:41", "04/12/2017 07:12:17", "04/12/2017 07:13:54", "04/12/2017 07:17:45", "04/12/2017 07:18:56", "05/12/2017"]
</code>```

Here, same date can have multiple times.

Also from same data base, I am getting some other data called actions.

```<code>ActionsDBArray:["1", "6", "1", "1", "1", "2", "2", "2", "4", "1", "5", "2", "3"]
</code>```

these above two data getting from local database. And both arrays number of count is equal.

Now, I am getting number of dates from server response. That is like

```<code>TotalDaysServerArray:["22/11/2017 11:59:59", "23/11/2017 11:59:58", "24/11/2017 11:59:57"]
</code>```

Here, I am showing TotalDaysServerArray data in table view.

So, here, If user pressed on first cell like 22/11/2017 11:59:59, I need to check this date (not time, only same date) is existed in datesFromDBArray, if existed, then need to check how many indexes its existed, and need to fetch ActionsDBArray same indexes data.

So, I need to get the list of ActionsDBArray indexes and need to show the list of that in some other place.

I have tried some logic which was not worked, so, I am posting query here.

Can anyone suggest me, how to achieve this?

答:
```<code>let clickedStr = TotalDaysServerArray[indexPath.row]
let str =  clickedStr.components(separatedBy: " ").first
 for(index , value) in datesFromDBArray.enumerated() {
            if str == value.components(separatedBy: " ").first! {
                print(ActionsDBArray[index])
            }
       }
</code>```

Body:
I have array of dates (strings) which are coming from local data base like following.

datesFromDBArray:["04/12/2017 07:10:41", "04/12/2017 07:12:17", "04/12/2017 07:13:54", "04/12/2017 07:17:45", "04/12/2017 07:18:56", "05/12/2017"]

Here, same date can have multiple times.

Also from same data base, I am getting some other data called actions.

ActionsDBArray:["1", "6", "1", "1", "1", "2", "2", "2", "4", "1", "5", "2", "3"]

these above two data getting from local database. And both arrays number of count is equal.

Now, I am getting number of dates from server response. That is like

TotalDaysServerArray:["22/11/2017 11:59:59", "23/11/2017 11:59:58", "24/11/2017 11:59:57"]

Here, I am showing TotalDaysServerArray data in table view.

So, here, If user pressed on first cell like 22/11/2017 11:59:59, I need to check this date (not time, only same date) is existed in datesFromDBArray, if existed, then need to check how many indexes its existed, and need to fetch ActionsDBArray same indexes data.

So, I need to get the list of ActionsDBArray indexes and need to show the list of that in some other place.

I have tried some logic which was not worked, so, I am posting query here.

Can anyone suggest me, how to achieve this?


问:
Trying to create dynamic cascading selects from a single JSON array using jQuery
I am sure this has been done and I suspect I am just not searching for the correct terms so please don't blast me for asking something that has already been answered.

I have an array of item attributes (dynamic) and I want to drill down with select boxes to a final item.

```<code>var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved'
 }];
</code>```

UPDATED ARRAYS

```<code>var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-1.jpg'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-2.jpg'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-3.jpg'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-4.jpg'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved',
  'QoH': 3,
  'image': '101001506-5.jpg'
 }];

var formFields =  [
  {'name':'itemAt1',
   'label': 'Size',
   'fieldOpts': ['sm','med','lg','xl']
  },
  {'name':'itemAt2',
   'label': 'Color',
   'fieldOpts': ['blue','white','black']
  },
  {'name':'itemAt3',
   'label': 'Style',
   'fieldOpts': ['short sleeve','long sleeve']
  }
 ];
</code>```

I have three dynamically generated select boxes:

UPDATED TO REFLECT INITIAL OPTIONS IN ALL SELECT BOXES

```<code> <form>
  <label>Size</label>
  <select name="attribute1" id="id_attribute1">
   <option value="">Select Size</option>
   <option value="sm">sm</option>
   <option value="md">md</option>
   <option value="lg">lg</option>
  </select>

  <label>Color</label>
  <select name="attribute2" id="id_attribute2">
   <option value="">Select Color</option>
   <option value="blue">blue</option>
   <option value="white">white</option>
  </select>

  <label>Style</label>
  <select name="attribute3" id="id_attribute3">
   <option value="">Select Style</option>
   <option value="short sleeve">short sleeve</option>
   <option value="long sleeve">long sleeve</option>
  </select>
 </form>
</code>```

When a user selects the size, I want to query the array and return the available colors. When the user selects style, I want to return the itemAtID.

This is a very simplified representation of what I am trying to accomplish, but if I can make this work, I can scale it up to suit my purpose. I am sure there has to be a plugin for this but I have not been able to find one that doesn't require AJAX which puts an unnecessary load on the server as the data has already been passed in the original array of objects.

UPDATE
I have realize that I need to refine my original plan a little to make it more useable. The user should be able to select any of the select boxes first and the options for the remaining unselected boxes should be updated as enabled or disabled based on either their existence or the QoH (quantity on hand). Options that don't exist in the JSONarray (like the black color) should not appear, but options that exist but not in the selected size/color/style or with a 0 QoH should be disabled.

When selections for all boxes have been made, the JSONarray should be queried for the itemAtID matching those options and a hidden field (itemAtID) should be updated and the submit button should be enabled.

So my plan is to use a class based onChange to trigger the function.

Create empty array (formSelects).

Loop through the formFields array and 1)enable or disable options based on the the current field selection and 2)when a selection exists, push it to the formSelects array.

If the formSelects.length equals the formFields.length, search the JSONarray for the row that matches the criteria and update the hidden itemAtID field and enable the submit button (and eventually update the image).

I think that will address my problems. If anyone sees any flaws in this plan, please let me know. I am not very fluent in jQuery so it would be nice to find out my plan won't work before I spend the next day trying to sort out the proper syntax.

UPDATE: just realize the first flaw. I have to figure out a way to deal with resetting the form so you don't get pigeon holed by your selections...in other words, if you style selection disables a size or color you would rather have, you would be stuck...not sure how to handle that.

Thanks for your help and your patience with my shifting plan.

答:
You can use this code,

```<code>//Populate Colors based on Size Selected
$('#id_attribute1').on('change',function(){
$("#id_attribute2").empty();
$("#id_attribute2").append('<option value="">please select color</option>');
for(var i = 0 ; i < JSONarray.length ; i++)
   {
      if(JSONarray[i]['attribute1'] == this.value)
         {
             $("#id_attribute2").append('<option value="'+JSONarray[i]['attribute2']+'">'+JSONarray[i]['attribute2']+'</option>');
         }
    }
});

//Populate Style based on Color Selected
$('#id_attribute2').on('change',function(){
$("#id_attribute3").empty();
$("#id_attribute3").append('<option value="">please select style</option>');
for(var i = 0 ; i < JSONarray.length ; i++)
   {
       if(JSONarray[i]['attribute2'] == this.value)
          {
              $("#id_attribute3").append('<option value="'+JSONarray[i]['itemAtID']+'">'+JSONarray[i]['attribute3']+'</option>');
          }
   }
});

//Return ItemAtID base on Style selected
$('#id_attribute3').on('change',function(){
    alert(this.value);
});
</code>```

Above is the straight forward way. You can reduce the code as follows,

```<code>//All Change event handled by single function
$('#id_attribute1,#id_attribute2,#id_attribute3').on('change',function(){
var id = this.id.substr("id_attribute".length); // id will give 1 or 2 or 3 that can be used to identify the select boxes
//id = 3 for the #id_attribute3
if(id == 3)
{
    alert(this.value);
}
else
{
    var newid = parseInt(id) + 1;
    //Find the select box to populate
    var $newattrid = $("#id_attribute"+ newid);
    var attribute = 'attribute'+ newid;
    $newattrid.empty();
    //id = 1 for the #id_attribute1
    if(id == 1)
    {
        $newattrid.append('<option value="" class="select">please select color</option>');
    }
    //For the #id_attribute2
    else
    {
        $newattrid.append('<option value="">please select style</option>');
    }

    for(var i = 0 ; i < JSONarray.length ; i++)
    {
         if(JSONarray[i]['attribute'+id] == this.value)
         {
             if(id == 1)
             {
                  $newattrid.append('<option value="'+JSONarray[i][attribute]+'">'+JSONarray[i][attribute]+'</option>');
             }
             else
             {
                  $newattrid.append('<option value="'+JSONarray[i]['itemAtID']+'">'+JSONarray[i][attribute]+'</option>');
             }
          }
     }
}
});
</code>```

Body:
I am sure this has been done and I suspect I am just not searching for the correct terms so please don't blast me for asking something that has already been answered.

I have an array of item attributes (dynamic) and I want to drill down with select boxes to a final item.

var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved'
 }];

UPDATED ARRAYS

var JSONarray = [
 {'itemAtID':1,
  'attribute1':'sm',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-1.jpg'
 },
 {'itemAtID':2,
  'attribute1':'med',
  'attribute2':'blue',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-2.jpg'
 },
 {'itemAtID':3,
  'attribute1':'lg',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-3.jpg'
 },
 {'itemAtID':4,
  'attribute1':'med',
  'attribute2':'white',
  'attribute3':'short sleeved',
  'QoH': 3,
  'image': '101001506-4.jpg'
 },
 {'itemAtID':5,
  'attribute1':'lg',
  'attribute2':'blue',
  'attribute3':'long sleeved',
  'QoH': 3,
  'image': '101001506-5.jpg'
 }];

var formFields =  [
  {'name':'itemAt1',
   'label': 'Size',
   'fieldOpts': ['sm','med','lg','xl']
  },
  {'name':'itemAt2',
   'label': 'Color',
   'fieldOpts': ['blue','white','black']
  },
  {'name':'itemAt3',
   'label': 'Style',
   'fieldOpts': ['short sleeve','long sleeve']
  }
 ];

I have three dynamically generated select boxes:

UPDATED TO REFLECT INITIAL OPTIONS IN ALL SELECT BOXES

 <form>
  Size
  <select name="attribute1" id="id_attribute1">
   <option value="">Select Size</option>
   <option value="sm">sm</option>
   <option value="md">md</option>
   <option value="lg">lg</option>
  </select>

  Color
  <select name="attribute2" id="id_attribute2">
   <option value="">Select Color</option>
   <option value="blue">blue</option>
   <option value="white">white</option>
  </select>

  Style
  <select name="attribute3" id="id_attribute3">
   <option value="">Select Style</option>
   <option value="short sleeve">short sleeve</option>
   <option value="long sleeve">long sleeve</option>
  </select>
 </form>

When a user selects the size, I want to query the array and return the available colors. When the user selects style, I want to return the itemAtID.

This is a very simplified representation of what I am trying to accomplish, but if I can make this work, I can scale it up to suit my purpose. I am sure there has to be a plugin for this but I have not been able to find one that doesn't require AJAX which puts an unnecessary load on the server as the data has already been passed in the original array of objects.

UPDATE
I have realize that I need to refine my original plan a little to make it more useable. The user should be able to select any of the select boxes first and the options for the remaining unselected boxes should be updated as enabled or disabled based on either their existence or the QoH (quantity on hand). Options that don't exist in the JSONarray (like the black color) should not appear, but options that exist but not in the selected size/color/style or with a 0 QoH should be disabled.

When selections for all boxes have been made, the JSONarray should be queried for the itemAtID matching those options and a hidden field (itemAtID) should be updated and the submit button should be enabled.

So my plan is to use a class based onChange to trigger the function.

Create empty array (formSelects).

Loop through the formFields array and 1)enable or disable options based on the the current field selection and 2)when a selection exists, push it to the formSelects array.

If the formSelects.length equals the formFields.length, search the JSONarray for the row that matches the criteria and update the hidden itemAtID field and enable the submit button (and eventually update the image).

I think that will address my problems. If anyone sees any flaws in this plan, please let me know. I am not very fluent in jQuery so it would be nice to find out my plan won't work before I spend the next day trying to sort out the proper syntax.

UPDATE: just realize the first flaw. I have to figure out a way to deal with resetting the form so you don't get pigeon holed by your selections...in other words, if you style selection disables a size or color you would rather have, you would be stuck...not sure how to handle that.

Thanks for your help and your patience with my shifting plan.

Body:
You can use this code,

//Populate Colors based on Size Selected
$('#id_attribute1').on('change',function(){
$("#id_attribute2").empty();
$("#id_attribute2").append('<option value="">please select color</option>');
for(var i = 0 ; i < JSONarray.length ; i++)
   {
      if(JSONarray[i]['attribute1'] == this.value)
         {
             $("#id_attribute2").append('<option value="'+JSONarray[i]['attribute2']+'">'+JSONarray[i]['attribute2']+'</option>');
         }
    }
});

//Populate Style based on Color Selected
$('#id_attribute2').on('change',function(){
$("#id_attribute3").empty();
$("#id_attribute3").append('<option value="">please select style</option>');
for(var i = 0 ; i < JSONarray.length ; i++)
   {
       if(JSONarray[i]['attribute2'] == this.value)
          {
              $("#id_attribute3").append('<option value="'+JSONarray[i]['itemAtID']+'">'+JSONarray[i]['attribute3']+'</option>');
          }
   }
});

//Return ItemAtID base on Style selected
$('#id_attribute3').on('change',function(){
    alert(this.value);
});

Above is the straight forward way. You can reduce the code as follows,

//All Change event handled by single function
$('#id_attribute1,#id_attribute2,#id_attribute3').on('change',function(){
var id = this.id.substr("id_attribute".length); // id will give 1 or 2 or 3 that can be used to identify the select boxes
//id = 3 for the #id_attribute3
if(id == 3)
{
    alert(this.value);
}
else
{
    var newid = parseInt(id) + 1;
    //Find the select box to populate
    var $newattrid = $("#id_attribute"+ newid);
    var attribute = 'attribute'+ newid;
    $newattrid.empty();
    //id = 1 for the #id_attribute1
    if(id == 1)
    {
        $newattrid.append('<option value="" class="select">please select color</option>');
    }
    //For the #id_attribute2
    else
    {
        $newattrid.append('<option value="">please select style</option>');
    }

    for(var i = 0 ; i < JSONarray.length ; i++)
    {
         if(JSONarray[i]['attribute'+id] == this.value)
         {
             if(id == 1)
             {
                  $newattrid.append('<option value="'+JSONarray[i][attribute]+'">'+JSONarray[i][attribute]+'</option>');
             }
             else
             {
                  $newattrid.append('<option value="'+JSONarray[i]['itemAtID']+'">'+JSONarray[i][attribute]+'</option>');
             }
          }
     }
}
});


问:
DatePicker not working on bootstrap 4
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.</p>

```<code><!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <!-- datepicker -->
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
    $(function() {
      $("#datepicker").datepicker();
    });
  </script>
</head>

<body>
  <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>
    <a class="navbar-brand" href="#">Menu</a>
    <div class="collapse navbar-collapse" id="navbarsExampleDefault">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Management</a>
          <div class="dropdown-menu" aria-labelledby="dropdown01">
            <a class="dropdown-item" href="dashboard.php?act=create_program">Create Program</a>
            <a class="dropdown-item" href="dashboard.php?act=view_program">View Program</a>
          </div>
        </li>
      </ul>
    </div>
  </nav>
  <div class="container-fluid">
    <div class="row">
      <div class="col-md-4"></div>
      <div class="col-md-4">
        <!-- Datepicker -->
        Date: <input type="text" id="datepicker">
      </div>
      <div class="col-md-4"></div>
    </div>
  </div>
  <!-- jQuery first, then Tether, then Bootstrap JS. -->
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
</body>

</html>
</code>```

答:
I think you should add the ' popper.js ' file too as Bootstrap 4 popup elements are dependent on popperjs.

Popper.js

Title: DatePicker not working on bootstrap 4

Body:
I want to used datepicker on my project.This is my first time using bootstrap.The problem is that datepicker not displayed when i click the date form.I already try replace CDN url position inside  and inside  tag and still not worked.I dont know what mistake that i make,hope you guys can help me with this problem thank you.

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">

      </button>
    Menu

          Management

            Create Program
            View Program

        Date: <input type="text" id="datepicker">


问:
How to retrieve sent box items from node-imap or node-inbox module
Here is my code but its not working for sent message folder. I have tried using node-imap and node-inbox and node-maillistner2 module but none of them were able to retrieve the sent message box. I am using ymail account and imap server.</p>

```<code>  var inbox = require("inbox");

  console.log(mailLogin);
  var client = inbox.createConnection(false, mailLogin.imapserver, {
    secureConnection: mailLogin.isTlsEnabled,
    auth: {
      user: mailLogin.email,
      pass: mailLogin.password
    }
  });

  client.connect();
  client.listMailboxes({all:true}, function (error, info) {
    console.log(info)
  })

  client.on("connect", function () {
    client.openMailbox("INBOX/SENT", function (error, info) {
      if (error) throw error;

      client.listMessages(-10, function (err, messages) {
        messages.forEach(function (message) {
          console.log(message.UID + ": " + message.title);
        });
      });

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

答:
You can use mail-listner2 lib for the same, below is the code snippet for reading inbox messages, the same would work with send box too, replace INBOX with SENT. Let me know the progress.</p>

```<code> emailbody(userid, password) {

        var deferred = protractor.promise.defer();

        var MailListener = require("mail-listener2");
        var mailListener = new MailListener({
            username: userid,
            password: password,
            host: "imap.gmail.com",
            //host: "imap.gmx.com",
            port: 993, // imap port
            tls: true,
            connTimeout: 25000, // Default by node-imap
            authTimeout: 10000, // Default by node-imap,
            debug: console.log, // Or your custom function with only one incoming argument. Default: null
            tlsOptions: { rejectUnauthorized: false },
            mailbox: "INBOX", // mailbox to monitor
            searchFilter: ["UNSEEN"], // the search filter being used after an IDLE notification has been retrieved
            markSeen: true, // all fetched email willbe marked as seen and not fetched next time
            fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
            mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib.
            attachments: true, // download attachments as they are encountered to the project directory
            attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments

        });

        global.mailListener = mailListener;

        mailListener.start();

        mailListener.on("mail", function (mail, seqno, attributes) {
            console.log('email received!');
            global.mailListener.stop();
            deferred.fulfill(mail);
        });

        mailListener.on("error", function (err) {
            console.log('Email reading error');
            global.mailListener.stop();
            deferred.reject(err);
        });
    return deferred.promise;

}
</code>```

Body:
Here is my code but its not working for sent message folder. I have tried using node-imap and node-inbox and node-maillistner2 module but none of them were able to retrieve the sent message box. I am using ymail account and imap server.

  var inbox = require("inbox");

  console.log(mailLogin);
  var client = inbox.createConnection(false, mailLogin.imapserver, {
    secureConnection: mailLogin.isTlsEnabled,
    auth: {
      user: mailLogin.email,
      pass: mailLogin.password
    }
  });

  client.connect();
  client.listMailboxes({all:true}, function (error, info) {
    console.log(info)
  })

  client.on("connect", function () {
    client.openMailbox("INBOX/SENT", function (error, info) {
      if (error) throw error;

      client.listMessages(-10, function (err, messages) {
        messages.forEach(function (message) {
          console.log(message.UID + ": " + message.title);
        });
      });

    });
  });

Body:
You can use mail-listner2 lib for the same, below is the code snippet for reading inbox messages, the same would work with send box too, replace INBOX with SENT. Let me know the progress.

 emailbody(userid, password) {

        var deferred = protractor.promise.defer();

        var MailListener = require("mail-listener2");
        var mailListener = new MailListener({
            username: userid,
            password: password,
            host: "imap.gmail.com",
            //host: "imap.gmx.com",
            port: 993, // imap port
            tls: true,
            connTimeout: 25000, // Default by node-imap
            authTimeout: 10000, // Default by node-imap,
            debug: console.log, // Or your custom function with only one incoming argument. Default: null
            tlsOptions: { rejectUnauthorized: false },
            mailbox: "INBOX", // mailbox to monitor
            searchFilter: ["UNSEEN"], // the search filter being used after an IDLE notification has been retrieved
            markSeen: true, // all fetched email willbe marked as seen and not fetched next time
            fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
            mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib.
            attachments: true, // download attachments as they are encountered to the project directory
            attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments

        });

        global.mailListener = mailListener;

        mailListener.start();

        mailListener.on("mail", function (mail, seqno, attributes) {
            console.log('email received!');
            global.mailListener.stop();
            deferred.fulfill(mail);
        });

        mailListener.on("error", function (err) {
            console.log('Email reading error');
            global.mailListener.stop();
            deferred.reject(err);
        });
    return deferred.promise;

}


问:
WCF (SOAP):Protecting single operations with custom UserName validator - similar to what WcfRestContrib offers but for soap?
I was hoping to be able to protect my WCF services on an operation level not service level.

Hence some methods are protected and others not. I know there is an attribute called PrincipalPermission but this works with Windows

I was hoping something existed for WCF Soap like it does for WCF Rest in this contrib project. WcfRestContrib

This extra project allows the use of a custom username and password validator and allow it only to protect certain methods by decorating the methods with an attribute

Is this possible with WCF (soap)?

Thanks in advance

答:
Yes, it is possible to do operation level authorization checks with SOAP in WCF, but you'll need to do claims based authorization (as far as I know). That's what my team does for our product.

The hook point in WCF is to implement a custom ServiceAuthorizationManger

ServiceAuthorizationManager.CheckAccessCore Method

How to: Create a Custom Authorization Manager for a Service

and plug that into your service behaviour:

```<code><behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceAuthorization serviceAuthorizationManagerType="MyServiceAuthorizationManager" />
    </behavior>
  </serviceBehaviors>
</code>```

When you implement your authorization manager, override CheckAccessCore, and then simply return true/false is they are authorized or not.

Body:
Yes, it is possible to do operation level authorization checks with SOAP in WCF, but you'll need to do claims based authorization (as far as I know). That's what my team does for our product.

The hook point in WCF is to implement a custom ServiceAuthorizationManger

ServiceAuthorizationManager.CheckAccessCore Method

How to: Create a Custom Authorization Manager for a Service

and plug that into your service behaviour:

<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceAuthorization serviceAuthorizationManagerType="MyServiceAuthorizationManager" />
    </behavior>
  </serviceBehaviors>

When you implement your authorization manager, override CheckAccessCore, and then simply return true/false is they are authorized or not.


问:
Php error in code while updating the data in sql
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

```<code> <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>
</code>```

The HTML code is:

```<code>  <html>
    <head>
        <title>Edit Data</title>
    </head>

    <body>
        <a href="index.php">Home</a>
        <br/><br/>

        <form name="form1" method="post" action="update.php">
            <table border="0">
                <tr>
                    <td>Name</td>
                    <td><input type="text" name="name" value="<?php echo $name;?>"></td>
                </tr>
                <tr>
                    <td>address</td>
                    <td><input type="text" name="address" value="<?php echo $address;?>"></td>
                </tr>

                <tr>
                   <td><input type="hidden" name="id" value="<?php echo $_GET['id'];?>"></td>
                    <td><input type="submit" name="update" value="Update"></td>
                </tr>
            </table>
        </form>
    </body>
    </html>
</code>```

答:
I got the issue, So I am posting a separate answer here again:

You need to update few things,

```<code><?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_GET['update'])){  // Checking if the query parameter is available.
     $id=$_GET['update'];    // Getting the query string value here.
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='".$name."',address='".$address."' WHERE id='".$id."'";  // Added `""` here for all variables.
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>
</code>```

Notice in the above code that you are getting query result in $row variable. So use that in HTML as well. Like this:

```<code><html>
<head>
    <title>Edit Data</title>
</head>

<body>
    <a href="index.php">Home</a>
    <br/><br/>

    <form name="form1" method="post" action="update.php">
        <table border="0">
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" value="<?php echo (isset($row['name']))? $row['name'] : ''?>"></td>
            </tr>
            <tr>
                <td>address</td>
                <td><input type="text" name="address" value="<?php echo (isset($row['address']))? $row['address'] : ''?>"></td>
            </tr>

            <tr>
               <td><input type="hidden" name="id" value="<?php echo (isset($_GET['id']))? $_GET['id'] : ''?>"></td>
                <td><input type="submit" name="update" value="Update"></td>
            </tr>
        </table>
    </form>
</body>
</html>
</code>```

Body:
I get an error Undefined variable name, address, and id though I have defined it. I have used isset function but it is not working. Also, some HTML code appears in the name and address field.

 <?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_POST['update'])){
     $id=$_POST['id'];
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='$name',address='$address' WHERE id='$id'";
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>

The HTML code is:

        <title>Edit Data</title>

        Home

        <form name="form1" method="post" action="update.php">

                    Name
                    <input type="text" name="name" value="<?php echo $name;?>">

                    address
                    <input type="text" name="address" value="<?php echo $address;?>">

                   <input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
                    <input type="submit" name="update" value="Update">

        </form>

Body:
I got the issue, So I am posting a separate answer here again:

You need to update few things,

<?php
$link=mysqli_connect("localhost","root","");
$select=mysqli_select_db($link,'first_db');

if(isset($_GET['update'])){  // Checking if the query parameter is available.
     $id=$_GET['update'];    // Getting the query string value here.
     $query="SELECT * FROM list WHERE id='$id'";
     $run=mysqli_query($link,$query);
     $row=mysqli_fetch_array($run);
 }
if(isset($_POST['name'])&& isset($_POST['address'])){
    $name=$_POST['name'];
    $address=$_POST['address'];
    $id = $_POST['id'];
    $query="UPDATE list SET name='".$name."',address='".$address."' WHERE id='".$id."'";  // Added `""` here for all variables.
    $result=mysqli_query($link,$query);
}
else{
    echo"The fields cannot be empty";
}

?>

Notice in the above code that you are getting query result in $row variable. So use that in HTML as well. Like this:

<html>
<head>
    <title>Edit Data</title>
</head>

<body>
    <a href="index.php">Home</a>
    <br/><br/>

    <form name="form1" method="post" action="update.php">
        <table border="0">
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" value="<?php echo (isset($row['name']))? $row['name'] : ''?>"></td>
            </tr>
            <tr>
                <td>address</td>
                <td><input type="text" name="address" value="<?php echo (isset($row['address']))? $row['address'] : ''?>"></td>
            </tr>

            <tr>
               <td><input type="hidden" name="id" value="<?php echo (isset($_GET['id']))? $_GET['id'] : ''?>"></td>
                <td><input type="submit" name="update" value="Update"></td>
            </tr>
        </table>
    </form>
</body>
</html>


问:
Making element border meet browser window on browser resize
As I shrink the browser screen, how can I make an element's border smoothly meet the edges of the window while text remains 15px away from the sides?

I have the following HTML:

```<code><section>
 <header>
  <h1>Header Text</h1>
 </header>
</section>
</code>```

In desktop view, it looks like this:

The section has a max-width of 1000px, and it is centered with margin-left and margin-right set to auto. Furthermore, the header is width:100% (as is by default) and it has a border-top:1px solid black;.

In mobile view, the header looks like this:

So the header with the border on the top touches against the edge of the screen, but the h1 inside has 15px of padding on the left and right.

My question is: when the screen shrinks from 1030px to 1000px, how do I make it so that the h1 content always stays 15px away from the edge of the screen, but the border meets the edge of the screen?

body{padding:0;margin:0;}
section{max-width:1000px;margin:0 auto;}
header{border-top:1px solid black}
@media(max-width:1000px){
  h1{padding:0 15px;}
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
 <header>
  <h1>Header Text</h1>
 </header>
</section></code>```

答:
You'll need to position your h1 element absolutely using a media query:

```<code>body{padding:0;margin:0;}
section{max-width:1000px;margin:10px auto;}
header{border-top:1px solid black}

@media (max-width: 1030px) {
  h1{position: absolute; left: 15px}
}
</code>```

Here is the solution shown on CodePen.

Body:
As I shrink the browser screen, how can I make an element's border smoothly meet the edges of the window while text remains 15px away from the sides?

I have the following HTML:

Header Text

In desktop view, it looks like this:

The section has a max-width of 1000px, and it is centered with margin-left and margin-right set to auto. Furthermore, the header is width:100% (as is by default) and it has a border-top:1px solid black;.

In mobile view, the header looks like this:

So the header with the border on the top touches against the edge of the screen, but the h1 inside has 15px of padding on the left and right.

My question is: when the screen shrinks from 1030px to 1000px, how do I make it so that the h1 content always stays 15px away from the edge of the screen, but the border meets the edge of the screen?

body{padding:0;margin:0;}
section{max-width:1000px;margin:0 auto;}
header{border-top:1px solid black}
@media(max-width:1000px){
  h1{padding:0 15px;}
}

Header Text

Body:
You'll need to position your h1 element absolutely using a media query:

body{padding:0;margin:0;}
section{max-width:1000px;margin:10px auto;}
header{border-top:1px solid black}

@media (max-width: 1030px) {
  h1{position: absolute; left: 15px}
}

Here is the solution shown on CodePen.