问:
VBA "kill file" not working on first run, but on all following runs
I've run into a rather weird error on two VBA Scripts I wrote and can't quite put my finger on where the issue might lie exactly...

It's about two VBA Macros which handle the same functionality, one for Word and one for Excel.
What the macros do is parsing some information into a temporary .txt file which is created as such:

```<code>Dim Appl
Set Appl = CreateObject("WScript.Shell").Exec("cmd.exe /k im viewissue " & issue & " > " & "D:\temp" & issue & ".txt")
Appl.Terminate
</code>```

Subsequently some information is extracted from the .txt file and written into the Excel/ Word files resprectively.

EDIT: As so:

```<code>Set FileNum = CreateObject("Scripting.FileSystemObject").OpenTextFile("D:\temp" & issue & ".txt", 1)
   'Read some lines and write them into the Word/Excel files...
FileNum.Close
</code>```

end of Edit.

After the macro is done with the file it deletes it:

```<code>Kill "D:\temp" & issue & ".txt"
</code>```

Everything works without any problems: File is created, information extraction works, file is removed... EXCEPT on the first time you try to run it.

The first time you try to run it (on a freshly started up machine) you get a "Runtime Error 70: Access denied" connected to the line with the kill command.
If you just cancel the error message window and try again, it works fine.

I've checked the following:

.txt file is created (even on first run)

permissions are set correctly so as to be able to delete it manually without a problem

same problem on both the Word and Excel macros after startup

running the script on Word (with the error message) eliminates the problem on the first run of the Excel script and vice versa (even though the stranded .txt file has been removed after the missed attempt)

I really don't know what the problem might be... Don't quite see the difference between the first run and the subsequent ones.

Any kind of hint is much appreciated.
Cheers.

EDIT: On another note I've managed to rule out the possibility, that the FileSystemObject is the source of the problem, since I get the same issue when running the script without actually doing anything with the file.

答: Working on the assumption that MS Office's internal processes aren't done with the file you want to kill at the time you want to delete it, the easiest method should be to delay the deleting until some other time, for example, Before_Close. Another obvious time to kill the file would be before you use it again, but that would be counter-intuitive because when the name is reused the existing file would be over-written. I mean to point out that there isn't such a terrible rush to delete the file, and the MS engineers who designed their program not to let go of it promptly may have considered that fact.</p>

Body:
I've run into a rather weird error on two VBA Scripts I wrote and can't quite put my finger on where the issue might lie exactly...

It's about two VBA Macros which handle the same functionality, one for Word and one for Excel.
What the macros do is parsing some information into a temporary .txt file which is created as such:

Dim Appl
Set Appl = CreateObject("WScript.Shell").Exec("cmd.exe /k im viewissue " & issue & " > " & "D:\temp" & issue & ".txt")
Appl.Terminate

Subsequently some information is extracted from the .txt file and written into the Excel/ Word files resprectively.

EDIT: As so:

Set FileNum = CreateObject("Scripting.FileSystemObject").OpenTextFile("D:\temp" & issue & ".txt", 1)
   'Read some lines and write them into the Word/Excel files...
FileNum.Close

end of Edit.

After the macro is done with the file it deletes it:

Kill "D:\temp" & issue & ".txt"

Everything works without any problems: File is created, information extraction works, file is removed... EXCEPT on the first time you try to run it.

The first time you try to run it (on a freshly started up machine) you get a "Runtime Error 70: Access denied" connected to the line with the kill command.
If you just cancel the error message window and try again, it works fine.

I've checked the following:

.txt file is created (even on first run)

permissions are set correctly so as to be able to delete it manually without a problem

same problem on both the Word and Excel macros after startup

running the script on Word (with the error message) eliminates the problem on the first run of the Excel script and vice versa (even though the stranded .txt file has been removed after the missed attempt)

I really don't know what the problem might be... Don't quite see the difference between the first run and the subsequent ones.

Any kind of hint is much appreciated.
Cheers.

EDIT: On another note I've managed to rule out the possibility, that the FileSystemObject is the source of the problem, since I get the same issue when running the script without actually doing anything with the file.


来源: stackexchange

问:
Laravel - check if Ajax request
I have been trying to find a way to determine Ajax calls in Laravel but I have not found any documentation about it.

I have an index() controller function where I want to handle the response differently based on the nature of the request. Basically this is a resource controller method that is bound to GET request.

public function index()
{
    if(!$this->isLogin())
        return Redirect::to('login');

    if(isAjax()) // This is what I am needing.
    {
        return $JSON;
    }

    $data = array(
        'records' => $this->table->fetchAll()
    );

    $this->setLayout(compact('data'));
}
```
<p>I know the other methods of determining the Ajax request in PHP but I want something specific to Laravel.</p>
<p>Thanks</p>
<p><strong>Updated:</strong></p>
<p>I tried using</p>
<pre class="lang-php prettyprint-override"><code>if(Request::ajax())
{
    echo 'Ajax';
}
</code>```

But I am receiving this error:

Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context

The class shows that this is not a static method.

答: Sometimes Request::ajax() doesn't work, then use \Request::ajax()

ContentLicense: CC BY-SA 4.0

Title: Laravel - check if Ajax request

Body:
I have been trying to find a way to determine Ajax calls in Laravel but I have not found any documentation about it.

I have an index() controller function where I want to handle the response differently based on the nature of the request. Basically this is a resource controller method that is bound to GET request.

public function index()
{
    if(!$this->isLogin())
        return Redirect::to('login');

    if(isAjax()) // This is what I am needing.
    {
        return $JSON;
    }

    $data = array(
        'records' => $this->table->fetchAll()
    );

    $this->setLayout(compact('data'));
}

I know the other methods of determining the Ajax request in PHP but I want something specific to Laravel.

Thanks

Updated:

I tried using

if(Request::ajax())
{
    echo 'Ajax';
}

But I am receiving this error:

Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context

The class shows that this is not a static method.

ContentLicense: CC BY-SA 3.0


问:
Differentiating text keycode from control keycode in Android KeyEvent
There are 284 KeyEvent key codes. Some of them represent Unicode characters (like KEYCODE_A and KEYCODE_1), while others represent control characters (like KEYCODE_DEL).

I am making a custom view that handles keyboard input. It gets most of its input from an Input Connection, but sometimes keyboards send key codes (normall associated with hard keyboard input). I need to handle that, too. Do I need to exhaustively handle every control key code and then convert the rest to text (with (char) event.getUnicodeChar()) or is there a built in way to differentiate the text codes from the control codes?

答:
The KeyEvent.getUnicodeChar() documentation says

Returns 0 if the key is not one that is used to type Unicode characters.

Thus it is easy to differentiate text codes from control codes like this:

```<code>if (keyEvent.getUnicodeChar() != 0) {
    // unicode text
    char unicodeChar = (char) keyEvent.getUnicodeChar();
} else {
    // control char
}
</code>```

Here is a list that helped me reach this conclution:

```<code>// keyCode, Unicode, char, keyCode name

0   0   ��  KEYCODE_UNKNOWN
1   0   ��  KEYCODE_SOFT_LEFT
2   0   ��  KEYCODE_SOFT_RIGHT
3   0   ��  KEYCODE_HOME
4   0   ��  KEYCODE_BACK
5   0   ��  KEYCODE_CALL
6   0   ��  KEYCODE_ENDCALL
7   48  0   KEYCODE_0
8   49  1   KEYCODE_1
9   50  2   KEYCODE_2
10  51  3   KEYCODE_3
11  52  4   KEYCODE_4
12  53  5   KEYCODE_5
13  54  6   KEYCODE_6
14  55  7   KEYCODE_7
15  56  8   KEYCODE_8
16  57  9   KEYCODE_9
17  42  *   KEYCODE_STAR
18  35  #   KEYCODE_POUND
19  0   ��  KEYCODE_DPAD_UP
20  0   ��  KEYCODE_DPAD_DOWN
21  0   ��  KEYCODE_DPAD_LEFT
22  0   ��  KEYCODE_DPAD_RIGHT
23  0   ��  KEYCODE_DPAD_CENTER
24  0   ��  KEYCODE_VOLUME_UP
25  0   ��  KEYCODE_VOLUME_DOWN
26  0   ��  KEYCODE_POWER
27  0   ��  KEYCODE_CAMERA
28  0   ��  KEYCODE_CLEAR
29  97  a   KEYCODE_A
30  98  b   KEYCODE_B
31  99  c   KEYCODE_C
32  100 d   KEYCODE_D
33  101 e   KEYCODE_E
34  102 f   KEYCODE_F
35  103 g   KEYCODE_G
36  104 h   KEYCODE_H
37  105 i   KEYCODE_I
38  106 j   KEYCODE_J
39  107 k   KEYCODE_K
40  108 l   KEYCODE_L
41  109 m   KEYCODE_M
42  110 n   KEYCODE_N
43  111 o   KEYCODE_O
44  112 p   KEYCODE_P
45  113 q   KEYCODE_Q
46  114 r   KEYCODE_R
47  115 s   KEYCODE_S
48  116 t   KEYCODE_T
49  117 u   KEYCODE_U
50  118 v   KEYCODE_V
51  119 w   KEYCODE_W
52  120 x   KEYCODE_X
53  121 y   KEYCODE_Y
54  122 z   KEYCODE_Z
55  44  ,   KEYCODE_COMMA
56  46  .   KEYCODE_PERIOD
57  0   ��  KEYCODE_ALT_LEFT
58  0   ��  KEYCODE_ALT_RIGHT
59  0   ��  KEYCODE_SHIFT_LEFT
60  0   ��  KEYCODE_SHIFT_RIGHT
61  9       KEYCODE_TAB
62  32      KEYCODE_SPACE
63  0   ��  KEYCODE_SYM
64  0   ��  KEYCODE_EXPLORER
65  0   ��  KEYCODE_ENVELOPE
66  10      KEYCODE_ENTER
67  0   ��  KEYCODE_DEL
68  96  `   KEYCODE_GRAVE
69  45  -   KEYCODE_MINUS
70  61  =   KEYCODE_EQUALS
71  91  [   KEYCODE_LEFT_BRACKET
72  93  ]   KEYCODE_RIGHT_BRACKET
73  92  \   KEYCODE_BACKSLASH
74  59  ;   KEYCODE_SEMICOLON
75  39  '   KEYCODE_APOSTROPHE
76  47  /   KEYCODE_SLASH
77  64  @   KEYCODE_AT
78  0   ��  KEYCODE_NUM
79  0   ��  KEYCODE_HEADSETHOOK
80  0   ��  KEYCODE_FOCUS
81  43  +   KEYCODE_PLUS
82  0   ��  KEYCODE_MENU
83  0   ��  KEYCODE_NOTIFICATION
84  0   ��  KEYCODE_SEARCH
85  0   ��  KEYCODE_MEDIA_PLAY_PAUSE
86  0   ��  KEYCODE_MEDIA_STOP
87  0   ��  KEYCODE_MEDIA_NEXT
88  0   ��  KEYCODE_MEDIA_PREVIOUS
89  0   ��  KEYCODE_MEDIA_REWIND
90  0   ��  KEYCODE_MEDIA_FAST_FORWARD
91  0   ��  KEYCODE_MUTE
92  0   ��  KEYCODE_PAGE_UP
93  0   ��  KEYCODE_PAGE_DOWN
94  0   ��  KEYCODE_PICTSYMBOLS
95  0   ��  KEYCODE_SWITCH_CHARSET
96  0   ��  KEYCODE_BUTTON_A
97  0   ��  KEYCODE_BUTTON_B
98  0   ��  KEYCODE_BUTTON_C
99  0   ��  KEYCODE_BUTTON_X
100 0   ��  KEYCODE_BUTTON_Y
101 0   ��  KEYCODE_BUTTON_Z
102 0   ��  KEYCODE_BUTTON_L1
103 0   ��  KEYCODE_BUTTON_R1
104 0   ��  KEYCODE_BUTTON_L2
105 0   ��  KEYCODE_BUTTON_R2
106 0   ��  KEYCODE_BUTTON_THUMBL
107 0   ��  KEYCODE_BUTTON_THUMBR
108 0   ��  KEYCODE_BUTTON_START
109 0   ��  KEYCODE_BUTTON_SELECT
110 0   ��  KEYCODE_BUTTON_MODE
111 0   ��  KEYCODE_ESCAPE
112 0   ��  KEYCODE_FORWARD_DEL
113 0   ��  KEYCODE_CTRL_LEFT
114 0   ��  KEYCODE_CTRL_RIGHT
115 0   ��  KEYCODE_CAPS_LOCK
116 0   ��  KEYCODE_SCROLL_LOCK
117 0   ��  KEYCODE_META_LEFT
118 0   ��  KEYCODE_META_RIGHT
119 0   ��  KEYCODE_FUNCTION
120 0   ��  KEYCODE_SYSRQ
121 0   ��  KEYCODE_BREAK
122 0   ��  KEYCODE_MOVE_HOME
123 0   ��  KEYCODE_MOVE_END
124 0   ��  KEYCODE_INSERT
125 0   ��  KEYCODE_FORWARD
126 0   ��  KEYCODE_MEDIA_PLAY
127 0   ��  KEYCODE_MEDIA_PAUSE
128 0   ��  KEYCODE_MEDIA_CLOSE
129 0   ��  KEYCODE_MEDIA_EJECT
130 0   ��  KEYCODE_MEDIA_RECORD
131 0   ��  KEYCODE_F1
132 0   ��  KEYCODE_F2
133 0   ��  KEYCODE_F3
134 0   ��  KEYCODE_F4
135 0   ��  KEYCODE_F5
136 0   ��  KEYCODE_F6
137 0   ��  KEYCODE_F7
138 0   ��  KEYCODE_F8
139 0   ��  KEYCODE_F9
140 0   ��  KEYCODE_F10
141 0   ��  KEYCODE_F11
142 0   ��  KEYCODE_F12
143 0   ��  KEYCODE_NUM_LOCK
144 0   ��  KEYCODE_NUMPAD_0
145 0   ��  KEYCODE_NUMPAD_1
146 0   ��  KEYCODE_NUMPAD_2
147 0   ��  KEYCODE_NUMPAD_3
148 0   ��  KEYCODE_NUMPAD_4
149 0   ��  KEYCODE_NUMPAD_5
150 0   ��  KEYCODE_NUMPAD_6
151 0   ��  KEYCODE_NUMPAD_7
152 0   ��  KEYCODE_NUMPAD_8
153 0   ��  KEYCODE_NUMPAD_9
154 47  /   KEYCODE_NUMPAD_DIVIDE
155 42  *   KEYCODE_NUMPAD_MULTIPLY
156 45  -   KEYCODE_NUMPAD_SUBTRACT
157 43  +   KEYCODE_NUMPAD_ADD
158 0   ��  KEYCODE_NUMPAD_DOT
159 44  ,   KEYCODE_NUMPAD_COMMA
160 10      KEYCODE_NUMPAD_ENTER
161 61  =   KEYCODE_NUMPAD_EQUALS
162 40  (   KEYCODE_NUMPAD_LEFT_PAREN
163 41  )   KEYCODE_NUMPAD_RIGHT_PAREN
164 0   ��  KEYCODE_VOLUME_MUTE
165 0   ��  KEYCODE_INFO
166 0   ��  KEYCODE_CHANNEL_UP
167 0   ��  KEYCODE_CHANNEL_DOWN
168 0   ��  KEYCODE_ZOOM_IN
169 0   ��  KEYCODE_ZOOM_OUT
170 0   ��  KEYCODE_TV
171 0   ��  KEYCODE_WINDOW
172 0   ��  KEYCODE_GUIDE
173 0   ��  KEYCODE_DVR
174 0   ��  KEYCODE_BOOKMARK
175 0   ��  KEYCODE_CAPTIONS
176 0   ��  KEYCODE_SETTINGS
177 0   ��  KEYCODE_TV_POWER
178 0   ��  KEYCODE_TV_INPUT
179 0   ��  KEYCODE_STB_POWER
180 0   ��  KEYCODE_STB_INPUT
181 0   ��  KEYCODE_AVR_POWER
182 0   ��  KEYCODE_AVR_INPUT
183 0   ��  KEYCODE_PROG_RED
184 0   ��  KEYCODE_PROG_GREEN
185 0   ��  KEYCODE_PROG_YELLOW
186 0   ��  KEYCODE_PROG_BLUE
187 0   ��  KEYCODE_APP_SWITCH
188 0   ��  KEYCODE_BUTTON_1
189 0   ��  KEYCODE_BUTTON_2
190 0   ��  KEYCODE_BUTTON_3
191 0   ��  KEYCODE_BUTTON_4
192 0   ��  KEYCODE_BUTTON_5
193 0   ��  KEYCODE_BUTTON_6
194 0   ��  KEYCODE_BUTTON_7
195 0   ��  KEYCODE_BUTTON_8
196 0   ��  KEYCODE_BUTTON_9
197 0   ��  KEYCODE_BUTTON_10
198 0   ��  KEYCODE_BUTTON_11
199 0   ��  KEYCODE_BUTTON_12
200 0   ��  KEYCODE_BUTTON_13
201 0   ��  KEYCODE_BUTTON_14
202 0   ��  KEYCODE_BUTTON_15
203 0   ��  KEYCODE_BUTTON_16
204 0   ��  KEYCODE_LANGUAGE_SWITCH
205 0   ��  KEYCODE_MANNER_MODE
206 0   ��  KEYCODE_3D_MODE
207 0   ��  KEYCODE_CONTACTS
208 0   ��  KEYCODE_CALENDAR
209 0   ��  KEYCODE_MUSIC
210 0   ��  KEYCODE_CALCULATOR
211 0   ��  KEYCODE_ZENKAKU_HANKAKU
212 0   ��  KEYCODE_EISU
213 0   ��  KEYCODE_MUHENKAN
214 0   ��  KEYCODE_HENKAN
215 0   ��  KEYCODE_KATAKANA_HIRAGANA
216 0   ��  KEYCODE_YEN
217 0   ��  KEYCODE_RO
218 0   ��  KEYCODE_KANA
219 0   ��  KEYCODE_ASSIST
220 0   ��  KEYCODE_BRIGHTNESS_DOWN
221 0   ��  KEYCODE_BRIGHTNESS_UP
222 0   ��  KEYCODE_MEDIA_AUDIO_TRACK
223 0   ��  KEYCODE_SLEEP
224 0   ��  KEYCODE_WAKEUP
225 0   ��  KEYCODE_PAIRING
226 0   ��  KEYCODE_MEDIA_TOP_MENU
227 0   ��  KEYCODE_11
228 0   ��  KEYCODE_12
229 0   ��  KEYCODE_LAST_CHANNEL
230 0   ��  KEYCODE_TV_DATA_SERVICE
231 0   ��  KEYCODE_VOICE_ASSIST
232 0   ��  KEYCODE_TV_RADIO_SERVICE
233 0   ��  KEYCODE_TV_TELETEXT
234 0   ��  KEYCODE_TV_NUMBER_ENTRY
235 0   ��  KEYCODE_TV_TERRESTRIAL_ANALOG
236 0   ��  KEYCODE_TV_TERRESTRIAL_DIGITAL
237 0   ��  KEYCODE_TV_SATELLITE
238 0   ��  KEYCODE_TV_SATELLITE_BS
239 0   ��  KEYCODE_TV_SATELLITE_CS
240 0   ��  KEYCODE_TV_SATELLITE_SERVICE
241 0   ��  KEYCODE_TV_NETWORK
242 0   ��  KEYCODE_TV_ANTENNA_CABLE
243 0   ��  KEYCODE_TV_INPUT_HDMI_1
244 0   ��  KEYCODE_TV_INPUT_HDMI_2
245 0   ��  KEYCODE_TV_INPUT_HDMI_3
246 0   ��  KEYCODE_TV_INPUT_HDMI_4
247 0   ��  KEYCODE_TV_INPUT_COMPOSITE_1
248 0   ��  KEYCODE_TV_INPUT_COMPOSITE_2
249 0   ��  KEYCODE_TV_INPUT_COMPONENT_1
250 0   ��  KEYCODE_TV_INPUT_COMPONENT_2
251 0   ��  KEYCODE_TV_INPUT_VGA_1
252 0   ��  KEYCODE_TV_AUDIO_DESCRIPTION
253 0   ��  KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
254 0   ��  KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN
255 0   ��  KEYCODE_TV_ZOOM_MODE
256 0   ��  KEYCODE_TV_CONTENTS_MENU
257 0   ��  KEYCODE_TV_MEDIA_CONTEXT_MENU
258 0   ��  KEYCODE_TV_TIMER_PROGRAMMING
259 0   ��  KEYCODE_HELP
260 0   ��  KEYCODE_NAVIGATE_PREVIOUS
261 0   ��  KEYCODE_NAVIGATE_NEXT
262 0   ��  KEYCODE_NAVIGATE_IN
263 0   ��  KEYCODE_NAVIGATE_OUT
264 0   ��  KEYCODE_STEM_PRIMARY
265 0   ��  KEYCODE_STEM_1
266 0   ��  KEYCODE_STEM_2
267 0   ��  KEYCODE_STEM_3
268 0   ��  KEYCODE_DPAD_UP_LEFT
269 0   ��  KEYCODE_DPAD_DOWN_LEFT
270 0   ��  KEYCODE_DPAD_UP_RIGHT
271 0   ��  KEYCODE_DPAD_DOWN_RIGHT
272 0   ��  KEYCODE_MEDIA_SKIP_FORWARD
273 0   ��  KEYCODE_MEDIA_SKIP_BACKWARD
274 0   ��  KEYCODE_MEDIA_STEP_FORWARD
275 0   ��  KEYCODE_MEDIA_STEP_BACKWARD
276 0   ��  KEYCODE_SOFT_SLEEP
277 0   ��  KEYCODE_CUT
278 0   ��  KEYCODE_COPY
279 0   ��  KEYCODE_PASTE
280 0   ��  KEYCODE_SYSTEM_NAVIGATION_UP
281 0   ��  KEYCODE_SYSTEM_NAVIGATION_DOWN
282 0   ��  KEYCODE_SYSTEM_NAVIGATION_LEFT
283 0   ��  KEYCODE_SYSTEM_NAVIGATION_RIGHT
</code>```

Dead keys

Note that it might also be necessary to take dead keys into account. The docs say

The system recognizes the following Unicode characters as combining
  diacritical dead key characters.

'\u0300': Grave accent.

'\u0301': Acute accent.

'\u0302': Circumflex accent.

'\u0303': Tilde accent.

'\u0308': Umlaut accent.

When a dead key is typed followed by another character, the dead key
  and the following characters are composed. For example, when the user
  types a grave accent dead key followed by the letter 'a', the result
  is 'à'.

To get the dead key a combination of KeyEvent.getDeadChar(), COMBINING_ACCENT, and COMBINING_ACCENT_MASK are used. The following method is used in many open source projects to send hard key events on to the InputConnection.

```<code>/**
 * This translates incoming hard key events in to edit operations on an
 * InputConnection.  It is only needed when using the
 * PROCESS_HARD_KEYS option.
 */
private boolean translateKeyDown(int keyCode, KeyEvent event) {
    mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState,
            keyCode, event);
    int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState));
    mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
    InputConnection ic = getCurrentInputConnection();
    if (c == 0 || ic == null) {
        return false;
    }

    boolean dead = false;

    if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) {
        dead = true;
        c = c & KeyCharacterMap.COMBINING_ACCENT_MASK;
    }

    if (mComposing.length() > 0) {
        char accent = mComposing.charAt(mComposing.length() -1 );
        int composed = KeyEvent.getDeadChar(accent, c);

        if (composed != 0) {
            c = composed;
            mComposing.setLength(mComposing.length()-1);
        }
    }

    onKey(c, null);

    return true;
}
</code>```

Another way?

@pskink mentions TextKeyListener, BaseKeyListener and KeyListener. These may very well be a better way to go. However, I was unable to find adequate explanation and examples of how to use them.

Body:
The KeyEvent.getUnicodeChar() documentation says

Returns 0 if the key is not one that is used to type Unicode characters.

Thus it is easy to differentiate text codes from control codes like this:

if (keyEvent.getUnicodeChar() != 0) {
    // unicode text
    char unicodeChar = (char) keyEvent.getUnicodeChar();
} else {
    // control char
}

Here is a list that helped me reach this conclution:

// keyCode, Unicode, char, keyCode name

0   0   ��  KEYCODE_UNKNOWN
1   0   ��  KEYCODE_SOFT_LEFT
2   0   ��  KEYCODE_SOFT_RIGHT
3   0   ��  KEYCODE_HOME
4   0   ��  KEYCODE_BACK
5   0   ��  KEYCODE_CALL
6   0   ��  KEYCODE_ENDCALL
7   48  0   KEYCODE_0
8   49  1   KEYCODE_1
9   50  2   KEYCODE_2
10  51  3   KEYCODE_3
11  52  4   KEYCODE_4
12  53  5   KEYCODE_5
13  54  6   KEYCODE_6
14  55  7   KEYCODE_7
15  56  8   KEYCODE_8
16  57  9   KEYCODE_9
17  42  *   KEYCODE_STAR
18  35  #   KEYCODE_POUND
19  0   ��  KEYCODE_DPAD_UP
20  0   ��  KEYCODE_DPAD_DOWN
21  0   ��  KEYCODE_DPAD_LEFT
22  0   ��  KEYCODE_DPAD_RIGHT
23  0   ��  KEYCODE_DPAD_CENTER
24  0   ��  KEYCODE_VOLUME_UP
25  0   ��  KEYCODE_VOLUME_DOWN
26  0   ��  KEYCODE_POWER
27  0   ��  KEYCODE_CAMERA
28  0   ��  KEYCODE_CLEAR
29  97  a   KEYCODE_A
30  98  b   KEYCODE_B
31  99  c   KEYCODE_C
32  100 d   KEYCODE_D
33  101 e   KEYCODE_E
34  102 f   KEYCODE_F
35  103 g   KEYCODE_G
36  104 h   KEYCODE_H
37  105 i   KEYCODE_I
38  106 j   KEYCODE_J
39  107 k   KEYCODE_K
40  108 l   KEYCODE_L
41  109 m   KEYCODE_M
42  110 n   KEYCODE_N
43  111 o   KEYCODE_O
44  112 p   KEYCODE_P
45  113 q   KEYCODE_Q
46  114 r   KEYCODE_R
47  115 s   KEYCODE_S
48  116 t   KEYCODE_T
49  117 u   KEYCODE_U
50  118 v   KEYCODE_V
51  119 w   KEYCODE_W
52  120 x   KEYCODE_X
53  121 y   KEYCODE_Y
54  122 z   KEYCODE_Z
55  44  ,   KEYCODE_COMMA
56  46  .   KEYCODE_PERIOD
57  0   ��  KEYCODE_ALT_LEFT
58  0   ��  KEYCODE_ALT_RIGHT
59  0   ��  KEYCODE_SHIFT_LEFT
60  0   ��  KEYCODE_SHIFT_RIGHT
61  9       KEYCODE_TAB
62  32      KEYCODE_SPACE
63  0   ��  KEYCODE_SYM
64  0   ��  KEYCODE_EXPLORER
65  0   ��  KEYCODE_ENVELOPE
66  10      KEYCODE_ENTER
67  0   ��  KEYCODE_DEL
68  96  `   KEYCODE_GRAVE
69  45  -   KEYCODE_MINUS
70  61  =   KEYCODE_EQUALS
71  91  [   KEYCODE_LEFT_BRACKET
72  93  ]   KEYCODE_RIGHT_BRACKET
73  92  \   KEYCODE_BACKSLASH
74  59  ;   KEYCODE_SEMICOLON
75  39  '   KEYCODE_APOSTROPHE
76  47  /   KEYCODE_SLASH
77  64  @   KEYCODE_AT
78  0   ��  KEYCODE_NUM
79  0   ��  KEYCODE_HEADSETHOOK
80  0   ��  KEYCODE_FOCUS
81  43  +   KEYCODE_PLUS
82  0   ��  KEYCODE_MENU
83  0   ��  KEYCODE_NOTIFICATION
84  0   ��  KEYCODE_SEARCH
85  0   ��  KEYCODE_MEDIA_PLAY_PAUSE
86  0   ��  KEYCODE_MEDIA_STOP
87  0   ��  KEYCODE_MEDIA_NEXT
88  0   ��  KEYCODE_MEDIA_PREVIOUS
89  0   ��  KEYCODE_MEDIA_REWIND
90  0   ��  KEYCODE_MEDIA_FAST_FORWARD
91  0   ��  KEYCODE_MUTE
92  0   ��  KEYCODE_PAGE_UP
93  0   ��  KEYCODE_PAGE_DOWN
94  0   ��  KEYCODE_PICTSYMBOLS
95  0   ��  KEYCODE_SWITCH_CHARSET
96  0   ��  KEYCODE_BUTTON_A
97  0   ��  KEYCODE_BUTTON_B
98  0   ��  KEYCODE_BUTTON_C
99  0   ��  KEYCODE_BUTTON_X
100 0   ��  KEYCODE_BUTTON_Y
101 0   ��  KEYCODE_BUTTON_Z
102 0   ��  KEYCODE_BUTTON_L1
103 0   ��  KEYCODE_BUTTON_R1
104 0   ��  KEYCODE_BUTTON_L2
105 0   ��  KEYCODE_BUTTON_R2
106 0   ��  KEYCODE_BUTTON_THUMBL
107 0   ��  KEYCODE_BUTTON_THUMBR
108 0   ��  KEYCODE_BUTTON_START
109 0   ��  KEYCODE_BUTTON_SELECT
110 0   ��  KEYCODE_BUTTON_MODE
111 0   ��  KEYCODE_ESCAPE
112 0   ��  KEYCODE_FORWARD_DEL
113 0   ��  KEYCODE_CTRL_LEFT
114 0   ��  KEYCODE_CTRL_RIGHT
115 0   ��  KEYCODE_CAPS_LOCK
116 0   ��  KEYCODE_SCROLL_LOCK
117 0   ��  KEYCODE_META_LEFT
118 0   ��  KEYCODE_META_RIGHT
119 0   ��  KEYCODE_FUNCTION
120 0   ��  KEYCODE_SYSRQ
121 0   ��  KEYCODE_BREAK
122 0   ��  KEYCODE_MOVE_HOME
123 0   ��  KEYCODE_MOVE_END
124 0   ��  KEYCODE_INSERT
125 0   ��  KEYCODE_FORWARD
126 0   ��  KEYCODE_MEDIA_PLAY
127 0   ��  KEYCODE_MEDIA_PAUSE
128 0   ��  KEYCODE_MEDIA_CLOSE
129 0   ��  KEYCODE_MEDIA_EJECT
130 0   ��  KEYCODE_MEDIA_RECORD
131 0   ��  KEYCODE_F1
132 0   ��  KEYCODE_F2
133 0   ��  KEYCODE_F3
134 0   ��  KEYCODE_F4
135 0   ��  KEYCODE_F5
136 0   ��  KEYCODE_F6
137 0   ��  KEYCODE_F7
138 0   ��  KEYCODE_F8
139 0   ��  KEYCODE_F9
140 0   ��  KEYCODE_F10
141 0   ��  KEYCODE_F11
142 0   ��  KEYCODE_F12
143 0   ��  KEYCODE_NUM_LOCK
144 0   ��  KEYCODE_NUMPAD_0
145 0   ��  KEYCODE_NUMPAD_1
146 0   ��  KEYCODE_NUMPAD_2
147 0   ��  KEYCODE_NUMPAD_3
148 0   ��  KEYCODE_NUMPAD_4
149 0   ��  KEYCODE_NUMPAD_5
150 0   ��  KEYCODE_NUMPAD_6
151 0   ��  KEYCODE_NUMPAD_7
152 0   ��  KEYCODE_NUMPAD_8
153 0   ��  KEYCODE_NUMPAD_9
154 47  /   KEYCODE_NUMPAD_DIVIDE
155 42  *   KEYCODE_NUMPAD_MULTIPLY
156 45  -   KEYCODE_NUMPAD_SUBTRACT
157 43  +   KEYCODE_NUMPAD_ADD
158 0   ��  KEYCODE_NUMPAD_DOT
159 44  ,   KEYCODE_NUMPAD_COMMA
160 10      KEYCODE_NUMPAD_ENTER
161 61  =   KEYCODE_NUMPAD_EQUALS
162 40  (   KEYCODE_NUMPAD_LEFT_PAREN
163 41  )   KEYCODE_NUMPAD_RIGHT_PAREN
164 0   ��  KEYCODE_VOLUME_MUTE
165 0   ��  KEYCODE_INFO
166 0   ��  KEYCODE_CHANNEL_UP
167 0   ��  KEYCODE_CHANNEL_DOWN
168 0   ��  KEYCODE_ZOOM_IN
169 0   ��  KEYCODE_ZOOM_OUT
170 0   ��  KEYCODE_TV
171 0   ��  KEYCODE_WINDOW
172 0   ��  KEYCODE_GUIDE
173 0   ��  KEYCODE_DVR
174 0   ��  KEYCODE_BOOKMARK
175 0   ��  KEYCODE_CAPTIONS
176 0   ��  KEYCODE_SETTINGS
177 0   ��  KEYCODE_TV_POWER
178 0   ��  KEYCODE_TV_INPUT
179 0   ��  KEYCODE_STB_POWER
180 0   ��  KEYCODE_STB_INPUT
181 0   ��  KEYCODE_AVR_POWER
182 0   ��  KEYCODE_AVR_INPUT
183 0   ��  KEYCODE_PROG_RED
184 0   ��  KEYCODE_PROG_GREEN
185 0   ��  KEYCODE_PROG_YELLOW
186 0   ��  KEYCODE_PROG_BLUE
187 0   ��  KEYCODE_APP_SWITCH
188 0   ��  KEYCODE_BUTTON_1
189 0   ��  KEYCODE_BUTTON_2
190 0   ��  KEYCODE_BUTTON_3
191 0   ��  KEYCODE_BUTTON_4
192 0   ��  KEYCODE_BUTTON_5
193 0   ��  KEYCODE_BUTTON_6
194 0   ��  KEYCODE_BUTTON_7
195 0   ��  KEYCODE_BUTTON_8
196 0   ��  KEYCODE_BUTTON_9
197 0   ��  KEYCODE_BUTTON_10
198 0   ��  KEYCODE_BUTTON_11
199 0   ��  KEYCODE_BUTTON_12
200 0   ��  KEYCODE_BUTTON_13
201 0   ��  KEYCODE_BUTTON_14
202 0   ��  KEYCODE_BUTTON_15
203 0   ��  KEYCODE_BUTTON_16
204 0   ��  KEYCODE_LANGUAGE_SWITCH
205 0   ��  KEYCODE_MANNER_MODE
206 0   ��  KEYCODE_3D_MODE
207 0   ��  KEYCODE_CONTACTS
208 0   ��  KEYCODE_CALENDAR
209 0   ��  KEYCODE_MUSIC
210 0   ��  KEYCODE_CALCULATOR
211 0   ��  KEYCODE_ZENKAKU_HANKAKU
212 0   ��  KEYCODE_EISU
213 0   ��  KEYCODE_MUHENKAN
214 0   ��  KEYCODE_HENKAN
215 0   ��  KEYCODE_KATAKANA_HIRAGANA
216 0   ��  KEYCODE_YEN
217 0   ��  KEYCODE_RO
218 0   ��  KEYCODE_KANA
219 0   ��  KEYCODE_ASSIST
220 0   ��  KEYCODE_BRIGHTNESS_DOWN
221 0   ��  KEYCODE_BRIGHTNESS_UP
222 0   ��  KEYCODE_MEDIA_AUDIO_TRACK
223 0   ��  KEYCODE_SLEEP
224 0   ��  KEYCODE_WAKEUP
225 0   ��  KEYCODE_PAIRING
226 0   ��  KEYCODE_MEDIA_TOP_MENU
227 0   ��  KEYCODE_11
228 0   ��  KEYCODE_12
229 0   ��  KEYCODE_LAST_CHANNEL
230 0   ��  KEYCODE_TV_DATA_SERVICE
231 0   ��  KEYCODE_VOICE_ASSIST
232 0   ��  KEYCODE_TV_RADIO_SERVICE
233 0   ��  KEYCODE_TV_TELETEXT
234 0   ��  KEYCODE_TV_NUMBER_ENTRY
235 0   ��  KEYCODE_TV_TERRESTRIAL_ANALOG
236 0   ��  KEYCODE_TV_TERRESTRIAL_DIGITAL
237 0   ��  KEYCODE_TV_SATELLITE
238 0   ��  KEYCODE_TV_SATELLITE_BS
239 0   ��  KEYCODE_TV_SATELLITE_CS
240 0   ��  KEYCODE_TV_SATELLITE_SERVICE
241 0   ��  KEYCODE_TV_NETWORK
242 0   ��  KEYCODE_TV_ANTENNA_CABLE
243 0   ��  KEYCODE_TV_INPUT_HDMI_1
244 0   ��  KEYCODE_TV_INPUT_HDMI_2
245 0   ��  KEYCODE_TV_INPUT_HDMI_3
246 0   ��  KEYCODE_TV_INPUT_HDMI_4
247 0   ��  KEYCODE_TV_INPUT_COMPOSITE_1
248 0   ��  KEYCODE_TV_INPUT_COMPOSITE_2
249 0   ��  KEYCODE_TV_INPUT_COMPONENT_1
250 0   ��  KEYCODE_TV_INPUT_COMPONENT_2
251 0   ��  KEYCODE_TV_INPUT_VGA_1
252 0   ��  KEYCODE_TV_AUDIO_DESCRIPTION
253 0   ��  KEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP
254 0   ��  KEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN
255 0   ��  KEYCODE_TV_ZOOM_MODE
256 0   ��  KEYCODE_TV_CONTENTS_MENU
257 0   ��  KEYCODE_TV_MEDIA_CONTEXT_MENU
258 0   ��  KEYCODE_TV_TIMER_PROGRAMMING
259 0   ��  KEYCODE_HELP
260 0   ��  KEYCODE_NAVIGATE_PREVIOUS
261 0   ��  KEYCODE_NAVIGATE_NEXT
262 0   ��  KEYCODE_NAVIGATE_IN
263 0   ��  KEYCODE_NAVIGATE_OUT
264 0   ��  KEYCODE_STEM_PRIMARY
265 0   ��  KEYCODE_STEM_1
266 0   ��  KEYCODE_STEM_2
267 0   ��  KEYCODE_STEM_3
268 0   ��  KEYCODE_DPAD_UP_LEFT
269 0   ��  KEYCODE_DPAD_DOWN_LEFT
270 0   ��  KEYCODE_DPAD_UP_RIGHT
271 0   ��  KEYCODE_DPAD_DOWN_RIGHT
272 0   ��  KEYCODE_MEDIA_SKIP_FORWARD
273 0   ��  KEYCODE_MEDIA_SKIP_BACKWARD
274 0   ��  KEYCODE_MEDIA_STEP_FORWARD
275 0   ��  KEYCODE_MEDIA_STEP_BACKWARD
276 0   ��  KEYCODE_SOFT_SLEEP
277 0   ��  KEYCODE_CUT
278 0   ��  KEYCODE_COPY
279 0   ��  KEYCODE_PASTE
280 0   ��  KEYCODE_SYSTEM_NAVIGATION_UP
281 0   ��  KEYCODE_SYSTEM_NAVIGATION_DOWN
282 0   ��  KEYCODE_SYSTEM_NAVIGATION_LEFT
283 0   ��  KEYCODE_SYSTEM_NAVIGATION_RIGHT

Dead keys

Note that it might also be necessary to take dead keys into account. The docs say

The system recognizes the following Unicode characters as combining
  diacritical dead key characters.

'\u0300': Grave accent.

'\u0301': Acute accent.

'\u0302': Circumflex accent.

'\u0303': Tilde accent.

'\u0308': Umlaut accent.

When a dead key is typed followed by another character, the dead key
  and the following characters are composed. For example, when the user
  types a grave accent dead key followed by the letter 'a', the result
  is 'à'.

To get the dead key a combination of KeyEvent.getDeadChar(), COMBINING_ACCENT, and COMBINING_ACCENT_MASK are used. The following method is used in many open source projects to send hard key events on to the InputConnection.

/**
 * This translates incoming hard key events in to edit operations on an
 * InputConnection.  It is only needed when using the
 * PROCESS_HARD_KEYS option.
 */
private boolean translateKeyDown(int keyCode, KeyEvent event) {
    mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState,
            keyCode, event);
    int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState));
    mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState);
    InputConnection ic = getCurrentInputConnection();
    if (c == 0 || ic == null) {
        return false;
    }

    boolean dead = false;

    if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) {
        dead = true;
        c = c & KeyCharacterMap.COMBINING_ACCENT_MASK;
    }

    if (mComposing.length() > 0) {
        char accent = mComposing.charAt(mComposing.length() -1 );
        int composed = KeyEvent.getDeadChar(accent, c);

        if (composed != 0) {
            c = composed;
            mComposing.setLength(mComposing.length()-1);
        }
    }

    onKey(c, null);

    return true;
}

Another way?

@pskink mentions TextKeyListener, BaseKeyListener and KeyListener. These may very well be a better way to go. However, I was unable to find adequate explanation and examples of how to use them.


问:
Reading pdf files line by line using python
I used the following code to read the pdf file, but it does not read it. What could possibly be the reason?

from PyPDF2 import PdfFileReader

reader = PdfFileReader("example.pdf")
contents = reader.pages[0].extractText().split("\n")
print(contents)
```

The output is [u''] instead of reading the content.

答:
May be this can help you to read PDF.</p>

```<code>import pyPdf
def getPDFContent(path):
    content = ""
    pages = 10
    p = file(path, "rb")
    pdf_content = pyPdf.PdfFileReader(p)
    for i in range(0, pages):
        content += pdf_content.getPage(i).extractText() + "\n"
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return content
</code>```

Body:
I used the following code to read the pdf file, but it does not read it. What could possibly be the reason?

from PyPDF2 import PdfFileReader

reader = PdfFileReader("example.pdf")
contents = reader.pages[0].extractText().split("\n")
print(contents)

The output is [u''] instead of reading the content.

Body:
May be this can help you to read PDF.

import pyPdf
def getPDFContent(path):
    content = ""
    pages = 10
    p = file(path, "rb")
    pdf_content = pyPdf.PdfFileReader(p)
    for i in range(0, pages):
        content += pdf_content.getPage(i).extractText() + "\n"
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return content


问:
iOS - State restoration - Get previously restored view controller
I have a navigation controller with several view controllers inside.

While restoring app application(_:viewControllerWithRestorationIdentifierPath:coder:) method calls for each controller one by one initially for first in stack then for second and so on.
At time of restoring second view controller I need to get reference to first one (to make some connection between them).

Is there any way to get previously restored controller at this step without saving this controller somewhere in the app? (the same is about navigation controller I don't save referents to it anywhere in the app)

答:
My understanding is that only the last View Controller viewed before the app was sent to background will have its state restored by the encode/decode methods you listed above, with NSCoder.
BUT you still need to save your own data, e.g. using NSKeyedArchiver or Core Data in case the app is terminated by user, or the device reboots. This may be the best solution in your case.

See link for encodeRestorableState here:

https://developer.apple.com/documentation/uikit/uiviewcontroller/1621461-encoderestorablestate

Specifically it says:

This method is not a substitute for saving your app's data
  structures persistently to disk. You should continue to save your
  app's actual data to iCloud or the local file system using existing
  techniques. This method is intended only for saving configuration
  state or other information related to your app's user interface. You
  should consider any data you write to the coder as purgeable and be
  prepared for it to be unavailable during subsequent launches.


问:
How can I add font awesome icons into Custom Post Type UI Menu Icon area?
I want to add font awesome icons into Custom Post Type UI Menu Icon area but I couldn't add. How can I do any idea, guys? Thank you.

答:
you can download font awesome icons as png and upload in wordpress and write full url http://www.example.com/wp-content/uploads/2014/11/your-cpt-icon.png
like above...

icon size must be 20px...

or you can use dashicon.it automatically supports dashicons.

chck this image http://dev.savivatechnologies.com/hpa/wp-content/uploads/2017/07/dashicon.png

Hopes this will help you...


问:
Select matching element/rename HTML tag in Visual Studio Code
Let's say I've got the following code

```<code>    <div class="footer">
      <div>Foo</div>
    </div>
</code>```

How can I change .footer from a div element to a footer element?

That is, if I have the cursor in div I'm looking for a keyboard shortcut that selects the opening and closing tags of an element. I believe I've used emmet to do this before in Sublime, but I can't seem to find similar functionality in Code. (Ideally this would work in JSX files too...)

答: CTRL + D on windows. As mentioned by @tataata, CMD + D on Mac OS. Not limited to tag renaming. Very useful.</p>

Body:
Let's say I've got the following code

Foo

How can I change .footer from a div element to a footer element?

That is, if I have the cursor in div I'm looking for a keyboard shortcut that selects the opening and closing tags of an element. I believe I've used emmet to do this before in Sublime, but I can't seem to find similar functionality in Code. (Ideally this would work in JSX files too...)


问:
get %APPDATA% path using c++
I want to get the path to the %APPDATA% folder.

In win 2000 & xp it's in: C:\Documents and Settings\user name\Application Data

In vista & win7 it's in: C:\Users\user name\AppData\Roaming

I know there is the function SHGetSpecialFolderPath but it retrieves a BOOL
and I want to get the path as a string.

答:
The third parameter of SHGetSpecialFolderPath(), named lpszPath, is marked as __out.

Something like this should do:

```<code>// Beware, brain-compiled code ahead!
wchar_t buffer[MAX_PATH];
BOOL result = SHGetSpecialFolderPath( hWnd
                                    , buffer
                                    , CSIDL_LOCAL_APPDATA
                                    , false );
if(!result) throw "You'll need error handling here!";
std::wcout << buffer;
</code>```

Note: I haven't done any Win API work in years. Very likely someone comes along shortly pointing out where I blew it.

Title: get %APPDATA% path using c++

Body:
The third parameter of SHGetSpecialFolderPath(), named lpszPath, is marked as __out.

Something like this should do:

// Beware, brain-compiled code ahead!
wchar_t buffer[MAX_PATH];
BOOL result = SHGetSpecialFolderPath( hWnd
                                    , buffer
                                    , CSIDL_LOCAL_APPDATA
                                    , false );
if(!result) throw "You'll need error handling here!";
std::wcout << buffer;

Note: I haven't done any Win API work in years. Very likely someone comes along shortly pointing out where I blew it.

ContentLicense: CC BY-SA 2.5


问:
Angular JS: data binding with dynamically added html elements
I am facing problems with two way data binding in angular js. Here is the sample code.

```<code><!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body ng-app="">

<div>

<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="name"></p>

<div id="jack">
</div>
<script>
    $("document").ready(function(){
        $("#jack").append("<p ng-bind='name'></p>");
    });
</script>
</body>
</html>
</code>```

Over here I am dynamically adding a paragraph with ng-bind to a div called jack using jQuery

For some reason when I type something in input box it is not reflecting in paragraph with ng-bind property.

I am a novice in angular js and would request you to provide me a simple solution to tackle this issue.

答:
Well first we need to define the app and create custom directive.

```<code>var myApp=angular.module('myApp',[])
                 .controller('myCtrl',function($scope){
                      $scope.name="Your name";
                 })
   myApp.directive('myDirective', function() {
         return {
                 restrict: 'E',
                 template: '<span data-ng-bind="name"></span>'
         };
   });
</code>```

After this you need to use above created directive as like below

```<code><my-Directive></my-Directive>
</code>```

Body:
I am facing problems with two way data binding in angular js. Here is the sample code.

<!DOCTYPE html>

Input something in the input box:

Name: <input type="text" ng-model="name">

Over here I am dynamically adding a paragraph with ng-bind to a div called jack using jQuery

For some reason when I type something in input box it is not reflecting in paragraph with ng-bind property.

I am a novice in angular js and would request you to provide me a simple solution to tackle this issue.

Body:
Well first we need to define the app and create custom directive.

var myApp=angular.module('myApp',[])
                 .controller('myCtrl',function($scope){
                      $scope.name="Your name";
                 })
   myApp.directive('myDirective', function() {
         return {
                 restrict: 'E',
                 template: '<span data-ng-bind="name"></span>'
         };
   });

After this you need to use above created directive as like below

<my-Directive></my-Directive>


问:
How to create alert function in php?
i want insert user in db mysql, i have a controller php, im validate if user exist in db  through a function, then if or not exist i want show alert function an redirect to php page, for that im using:

```<code><?php

 if(dao::existUser($user)) {
    echo "<script type=\"text/javascript\">\n";
    echo "alert('user exist!');\n";
    echo "window.location = ('../insertUser.php');\n";
    echo "</script>";
 }
</code>```

this function works!! but
i want to encapsulate the function in a method to later call it

example:

```<code><?php
class Utils {
  static function responseText($message, $url) {
     echo "<script type=\"text/javascript\">\n";
     echo "alert('"+$message+"');\n";
     echo "window.location = ('"+$url+"');\n";
     echo "</script>";
  }
}
</code>```

then, in my controller:

```<code><?php

 if(dao::existUser($user)) {
   Utils::responseText("user exist",'../insertUser.php');
 }
</code>```

but not work, and after call responseText, my page  goes blank

答:
If i understand you properly bind javascript to php.

```<code><?php
    $script = '<script type="text/javascript">';
    $script .= 'function showAlert(){';
    $script .= 'alert("Hello World.");';
    $script .= '}';
    $script .= '</script>';
    echo $script;
?>
</code>```

Than after page has loaded you can call it !

```<code><script type="text/javascript">
    window.onload = function () {
        showAlert();
    }
</script>
</code>```

Title: How to create alert function in php?

Body:
i want insert user in db mysql, i have a controller php, im validate if user exist in db  through a function, then if or not exist i want show alert function an redirect to php page, for that im using:

<?php

 if(dao::existUser($user)) {
    echo "";
 }

this function works!! but
i want to encapsulate the function in a method to later call it

example:

<?php
class Utils {
  static function responseText($message, $url) {
     echo "";
  }
}

then, in my controller:

<?php

 if(dao::existUser($user)) {
   Utils::responseText("user exist",'../insertUser.php');
 }

but not work, and after call responseText, my page  goes blank

Body:
If i understand you properly bind javascript to php.

<?php
    $script = '<script type="text/javascript">';
    $script .= 'function showAlert(){';
    $script .= 'alert("Hello World.");';
    $script .= '}';
    $script .= '</script>';
    echo $script;
?>

Than after page has loaded you can call it !

<script type="text/javascript">
    window.onload = function () {
        showAlert();
    }
</script>


问:
VS2017 Item Template not showing up in Xamarin project
I created a new VS2017 project template because the C# 'Class' template for Xamarin.Android adds way too much usings for my tastes. Here's the .vstemplate file:

```<code><VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>Class.cs</DefaultName>
    <Name>Class</Name>
    <Description>An unfancy C# class.</Description>
    <ProjectType>CSharp</ProjectType>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References />
    <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">Class.cs</ProjectItem>
  </TemplateContent>
</VSTemplate>
</code>```

I can't figure out why, but this item template won't show up in my Xamarin.Android project. However, the template does show up when I create a new .NET Core/Framework project and click Add > New Item.

Any clue what's causing this? I've been staring at MSDN/StackOverflow questions for half an hour but none of them seem to help with this.

I'm using the latest stable build of VS2017, which I think is 15.2.

答:
You need the <AppliesTo/> element. See AppliesTo

Using your template you would do:

```<code><VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>Class.cs</DefaultName>
    <Name>Class</Name>
    <Description>An unfancy C# class.</Description>
    <ProjectType>CSharp</ProjectType>
    <AppliesTo>CSharp</AppliesTo>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References />
    <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">Class.cs</ProjectItem>
  </TemplateContent>
</VSTemplate>
</code>```

Body:
I created a new VS2017 project template because the C# 'Class' template for Xamarin.Android adds way too much usings for my tastes. Here's the .vstemplate file:

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>Class.cs</DefaultName>
    <Name>Class</Name>
    <Description>An unfancy C# class.</Description>
    <ProjectType>CSharp</ProjectType>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References />
    <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">Class.cs</ProjectItem>
  </TemplateContent>
</VSTemplate>

I can't figure out why, but this item template won't show up in my Xamarin.Android project. However, the template does show up when I create a new .NET Core/Framework project and click Add > New Item.

Any clue what's causing this? I've been staring at MSDN/StackOverflow questions for half an hour but none of them seem to help with this.

I'm using the latest stable build of VS2017, which I think is 15.2.

Body:
You need the <AppliesTo/> element. See AppliesTo

Using your template you would do:

<VSTemplate Version="3.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="Item">
  <TemplateData>
    <DefaultName>Class.cs</DefaultName>
    <Name>Class</Name>
    <Description>An unfancy C# class.</Description>
    <ProjectType>CSharp</ProjectType>
    <AppliesTo>CSharp</AppliesTo>
    <SortOrder>10</SortOrder>
    <Icon>__TemplateIcon.ico</Icon>
  </TemplateData>
  <TemplateContent>
    <References />
    <ProjectItem SubType="Code" TargetFileName="$fileinputname$.cs" ReplaceParameters="true">Class.cs</ProjectItem>
  </TemplateContent>
</VSTemplate>


问:
Reset to default slider value react-native
I try to create a reset button for the slider that will reset it to the initial value when pressed. My code doesn't show any error but the reset button doesn't work.

This is the Slider component:

```<code>import React, {Component} from 'react';
import {Slider,
  Text,
  StyleSheet,
  View} from 'react-native';
import {ButtonReset} from './ResetButton.js'

export class SliderRoll extends Component {

  state = {
    value: 1,
  };

  resetSliderValue = () => this.setState({value : 1})

  render() {
    return (
      <View style={styles.container}>
        <Slider style={styles.slider}
          minimumTrackTintColor={'blue'}
          maximumTrackTintColor={'red'}
          maximumValue = {2}
          value= {this.state.value}
          step={0.5}
          onValueChange={(value) => this.setState({value: value})}
        />

        <ButtonReset resetSliderValue = {this.state.resetSliderValue}/>
        <Text style={styles.text} >
          {this.state.value}
        </Text>

      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flexDirection:'column',
    width: 150,
    backgroundColor: 'pink',
    marginLeft: 50,
    justifyContent: 'center'
  },
  slider: {
    width: 150,
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    fontWeight: '500',
  },
})
</code>```

This is the Reset button:

```<code>import React, {Component} from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity
} from 'react-native';

export class ButtonReset extends Component{
    render(){
      return(
        <TouchableOpacity style = {styles.container}
            onPress= {this.props.resetSliderValue}>
          <Image
            style={styles.button}
            source={require('./restart.png')}
          />
        </TouchableOpacity>
      );
    }
}

const styles = StyleSheet.create({
    container: {
        width: 50,
        alignItems: 'center',
        backgroundColor: 'pink',
        marginLeft: 50,
        marginTop: 10,
    },
    button: {
        width:50,
        height:50,
        transform: [
            {scale: 1}
        ]
    }
})
</code>```

答:
Here is the problematic piece that stuck out right away:

<ButtonReset resetSliderValue = {this.state.resetSliderValue}/>

I believe it should be:

<ButtonReset resetSliderValue = {this.resetSliderValue}/>

Also, I believe you need to bind this so you can access this for setting state in the resetSliderValue function. I personally like to bind this once in the constructor for any functions that require it so no unnecessary rebinding during rendering:

```<code>constructor(props) {
  super(props);
  this.resetSliderValue = this.resetSliderValue.bind(this);
}
</code>```

Body:
I try to create a reset button for the slider that will reset it to the initial value when pressed. My code doesn't show any error but the reset button doesn't work.

This is the Slider component:

import React, {Component} from 'react';
import {Slider,
  Text,
  StyleSheet,
  View} from 'react-native';
import {ButtonReset} from './ResetButton.js'

export class SliderRoll extends Component {

  state = {
    value: 1,
  };

  resetSliderValue = () => this.setState({value : 1})

  render() {
    return (
      <View style={styles.container}>
        <Slider style={styles.slider}
          minimumTrackTintColor={'blue'}
          maximumTrackTintColor={'red'}
          maximumValue = {2}
          value= {this.state.value}
          step={0.5}
          onValueChange={(value) => this.setState({value: value})}
        />

        <ButtonReset resetSliderValue = {this.state.resetSliderValue}/>
        <Text style={styles.text} >
          {this.state.value}
        </Text>

      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flexDirection:'column',
    width: 150,
    backgroundColor: 'pink',
    marginLeft: 50,
    justifyContent: 'center'
  },
  slider: {
    width: 150,
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
    fontWeight: '500',
  },
})

This is the Reset button:

import React, {Component} from 'react';
import {
  Text,
  View,
  StyleSheet,
  Image,
  TouchableOpacity
} from 'react-native';

export class ButtonReset extends Component{
    render(){
      return(
        <TouchableOpacity style = {styles.container}
            onPress= {this.props.resetSliderValue}>
          <Image
            style={styles.button}
            source={require('./restart.png')}
          />
        </TouchableOpacity>
      );
    }
}

const styles = StyleSheet.create({
    container: {
        width: 50,
        alignItems: 'center',
        backgroundColor: 'pink',
        marginLeft: 50,
        marginTop: 10,
    },
    button: {
        width:50,
        height:50,
        transform: [
            {scale: 1}
        ]
    }
})

Body:
Here is the problematic piece that stuck out right away:

<ButtonReset resetSliderValue = {this.state.resetSliderValue}/>

I believe it should be:

<ButtonReset resetSliderValue = {this.resetSliderValue}/>

Also, I believe you need to bind this so you can access this for setting state in the resetSliderValue function. I personally like to bind this once in the constructor for any functions that require it so no unnecessary rebinding during rendering:

constructor(props) {
  super(props);
  this.resetSliderValue = this.resetSliderValue.bind(this);
}


问:
Git not in path during build step in jenkins
Git and Github plugins are installed.
Git is used to clone the repository (so it works).
I don't have any nodes other than the master which handles the builds.
Git PATH is specified at /jenkins/configureTools/.

However, I get this error message?

```<code>+ bower install
bower semantic-ui-range#*       ENOGIT git is not installed or not in the PATH
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>```

How can I avoid it?

答:
The OP created a Jenkins VM in the context of Bitnami Jenkins for Google Cloud Platform, you can check out the section "How to start with Git and Jenkins?"

As described below, that does not work well (the PATH does not include Git on bower operations)

Workaround, proposed by the OP:

Created another Jenkins VM, this time not using the Bitnami Jenkins.

  It works out of the box.

Original answer.

Regarding bower, check bower issue 972

had to go into /bower/lib/core/resolvers/GitResolver.js and comment out the line that checks if Git is there to get this to work. It seems that the which module isn't working correctly for me.

Commented out line:

```<code>if (!hasGit) {
     throw createError('git is not installed or not in the PATH', 'ENOGIT');
}
</code>```

Bower: 1.7.7

Node: 5.9.0

More generally:

You need to make sure:

Jenkins global settings has a Git PATH defined

the slaves have a Git installed at that PATH

Example:

(Source: "Jenkins path to git Windows master / Linux slave")

That way, you don't depend on the PATH environment variable (on the master or the slaves), as Jenkins will complete it with the Git path defined.

Just in case the slave is executed with a different account (and different PATH), try (if your current PATH does include git) to make that path available to all users (for testing):

```<code>echo "PATH=$PATH" | sudo tee /etc/environment
</code>```

Body:
Git and Github plugins are installed.
Git is used to clone the repository (so it works).
I don't have any nodes other than the master which handles the builds.
Git PATH is specified at /jenkins/configureTools/.

However, I get this error message?

+ bower install
bower semantic-ui-range#*       ENOGIT git is not installed or not in the PATH
Build step 'Execute shell' marked build as failure
Finished: FAILURE

How can I avoid it?

Body:
The OP created a Jenkins VM in the context of Bitnami Jenkins for Google Cloud Platform, you can check out the section "How to start with Git and Jenkins?"

As described below, that does not work well (the PATH does not include Git on bower operations)

Workaround, proposed by the OP:

Created another Jenkins VM, this time not using the Bitnami Jenkins.

  It works out of the box.

Original answer.

Regarding bower, check bower issue 972

had to go into /bower/lib/core/resolvers/GitResolver.js and comment out the line that checks if Git is there to get this to work. It seems that the which module isn't working correctly for me.

Commented out line:

if (!hasGit) {
     throw createError('git is not installed or not in the PATH', 'ENOGIT');
}

Bower: 1.7.7

Node: 5.9.0

More generally:

You need to make sure:

Jenkins global settings has a Git PATH defined

the slaves have a Git installed at that PATH

Example:

(Source: "Jenkins path to git Windows master / Linux slave")

That way, you don't depend on the PATH environment variable (on the master or the slaves), as Jenkins will complete it with the Git path defined.

Just in case the slave is executed with a different account (and different PATH), try (if your current PATH does include git) to make that path available to all users (for testing):

echo "PATH=$PATH" | sudo tee /etc/environment


问:
When to call SetProcessWorkingSetSize? (Convincing the memory manager to release the memory)
In a previous post ( My program never releases the memory back. Why? ) I show that FastMM can cache (read as hold for itself) pretty large amounts of memory. If your application just loaded a large data set in RAM, after releasing the data, you will see that impressive amounts of RAM are not released back to the memory pool.

I looked around and it seems that calling the SetProcessWorkingSetSize API function will "flush" the cache to disk. However, I cannot decide when to call this function. I wanted to call it at the end of the OnClick event on the button that is performing the RAM intensive operation. However, some people are saying that this may cause AV.

If anybody used this function successfully, please let me (us) know.

Many thanks.

Edit:

1. After releasing the data set, the program still takes large amounts of RAM. After calling SetProcessWorkingSetSize the size returns to few MB. Some argue that nothing was released back. I agree. But the memory foot print is now small AND it is NOT increasing back after using the program normally (for example when performing normal operation that does not involves loading large data sets). Unfortunately, there is no way to demonstrate that the memory swapped to disk is ever loaded back into memory, but I think it is not.
2. I have already demonstrated (I hope) this is not a memory leak:

My program never releases the memory back. Why?

How to convince the memory manager to release unused memory

答: I used this function just once, when I implemented TWebBrowser. This component took me so much memory even if I destroyed the instance.</p>


问:
How to return the instance name of a class?
I would like the getName() method of SomeClass to return the instance name. In this case "SomeInstance." Is this possible to do, and how?

```<code>class SomeClass {
  getName() {
    return this.constructor.name;
  }
}

var SomeInstance = new SomeClass();

document.write(SomeInstance.getName());
</code>```

Update

This does the trick.

```<code>getName() {
  for (var instance in window){
        if (window[instance] === this){
            return instance;
        }
    }
}
</code>```

答:
Found this</p>

```<code>getName() {
  for (var instance in window){
        if (window[instance] === this){
            return instance;
        }
    }
 }
</code>```

Body:
I would like the getName() method of SomeClass to return the instance name. In this case "SomeInstance." Is this possible to do, and how?

class SomeClass {
  getName() {
    return this.constructor.name;
  }
}

var SomeInstance = new SomeClass();

document.write(SomeInstance.getName());

Update

This does the trick.

getName() {
  for (var instance in window){
        if (window[instance] === this){
            return instance;
        }
    }
}

Body:
Found this

getName() {
  for (var instance in window){
        if (window[instance] === this){
            return instance;
        }
    }
 }


问:
Jcomments list and form not showing
i have migrate my site joomla 1.5 to joomla 3.6.5. Jcomments working fine on joomla 1.5 but not working on joomla 3.6.5. Jcomments all configuration are same as old site extension but it's not showing anything in article full layout.

Plugin Configuration:

and this is link of article

http://www.weight-loss-center.net/joomlaL3/index.php/osteoporosis.html

答:
I have just post a reply on the forum post of JComments but for those who have a similar issue, about the comment list, it could be linked to multilingual. For instance, an article with /en/ on URL has some posts. If the site is multilingual and I access on my native language the URL would should /es/ on my browser and if no post in Spanish has been post, I won't see any comment.

Related to the form, I think is the template but as I answered in the forum post, I can see the form.

Title: Jcomments list and form not showing


问:
Deleting the head of doubly linked list
Sorry for such a low quality question but I have no idea why the following code doesn't work.

list points the head of the node.

```<code>void DeleteHeadNode(Node** list, Node * node)
    {
        if ((*list) == node) {
            Node * next = node->nextnode;
            next->prevnode = NULL;
        free(*list);
    }
}
</code>```

答:
I'm guessing "doesn't work" means list is no longer valid after your function - which will be true.

You should have

```<code>void DeleteHeadNode(Node** list, Node* node)
{
    if ((node != NULL) && (*list == node))    // check node being deleted
    {
        Node* next = node->nextnode;
        if (next != NULL)                     // ensure next exists
        {
           next->prevnode = NULL;
           free(*list);
           list = &next;                      // update pointer to head of list
        }
        else                                  // no next, list is now becoming empty
        {
           free(*list);
           list = NULL;                       // update pointer to head of list
        }
    }
}
</code>```

Title: Deleting the head of doubly linked list

Body:
Sorry for such a low quality question but I have no idea why the following code doesn't work.

list points the head of the node.

void DeleteHeadNode(Node** list, Node * node)
    {
        if ((*list) == node) {
            Node * next = node->nextnode;
            next->prevnode = NULL;
        free(*list);
    }
}

Body:
I'm guessing "doesn't work" means list is no longer valid after your function - which will be true.

You should have

void DeleteHeadNode(Node** list, Node* node)
{
    if ((node != NULL) && (*list == node))    // check node being deleted
    {
        Node* next = node->nextnode;
        if (next != NULL)                     // ensure next exists
        {
           next->prevnode = NULL;
           free(*list);
           list = &next;                      // update pointer to head of list
        }
        else                                  // no next, list is now becoming empty
        {
           free(*list);
           list = NULL;                       // update pointer to head of list
        }
    }
}


问:
How can I send an embed via my Discord bot, w/python?
I've been working a new Discord bot.

I've learnt a few stuff,and, now, I'd like to make the things a little more custom.

I've been trying to make the bot send embeds, instead, of a common message.

```<code>embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00)
embed.add_field(name="Fiel1", value="hi", inline=False)
embed.add_field(name="Field2", value="hi2", inline=False)
await self.bot.say(embed=embed)
</code>```

When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.

答:
When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.

This means you're out of date. Use pip to update your version of the library.

```<code>pip install --upgrade discord.py
</code>```

Body:
I've been working a new Discord bot.

I've learnt a few stuff,and, now, I'd like to make the things a little more custom.

I've been trying to make the bot send embeds, instead, of a common message.

embed=discord.Embed(title="Tile", description="Desc", color=0x00ff00)
embed.add_field(name="Fiel1", value="hi", inline=False)
embed.add_field(name="Field2", value="hi2", inline=False)
await self.bot.say(embed=embed)

When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.

Body:
When executing this code, I get the error that 'Embed' is not a valid member of the module 'discord'. All websites, show me this code, and I have no idea of any other way to send a embed.

This means you're out of date. Use pip to update your version of the library.

pip install --upgrade discord.py


问:
Cannot modify a primary key in MySQL
So I want to change kd_absen's length from 10 to 20 in the table called "absen". It's a primary key though.

And what happened next, phpmyadmin gave me this error massage

https://s.kaskus.id/r320x320/images/2017/07/08/9793710_20170708101310.JPG

What I tried so far: I tried to temporarily deleting the kd_absen in "penggajian" table (and re create it later). But a similar message appeared.

Any help will be appreciated, thanks in advance.

答:
1 - Remove the constraint of the primary key
2 - Alter the primary key field length
3 - Create another constraint to the primary key</p>

Title: Cannot modify a primary key in MySQL


问:
Why do we do a POST to confirm deletion in asp.net MVC?
The following is a note from Professional ASP.NET MVC 2 by Scott Hanselman ++

You might ask — why did we go through
  the effort of creating a <form> within
  our Delete Confi rmation screen? Why
  not just use a standard hyperlink to
  link to an action method that does the
  actual delete operation? The reason is
  because we want to be careful to guard
  against Web-crawlers and search
  engines discovering our URLs and
  inadvertently causing data to be
  deleted when they follow the links.
  HTTP-GET-based URLs are considered
  safe for them to access/crawl, and
  they are supposed to not follow
  HTTP-POST ones. A good rule is to make
  sure that you always put destructive
  or data-modifying operations behind
  HTTP-POST requests.

If web-crawlers and search engine have no access to the page containing deletion button, is it safe to use a standard hyperlink to link to an action method doing the actual delete operation?

答: If you use GET requests to do any changes to your database at all, you will more than likely get hit with Cross-Site Request Forgery attacks at some point. The book you are reading discusses that more, and I have a few posts about it on my blog. It's an extremely common vulnerability I find these days; as frequent as SQL Injection, and much simpler to exploit.


问:
My <input> box won't display single quotes
If it has a single quote in it, any string that I try to enter into my HTML input box is truncated in the input box once it is submitted.  Its POST value comes thru unchanged, but the string shows as truncated in the input box, whether I use htmlspecialchars() or not. A noobie question, no doubt, but I've tried hard to figure it out and run out of ideas. Thanks for any help.

```<code>    <!DOCTYPE html>
    <body><title> Self-inserting input_box_SO.php </title>
    <?php
    //  POST form initiation.
    ECHO "<form action='input_box_SO.php' method='post'>";

    // GET POSTed value and escape it for HTML use
    $Caption_htmlspecialchars=$_POST['Caption_htmlspecialchars'];
    $Caption_htmlspecialchars=htmlspecialchars($Caption_htmlspecialchars);
    ECHO "The echo of the variable <em> \$Caption_htmlspecialchars </em> looks like this:<br>";
    ECHO "<b> $Caption_htmlspecialchars </b><br>";
    ECHO "But in the input box, \$Caption_htmlspecialchars is truncated by a single quote: <br>";
    // ETA: Bad old line that caused the problem, now commented:
    // ECHO "<input type='text' name='Caption_htmlspecialchars' size=100 value='$Caption_htmlspecialchars' maxlength = 100 required /><br><br>";
    // ETA: Newly added line that fixes the problem:
echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required /><br><br>';
    // SUBMIT button.  Submits back to the same page: input_box.php
    echo "<b><input type='Submit' name='submit' value='Submit'/></b></br></br>";
    ?>
    </body></html>
</code>```

Here is what Inspect Elements > Elements shows for the input element:

 input_box_SO.php
The echo of the variable  $Caption_htmlspecialchars  looks like this:
 test with special chars. & " < > and a single quote ('), which causes truncation in the input box.
But in the input box, $Caption_htmlspecialchars is truncated by a single quote:
 and a single quote (" ),="" which="" causes="" truncation="" in="" the="" input="" box.="" '="" maxlength="100" required="">

With the Source looking like this:  value='test with special chars. & " < > and a single quote ('), which causes truncation in the input box. '

答:
Try to use the addslashes and do it like

$Caption_htmlspecialchars = addslashes($Caption_htmlspecialchars);

Body:
If it has a single quote in it, any string that I try to enter into my HTML input box is truncated in the input box once it is submitted.  Its POST value comes thru unchanged, but the string shows as truncated in the input box, whether I use htmlspecialchars() or not. A noobie question, no doubt, but I've tried hard to figure it out and run out of ideas. Thanks for any help.

    <!DOCTYPE html>
    <title> Self-inserting input_box_SO.php </title>
    <?php
    //  POST form initiation.
    ECHO "<form action='input_box_SO.php' method='post'>";

    // GET POSTed value and escape it for HTML use
    $Caption_htmlspecialchars=$_POST['Caption_htmlspecialchars'];
    $Caption_htmlspecialchars=htmlspecialchars($Caption_htmlspecialchars);
    ECHO "The echo of the variable  \$Caption_htmlspecialchars  looks like this:
";
    ECHO " $Caption_htmlspecialchars
";
    ECHO "But in the input box, \$Caption_htmlspecialchars is truncated by a single quote:
";
    // ETA: Bad old line that caused the problem, now commented:
    // ECHO "<input type='text' name='Caption_htmlspecialchars' size=100 value='$Caption_htmlspecialchars' maxlength = 100 required />

";
    // ETA: Newly added line that fixes the problem:
echo '<input type="text" name="Caption_htmlspecialchars" size=100 value="'.$Caption_htmlspecialchars.'" maxlength = 100 required />

';
    // SUBMIT button.  Submits back to the same page: input_box.php
    echo "<input type='Submit' name='submit' value='Submit'/>

";
    ?>

Here is what Inspect Elements > Elements shows for the input element:

 input_box_SO.php
The echo of the variable  $Caption_htmlspecialchars  looks like this:
 test with special chars. & " < > and a single quote ('), which causes truncation in the input box.
But in the input box, $Caption_htmlspecialchars is truncated by a single quote:
 and a single quote (" ),="" which="" causes="" truncation="" in="" the="" input="" box.="" '="" maxlength="100" required="">

With the Source looking like this:  value='test with special chars. & " < > and a single quote ('), which causes truncation in the input box. '


问:
How to do circular crop using matlab?
I usually use imcrop to crop rectanguler image but i wat to create circular crop. How to do it?

I know there is another quetion about this, here the link:

MATLAB: how do I crop out a circle from an image

```<code>[xx,yy] = ndgrid((1:imageSize(1))-ci(1),(1:imageSize(2))-ci(2));
mask = (xx.^2 + yy.^2)<ci(3)^2;
</code>```

and the result of imshow(mask) is rectangle with white background

Cropping Circular region of interest around a point in MATLAB

error in roimaskcc

http://www.mathworks.com/matlabcentral/newsreader/view_thread/242489

```<code>[xx,yy]=ndgrid(1:size(X,1), 1:size(X,2));
CroppingMask= ( (xx-Xcenter).^2+(yy-Ycenter).^2<=Radius^2 );
X=X.*CroppingMask;
</code>```

The result of imshow(CroppingMask) is a rectangle with black background with small white circular at the center of the rectangle. When I run line 3 it shows an error.

Please help me, step by step because I'm a beginner.

Here is my image: https://www.dropbox.com/s/5plqzqgyb1ej6gh/patricia.jpg. It resolution is 480x640.

答:
```<code>I = imread('patricia.jpg');
imageSize = size(I);
ci = [250, 300, 100];     % center and radius of circle ([c_row, c_col, r])
[xx,yy] = ndgrid((1:imageSize(1))-ci(1),(1:imageSize(2))-ci(2));
mask = uint8((xx.^2 + yy.^2)<ci(3)^2);
croppedImage = uint8(zeros(size(I)));
croppedImage(:,:,1) = I(:,:,1).*mask;
imshow(croppedImage);
</code>```

Title: How to do circular crop using matlab?

Body:
I usually use imcrop to crop rectanguler image but i wat to create circular crop. How to do it?

I know there is another quetion about this, here the link:

MATLAB: how do I crop out a circle from an image

[xx,yy] = ndgrid((1:imageSize(1))-ci(1),(1:imageSize(2))-ci(2));
mask = (xx.^2 + yy.^2)<ci(3)^2;

and the result of imshow(mask) is rectangle with white background

Cropping Circular region of interest around a point in MATLAB

error in roimaskcc

http://www.mathworks.com/matlabcentral/newsreader/view_thread/242489

[xx,yy]=ndgrid(1:size(X,1), 1:size(X,2));
CroppingMask= ( (xx-Xcenter).^2+(yy-Ycenter).^2<=Radius^2 );
X=X.*CroppingMask;

The result of imshow(CroppingMask) is a rectangle with black background with small white circular at the center of the rectangle. When I run line 3 it shows an error.

Please help me, step by step because I'm a beginner.

Here is my image: https://www.dropbox.com/s/5plqzqgyb1ej6gh/patricia.jpg. It resolution is 480x640.


问:
Jenkins multi branch project and Github webhooks
Looks like I'm missing something.

I set up multibrunch jon in Jenkins with SCM like git@github.someorg.com/repo.git It scanned all current branches.

Then I set up web hook in Github with URL http://jenkins.someorg.com/github-webhook/ for all events.

Github shows that event has been successfully sent.
Jenkins log shows that events has bees received.

```<code>Received PUSH for https://github.someorg.com/repo from IP ⇒ http://jenkins.someorg.com/github-webhook/
</code>```

But nothing happens on the Jenkins job itself...

答:
Double-check "Setting up a GitHub webhook in Jenkins"

You need to make sure your Build Trigger is set to  “Build when a change is pushed to GitHub”, with of course a GitHub repo url ;)

And Jenkins should have an SSH key already associated with the desired GitHub project.

Body:
Looks like I'm missing something.

I set up multibrunch jon in Jenkins with SCM like git@github.someorg.com/repo.git It scanned all current branches.

Then I set up web hook in Github with URL http://jenkins.someorg.com/github-webhook/ for all events.

Github shows that event has been successfully sent.
Jenkins log shows that events has bees received.

Received PUSH for https://github.someorg.com/repo from IP ⇒ http://jenkins.someorg.com/github-webhook/

But nothing happens on the Jenkins job itself...


问:
Toggle button not toggling for the first time
My app is simple: one button with one state toggleButton. In constructor toggleButton is set to the default value false. When I press the button, the app will start record some sensors and console.log their data to the chrome debugger screen.

```<code>constructor(props) {
    super(props);
    this.state = {
      toggleButton: false
    };
}

recordSensors() {
    let toggleButton = !this.state.toggleButton;
    this.setState({ toggleButton });

    if (this.state.toggleButton) {
        // start & record some sensors data
    } else {
        // stop recording
    }
}

render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={styles.toggleButton}
          onPress={() => this.recordSensors()}
        >
          <Text style={styles.buttonText}>
            {this.state.toggleButton ? 'Stop' : 'Start'}
          </Text>
        </TouchableOpacity>
        <Text>
          {this.state.toggleButton ? 'Recording...' : null}
        </Text>
      </View>
    );
  }
</code>```

The weird thing is, the first time I press the button, its text changed to Stop and the Recording... text appeared but the app didn't record sensors data. When I press the button again (the second time), then it now records.

But if I change if (this.state.toggleButton) to if (toggleButton) then it works fine. I can't understand the logic of it anymore. Can you guys help?

答:
You are using

```<code> let toggleButton = !this.state.toggleButton;
</code>```

Where toggleButton has inverse value of this.state.toggleButton

And, say if, this.state.toggleButton is false then toggleButton will have true as its value. So, the condition you are specifying is totally different here

```<code> if (this.state.toggleButton)   //if(false)
</code>```

And when you do

```<code>if(toggleButton)  //if(true)
</code>```

So, notice that condition when you have this.state.toggleButton as false or vice-versa

Body:
My app is simple: one button with one state toggleButton. In constructor toggleButton is set to the default value false. When I press the button, the app will start record some sensors and console.log their data to the chrome debugger screen.

constructor(props) {
    super(props);
    this.state = {
      toggleButton: false
    };
}

recordSensors() {
    let toggleButton = !this.state.toggleButton;
    this.setState({ toggleButton });

    if (this.state.toggleButton) {
        // start & record some sensors data
    } else {
        // stop recording
    }
}

render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity
          style={styles.toggleButton}
          onPress={() => this.recordSensors()}
        >
          <Text style={styles.buttonText}>
            {this.state.toggleButton ? 'Stop' : 'Start'}
          </Text>
        </TouchableOpacity>
        <Text>
          {this.state.toggleButton ? 'Recording...' : null}
        </Text>
      </View>
    );
  }

The weird thing is, the first time I press the button, its text changed to Stop and the Recording... text appeared but the app didn't record sensors data. When I press the button again (the second time), then it now records.

But if I change if (this.state.toggleButton) to if (toggleButton) then it works fine. I can't understand the logic of it anymore. Can you guys help?

Body:
You are using

 let toggleButton = !this.state.toggleButton;

Where toggleButton has inverse value of this.state.toggleButton

And, say if, this.state.toggleButton is false then toggleButton will have true as its value. So, the condition you are specifying is totally different here

 if (this.state.toggleButton)   //if(false)

And when you do

if(toggleButton)  //if(true)

So, notice that condition when you have this.state.toggleButton as false or vice-versa


问:
Delphi 2010: how do I convert a UTF8-encoded PAnsiChar to a UnicodeString?
The situation:  I’ve an external DLL that uses UTF-8 as its internal string format.  The interface functions all use PAnsiChar to pass strings along.

The rest of my application uses Delphi’s native string type; since I’m working with Delphi 2010, that will map to a UnicodeString.

How can I reliably cast those PAnsiChar arguments (which are pointing to UTF-8 encoded strings) to a UnicodeString?

I had this function, which I thought worked fine:

```<code>function PUTF8CharToString(Text: PAnsiChar): string;
var
  UText: UTF8String;
begin
  UText := UTF8String(Text);
  Result := string(UText);
end;
</code>```

...but now I’ve run into a case where the result string is corrupted; when I save the PAnsiChar to file, it’s fine; but when I save the resulting string after conversion using the above function, it’s corrupted.

Or should this work correctly, and is this indicative of some other memory (de)allocation problem?

Edit: I finally managed to get rid of the memory corruption by assigning the converted string to a local variable string, instead of directly passing it to another function.

答:
Try using SetString() instead of casting:</p>

```<code>function PUTF8CharToString(Text: PAnsiChar): string;
var
  UText: UTF8String;
begin
  SetString(UText, Text, StrLen(Text));
  Result := UText;
end;
</code>```

Body:
The situation:  I’ve an external DLL that uses UTF-8 as its internal string format.  The interface functions all use PAnsiChar to pass strings along.

The rest of my application uses Delphi’s native string type; since I’m working with Delphi 2010, that will map to a UnicodeString.

How can I reliably cast those PAnsiChar arguments (which are pointing to UTF-8 encoded strings) to a UnicodeString?

I had this function, which I thought worked fine:

function PUTF8CharToString(Text: PAnsiChar): string;
var
  UText: UTF8String;
begin
  UText := UTF8String(Text);
  Result := string(UText);
end;

...but now I’ve run into a case where the result string is corrupted; when I save the PAnsiChar to file, it’s fine; but when I save the resulting string after conversion using the above function, it’s corrupted.

Or should this work correctly, and is this indicative of some other memory (de)allocation problem?

Edit: I finally managed to get rid of the memory corruption by assigning the converted string to a local variable string, instead of directly passing it to another function.

Body:
Try using SetString() instead of casting:

function PUTF8CharToString(Text: PAnsiChar): string;
var
  UText: UTF8String;
begin
  SetString(UText, Text, StrLen(Text));
  Result := UText;
end;


问:
How to get all folders name of gmail using ImapX lib? C#
How to get all folders name of gmail using ImapX lib?
I read in http://hellowebapps.com/2010-02-09/imapx-net-library-to-manage-imap-folders/ but not found get all folder part.</p>

答:
Here's how:</p>

```<code>        public List<string> getMailboxes(string emailAddress, string emailPassword)
    {
        var client = new ImapClient("imap.gmail.com", 993, true, true);
        if (client.Connect())
        {
            if (client.Login(emailAddress, emailPassword))
            {
                //get all parent folers
                var folders = client.Folders;

                foreach (var parentFolder in folders)
                {
                    //get parent folder path
                    var parentPath = parentFolder.Path;

                    //check if every parent folder has subfolder
                    if (parentFolder.HasChildren)
                    {
                        var subfolders = parentFolder.SubFolders;
                        foreach(var subfolder in subfolders)
                        {
                            var subPath = subfolder.Path;
                        }
                    }
                }
            }
        }
    }
</code>```

Body:
Here's how:

        public List<string> getMailboxes(string emailAddress, string emailPassword)
    {
        var client = new ImapClient("imap.gmail.com", 993, true, true);
        if (client.Connect())
        {
            if (client.Login(emailAddress, emailPassword))
            {
                //get all parent folers
                var folders = client.Folders;

                foreach (var parentFolder in folders)
                {
                    //get parent folder path
                    var parentPath = parentFolder.Path;

                    //check if every parent folder has subfolder
                    if (parentFolder.HasChildren)
                    {
                        var subfolders = parentFolder.SubFolders;
                        foreach(var subfolder in subfolders)
                        {
                            var subPath = subfolder.Path;
                        }
                    }
                }
            }
        }
    }


问:
A better method to implement the alpha synapse function in MATLAB
I have implemented a leaky integrate and fire neuron system that gives output in the form of an alpha function alpha = t/tau * exp(1 - (t/tau)). However, the piece of code that I use to implement it takes up atleast 80% of the runtime (approximately 4s out of the total 5s). During the course of the program this prt gets called at least 30000 times while the computealphasynapseoutput function gets called at least 1.5 million times. So I want to reduce the runtime of this part. I have tried using arrayfun to implement it but that takes up a lot more time than this.

Can anyone suggest a more efficient implementation for this code??

To implement the alpha synapse I used the following piece of code:

```<code>% Get the identity of the currently active neurons
idAllActiveNeuron = idAllActiveNeuron > 0;
if any(idAllActiveNeuron) % Only run if atleast one neuron is active
    for iActiveNeuron = find(idAllActiveNeuron).' % run for each active neuron
        %% synapticOutputArray stores the synaptic output for each neuron for each time instant
        %% iIntegration is the time instant
        %% spikeTimesArray is a cell array that is composed of spike times for
        % each neuron. So if I have 5 neurons and neuron 4 spikes twice
        % while neuron 5 spikes once, spikeTimesArray would be something
        % like {[], [], [], [0.0023, 0.0034], [0.0675]}
        %% integrationInstant would be a time value like 0.0810
        %% tau_syn stores the value of tau for each neuron

        synapticOutputArray(iActiveNeuron, iIntegration) = computealphasynapseoutput(spikeTimesArray{iActiveNeuron}, integrationInstant, tau_syn(iActiveNeuron));

    end % iActiveNeuron
end
</code>```

The function computealphasynapse is implemented as follows:

```<code>function synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%%COMPUTEALPHASYNAPSEOUTPUT Calculates the synaptic output over all
%previous spikes of the neuron at a particular time instant using the
%alpha synapse function
%
% Usage:
%   synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%
% Inputs:
%           firingTime: vector of previous firing times (in seconds)
%   integrationInstant: current integration time instant (in seconds)
%               tauSyn: synaptic time constant of the neuron (in seconds)
%
% Output:
%   synapticOutput: Synaptic output of the neuron at current time summed
%                   over all firing instances
%

% Calculate the time difference of firing from current time
timeDifference = (integrationInstant - firingTime) / tauSyn;
% Calculate and sum the synaptic output for each spike
synapticOutput = sum(timeDifference .* exp(1 - timeDifference));

end % computealphasynapseoutput
</code>```

Edit:

I have finally awarded the bounty for this question to gnovice
  for his awesome answer. It helped me to shave off an entire 40 seconds
  from my simulation time (from 68 to 28 s). I hope it works for people
  in the future too. I would also like to acknowledge MrAzzaman and
  qbzenker for taking their time to answer the question and
  teaching me some cool new approaches. Also, others who commented and
  helped me. Thanks

答:
I tested the following code with a set of randomly produced firing times and taus, and it consistently ran about 7-8x faster. It's a bit strange, but bear with me.

The main idea is that MATLAB excels at operations on matrices, but can be pretty slow if you have to break those operations up, for instance with your for loop. The idea, then, is to try and do the whole cell array in one go. This would be easier if you could modify how the firing times are stored (i.e., not in a cell array), but I've made do with what you've got.

Basically, what we're going to do is convert the cell array of firing times to one big vector, calculate the synaptic output for all of them at once, then sum them according to their neuron. So, for instance, we'll eventually get the following:

```<code>% given spikeTimesArray = {[], [], [], [0.0023, 0.0034], [0.0675],...}
firingTimes = [0.0023, 0.0034, 0.0675,...];
neuronInd = [4,4,5,...];
</code>```

where the neuronInd vector is the corresponding neuron index of each firing time. This is the vector that, if you could create it when your firing times array was created, this whole process would be that much quicker. As it is, the process to calculate neuronInd is a bit opaque.

Regardless, we calculate this as follows:

```<code>% Calculate the number of time spikes for each neuron
numSpikes = cellfun(@numel,spikeTimesArray);
% Determine the index of all neurons with spikes
n = find(numSpikes);
% Calculate the starting indices for the neuronInd vector
m = cumsum([1,numSpikes]);
% Generate the neuronInd vector
neuronInd = interp1(m(n),n,1:(m(end)-1),'previous');
% Messy kludge to get around how interp1 works
neuronInd(isnan(neuronInd)) = n(end);
%Calculate timeDifference
delt = ([spikeTimesArray{:}] - integratonInstant)./tau_syn(neuronInd);
synapticOutputArray(:, iIntegration) = accumarray(neuronInd',delt.*exp(1-delt));
</code>```

Hope this helps.

Body:
I have implemented a leaky integrate and fire neuron system that gives output in the form of an alpha function alpha = t/tau * exp(1 - (t/tau)). However, the piece of code that I use to implement it takes up atleast 80% of the runtime (approximately 4s out of the total 5s). During the course of the program this prt gets called at least 30000 times while the computealphasynapseoutput function gets called at least 1.5 million times. So I want to reduce the runtime of this part. I have tried using arrayfun to implement it but that takes up a lot more time than this.

Can anyone suggest a more efficient implementation for this code??

To implement the alpha synapse I used the following piece of code:

% Get the identity of the currently active neurons
idAllActiveNeuron = idAllActiveNeuron > 0;
if any(idAllActiveNeuron) % Only run if atleast one neuron is active
    for iActiveNeuron = find(idAllActiveNeuron).' % run for each active neuron
        %% synapticOutputArray stores the synaptic output for each neuron for each time instant
        %% iIntegration is the time instant
        %% spikeTimesArray is a cell array that is composed of spike times for
        % each neuron. So if I have 5 neurons and neuron 4 spikes twice
        % while neuron 5 spikes once, spikeTimesArray would be something
        % like {[], [], [], [0.0023, 0.0034], [0.0675]}
        %% integrationInstant would be a time value like 0.0810
        %% tau_syn stores the value of tau for each neuron

        synapticOutputArray(iActiveNeuron, iIntegration) = computealphasynapseoutput(spikeTimesArray{iActiveNeuron}, integrationInstant, tau_syn(iActiveNeuron));

    end % iActiveNeuron
end

The function computealphasynapse is implemented as follows:

function synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%%COMPUTEALPHASYNAPSEOUTPUT Calculates the synaptic output over all
%previous spikes of the neuron at a particular time instant using the
%alpha synapse function
%
% Usage:
%   synapticOutput = computealphasynapseoutput(firingTime, integrationInstant, tauSyn)
%
% Inputs:
%           firingTime: vector of previous firing times (in seconds)
%   integrationInstant: current integration time instant (in seconds)
%               tauSyn: synaptic time constant of the neuron (in seconds)
%
% Output:
%   synapticOutput: Synaptic output of the neuron at current time summed
%                   over all firing instances
%

% Calculate the time difference of firing from current time
timeDifference = (integrationInstant - firingTime) / tauSyn;
% Calculate and sum the synaptic output for each spike
synapticOutput = sum(timeDifference .* exp(1 - timeDifference));

end % computealphasynapseoutput

Edit:

I have finally awarded the bounty for this question to gnovice
  for his awesome answer. It helped me to shave off an entire 40 seconds
  from my simulation time (from 68 to 28 s). I hope it works for people
  in the future too. I would also like to acknowledge MrAzzaman and
  qbzenker for taking their time to answer the question and
  teaching me some cool new approaches. Also, others who commented and
  helped me. Thanks

Body:
I tested the following code with a set of randomly produced firing times and taus, and it consistently ran about 7-8x faster. It's a bit strange, but bear with me.

The main idea is that MATLAB excels at operations on matrices, but can be pretty slow if you have to break those operations up, for instance with your for loop. The idea, then, is to try and do the whole cell array in one go. This would be easier if you could modify how the firing times are stored (i.e., not in a cell array), but I've made do with what you've got.

Basically, what we're going to do is convert the cell array of firing times to one big vector, calculate the synaptic output for all of them at once, then sum them according to their neuron. So, for instance, we'll eventually get the following:

% given spikeTimesArray = {[], [], [], [0.0023, 0.0034], [0.0675],...}
firingTimes = [0.0023, 0.0034, 0.0675,...];
neuronInd = [4,4,5,...];

where the neuronInd vector is the corresponding neuron index of each firing time. This is the vector that, if you could create it when your firing times array was created, this whole process would be that much quicker. As it is, the process to calculate neuronInd is a bit opaque.

Regardless, we calculate this as follows:

% Calculate the number of time spikes for each neuron
numSpikes = cellfun(@numel,spikeTimesArray);
% Determine the index of all neurons with spikes
n = find(numSpikes);
% Calculate the starting indices for the neuronInd vector
m = cumsum([1,numSpikes]);
% Generate the neuronInd vector
neuronInd = interp1(m(n),n,1:(m(end)-1),'previous');
% Messy kludge to get around how interp1 works
neuronInd(isnan(neuronInd)) = n(end);
%Calculate timeDifference
delt = ([spikeTimesArray{:}] - integratonInstant)./tau_syn(neuronInd);
synapticOutputArray(:, iIntegration) = accumarray(neuronInd',delt.*exp(1-delt));

Hope this helps.


问:
Syntax error in PHP login page query
I am trying to make a PHP login page that checks weather the user entered details are in the database but it returns the following error:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access
      violation: 1064 You have an error in your SQL syntax; check the manual that
      corresponds to your MariaDB server version for the right syntax to use near
      'SLEECT * FROM users where username = NULL AND password = NULL' at line 1 in
      C:\xampp\htdocs\sign\login.php:18 Stack trace: #0
      C:\xampp\htdocs\sign\login.php(18): PDOStatement->execute() #1

      C:\xampp\htdocs\sign\login.php(31): SignIn() #2 {main} thrown in
      C:\xampp\htdocs\sign\login.php on line 18

What am I doing wrong and how can I fix it?

```<code><?php
include('connection.php');
$username =$_POST['username'];
$password = $_POST['password'];
if($username == '') {
$errmsg_arr[] = 'You must enter your Username';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
function SignIn(){
global $connection;
$search = $connection->prepare("SLEECT * FROM users where username =
:username AND password = :password");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$result = $search->execute();
$count = $result->rowcount();
if($count> 0)
{
    $_SESSION['username'] = $_POST['username'];
    echo "welcom to the page ";
}
else{
    echo "wron email or password";
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>
</code>```

the code written in connection.php is

```<code><?php
try{
$connection = new PDO('mysql:host=localhost;dbname=signup;charset=utf8mb4',
'root', '');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $err){
echo $err->getMessage();
die();
}
?>
</code>```

the HTML code written is

```<code><html>
<body>
<form method="POST" action="login.php">
<b>Enter your username: </b><br>
<input type="text" name="username"><br>
<b>Enter your password: </b><br>
<input type="password" name ="password"><br>
<input type="submit" name="submit">
</form>
</body>
</html>
</code>```

答:
1ST : SLEECT spelling is SELECT

2ND : Follow the dolly aswin suggested steps .

```<code>if(isset($_POST['submit']))
{
    ......
}
</code>```

3RD : rowcount() should be rowCount() . c should be caps.

4TH :   you need to get the rowcount from statement .not from Boolean value $result only contains Boolean value true or false

```<code> $count = $result->rowCount();
</code>```

change to

```<code>$count = $search->rowCount();
</code>```

Title: Syntax error in PHP login page query

Body:
I am trying to make a PHP login page that checks weather the user entered details are in the database but it returns the following error:

Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access
      violation: 1064 You have an error in your SQL syntax; check the manual that
      corresponds to your MariaDB server version for the right syntax to use near
      'SLEECT * FROM users where username = NULL AND password = NULL' at line 1 in
      C:\xampp\htdocs\sign\login.php:18 Stack trace: #0
      C:\xampp\htdocs\sign\login.php(18): PDOStatement->execute() #1

      C:\xampp\htdocs\sign\login.php(31): SignIn() #2 {main} thrown in
      C:\xampp\htdocs\sign\login.php on line 18

What am I doing wrong and how can I fix it?

<?php
include('connection.php');
$username =$_POST['username'];
$password = $_POST['password'];
if($username == '') {
$errmsg_arr[] = 'You must enter your Username';
$errflag = true;
}
if($password == '') {
$errmsg_arr[] = 'You must enter your Password';
$errflag = true;
}
function SignIn(){
global $connection;
$search = $connection->prepare("SLEECT * FROM users where username =
:username AND password = :password");
$search->bindParam(':username',$username);
$search->bindParam(':password',$password);
$result = $search->execute();
$count = $result->rowcount();
if($count> 0)
{
    $_SESSION['username'] = $_POST['username'];
    echo "welcom to the page ";
}
else{
    echo "wron email or password";
}
}
if(isset($_POST['submit']))
{
SignIn();
}
?>

the code written in connection.php is

<?php
try{
$connection = new PDO('mysql:host=localhost;dbname=signup;charset=utf8mb4',
'root', '');
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $err){
echo $err->getMessage();
die();
}
?>

the HTML code written is

<form method="POST" action="login.php">
Enter your username:

<input type="text" name="username">

Enter your password:

<input type="password" name ="password">

<input type="submit" name="submit">
</form>

Body:
1ST : SLEECT spelling is SELECT

2ND : Follow the dolly aswin suggested steps .

if(isset($_POST['submit']))
{
    ......
}

3RD : rowcount() should be rowCount() . c should be caps.

4TH :   you need to get the rowcount from statement .not from Boolean value $result only contains Boolean value true or false

 $count = $result->rowCount();

change to

$count = $search->rowCount();


问:
Laravel 5.4 - Method paginate does not exist. - Multiple relation filter and orderby count
i have this situation in my db:

projects = id | title | slug

products = id | project_id | category_id

likes = id | project_id | user_id

I would like get all products with a specific "category_id", with "status" pubblished and order by project's likes (paginate for 21 products).

```<code>$products = Product::where('category_id', $category->id)->where('status','published')->with('project')->get()->sortBy(function($product)
        {
            return $product->project->like->count();
        })->paginate(21);
</code>```

Without "->paginate(21)" work well, so i get this error:

BadMethodCallException in Macroable.php line 74: Method paginate does
  not exist.

答:
remove get() from this and try

```<code>$products = Product::where('category_id', $category->id)->where('status','published')->with('project')->sortBy(function($product)
        {
            return $product->project->like->count();
        })->paginate(21);
</code>```

Body:
i have this situation in my db:

projects = id | title | slug

products = id | project_id | category_id

likes = id | project_id | user_id

I would like get all products with a specific "category_id", with "status" pubblished and order by project's likes (paginate for 21 products).

$products = Product::where('category_id', $category->id)->where('status','published')->with('project')->get()->sortBy(function($product)
        {
            return $product->project->like->count();
        })->paginate(21);

Without "->paginate(21)" work well, so i get this error:

BadMethodCallException in Macroable.php line 74: Method paginate does
  not exist.

Body:
remove get() from this and try

$products = Product::where('category_id', $category->id)->where('status','published')->with('project')->sortBy(function($product)
        {
            return $product->project->like->count();
        })->paginate(21);