问:
UNET - Object is synced over network but text component isn't
Hi so I'm trying to make chat for a multiplayer game and I've gotten the message prefabs to instantiate on all clients and the host, so that works fine. Only issue is the text doesnt change, it stays as the default. Here is the code I have:

ChatManager.cs:

```<code>using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class ChatManager : NetworkBehaviour
{
    [SerializeField] private GameObject chat;
    [SerializeField] private GameObject chatItemPrefab;
    [HideInInspector] public List<ChatItem> messages;

    public float messageExpireTime = 5;

    public static ChatManager instance;

    void Awake()
    {
        instance = this;
    }

    public void ChatSendMessage(string sender, string message)
    {
        CmdChatSendMessage(sender, message);
    }

    [Command]
    void CmdChatSendMessage(string sender, string message)
    {
        GameObject chatItem = Instantiate(chatItemPrefab);
        chatItem.transform.SetParent(chat.transform);
        ChatItem messageSettings = chatItem.GetComponent<ChatItem>();
        messageSettings.Setup(sender, message);
        messageSettings.chatNetId = chat.GetComponent<NetworkIdentity>().netId;
        NetworkServer.Spawn(chatItem);
        StartCoroutine(WaitForExpire(chatItem));
    }

    public IEnumerator WaitForExpire(GameObject chatItem)
    {
        yield return new WaitForSeconds(messageExpireTime);
        CmdDestroyChatMessage(chatItem);
    }

    [Command]
    void CmdDestroyChatMessage(GameObject chatItem)
    {
        NetworkServer.Destroy(chatItem);
    }
}
</code>```

ChatItem.cs:

```<code>using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Networking;

public class ChatItem : NetworkBehaviour
{
    [SerializeField] private Text senderText;
    [SerializeField] private Text messageText;
    [SyncVar] public NetworkInstanceId chatNetId;

    [SyncVar] public string sender;
    [SyncVar] public string message;

    void Start()
    {
        GameObject chatParent = ClientScene.FindLocalObject(chatNetId);
        transform.SetParent(chatParent.transform);
    }

    public void Setup(string sender, string message)
    {
        senderText.text = string.Format("[{0}]:", sender);
        messageText.text = message;
        this.sender = sender;
        this.message = message;
    }
}
</code>```

If "ChatSendMessage" is called with the paremeters "Server" and "hello!" on the host:

The host sees:

But the client sees:

which is the default text..

What is the issue I'm dealing with. Any ideas? Thanks

答:
FIXED - I set the text in the start method as well so if you're the person sending, it gets overwritten by the setup method but if you're a remote client, where setup is never run, you can just set the text from the syncvar which was already set from the setup method on the person sending's client. e.g.</p>

```<code>void Start()
{
    GameObject chatParent = ClientScene.FindLocalObject(chatNetId);
    transform.SetParent(chatParent.transform);
    senderText.text = string.Format("[{0}]:", sender);
    messageText.text = message;
}
</code>```

Body:
Hi so I'm trying to make chat for a multiplayer game and I've gotten the message prefabs to instantiate on all clients and the host, so that works fine. Only issue is the text doesnt change, it stays as the default. Here is the code I have:

ChatManager.cs:

using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class ChatManager : NetworkBehaviour
{
    [SerializeField] private GameObject chat;
    [SerializeField] private GameObject chatItemPrefab;
    [HideInInspector] public List<ChatItem> messages;

    public float messageExpireTime = 5;

    public static ChatManager instance;

    void Awake()
    {
        instance = this;
    }

    public void ChatSendMessage(string sender, string message)
    {
        CmdChatSendMessage(sender, message);
    }

    [Command]
    void CmdChatSendMessage(string sender, string message)
    {
        GameObject chatItem = Instantiate(chatItemPrefab);
        chatItem.transform.SetParent(chat.transform);
        ChatItem messageSettings = chatItem.GetComponent<ChatItem>();
        messageSettings.Setup(sender, message);
        messageSettings.chatNetId = chat.GetComponent<NetworkIdentity>().netId;
        NetworkServer.Spawn(chatItem);
        StartCoroutine(WaitForExpire(chatItem));
    }

    public IEnumerator WaitForExpire(GameObject chatItem)
    {
        yield return new WaitForSeconds(messageExpireTime);
        CmdDestroyChatMessage(chatItem);
    }

    [Command]
    void CmdDestroyChatMessage(GameObject chatItem)
    {
        NetworkServer.Destroy(chatItem);
    }
}

ChatItem.cs:

using UnityEngine.UI;
using UnityEngine;
using UnityEngine.Networking;

public class ChatItem : NetworkBehaviour
{
    [SerializeField] private Text senderText;
    [SerializeField] private Text messageText;
    [SyncVar] public NetworkInstanceId chatNetId;

    [SyncVar] public string sender;
    [SyncVar] public string message;

    void Start()
    {
        GameObject chatParent = ClientScene.FindLocalObject(chatNetId);
        transform.SetParent(chatParent.transform);
    }

    public void Setup(string sender, string message)
    {
        senderText.text = string.Format("[{0}]:", sender);
        messageText.text = message;
        this.sender = sender;
        this.message = message;
    }
}

If "ChatSendMessage" is called with the paremeters "Server" and "hello!" on the host:

The host sees:

But the client sees:

which is the default text..

What is the issue I'm dealing with. Any ideas? Thanks

Body:
FIXED - I set the text in the start method as well so if you're the person sending, it gets overwritten by the setup method but if you're a remote client, where setup is never run, you can just set the text from the syncvar which was already set from the setup method on the person sending's client. e.g.

void Start()
{
    GameObject chatParent = ClientScene.FindLocalObject(chatNetId);
    transform.SetParent(chatParent.transform);
    senderText.text = string.Format("[{0}]:", sender);
    messageText.text = message;
}


来源: stackexchange

问:
Is there already some std::vector based set/map implementation?
For small sets or maps, it's usually much faster to just use a sorted vector, instead of the tree-based set/map - especially for something like 5-10 elements. LLVM has some classes in that spirit, but no real adapter that would provide a std::map like interface backed up with a std::vector.

Any (free) implementation of this out there?

Edit: Thanks for all the alternative ideas, but I'm really interested in a vector based set/map. I do have specific cases where I tend to create huge amounts of sets/maps which contain usually less than 10 elements, and I do really want to have less memory pressure. Think about for example neighbor edges for a vertex in a triangle mesh, you easily wind up with 100k sets of 3-4 elements each.

答: I don't know any such implementation, but there are some functions that help working with sorted vectors already in STL, such as lower_bound and upper_bound.

OwnerDisplayName: Anteru

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Anteru


问:
Cleanly merge two arrays in ActionScript (3.0)?
What's a nice way to merge two sorted arrays in ActionScript (specifically ActionScript 3.0)?  The resulting array should be sorted and without duplicates.</p>

答:
```<code>function remDuplicates(_array:Array):void{
    for (var i:int = 0; i < _array.length;++i) {
        var index:int = _array.indexOf(_array[i]);
        if (index != -1 && index != i) {
            _array.splice(i--, 1);
        }
    }
}
</code>```

Then for the "merge" use concat.
exemple :

```<code>var testArray:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];
var testArray2:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];

testArray.concat(testArray2);
trace(testArray);
remDuplicates(testArray);
trace(testArray);
</code>```

OwnerDisplayName: mellis

Body:
function remDuplicates(_array:Array):void{
    for (var i:int = 0; i < _array.length;++i) {
        var index:int = _array.indexOf(_array[i]);
        if (index != -1 && index != i) {
            _array.splice(i--, 1);
        }
    }
}

Then for the "merge" use concat.
exemple :

var testArray:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];
var testArray2:Array = [1, 1, 1, 5, 4, 5, 5, 4, 7, 2, 3, 3, 6, 5, 8, 5, 4, 2, 4, 5, 1, 2, 3, 65, 5, 5, 5, 5, 8, 4, 7];

testArray.concat(testArray2);
trace(testArray);
remDuplicates(testArray);
trace(testArray);


问:
Android application keeps on stopping
I am new to android programming. I need an enlightenment on my android application. I don't know what's wrong but when I pressed my "calculate" button, it will stop working (crash). My program is about the FLAMES game where in you count each instance a character of a string intersects in another string. I am hoping to learn more, each help will be greatly appreciated. Thanks!

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

    Button button1 = (Button) findViewById(R.id.button);
    button1.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
         EditText edittext1 =  (EditText) findViewById(R.id.editText);
         final String name1 = edittext1.toString().replaceAll("\\s+","");
         EditText edittext2 = (EditText) findViewById(R.id.editText2);
         final String name2 = edittext2.toString().replaceAll("\\s+","");
         final TextView result = (TextView) findViewById(R.id.textView);

         int common = 0;
         int resultS = common % 6;

         if (name1.length() > name2.length()){

             for (int i = 0; i < name1.length(); i++) {
                 for (int j = 0; j < name2.length(); j++) {
                     if (name1.charAt(i) == name2.charAt(j)) {
                         common++;

                     }
                         result.setText(resultS);
                 }
             }

         }

         if(name2.length() > name1.length())
         {

             for (int i = 0; i < name2.length(); i++) {
                 for (int j = 0; j < name1.length(); j++) {
                     if (name2.charAt(i) == name1.charAt(j)) {
                         common++;

                     }
                     result.setText(resultS);

                 }

             }

         }

    }
});
</code>```

Logcat:

```<code>07-09 14:53:06.852 8302-8302/com.example.genesis.flames E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.example.genesis.flames, PID: 8302
                                                                      android.content.res.Resources$NotFoundException: String resource ID #0x0
                                                                          at android.content.res.Resources.getText(Resources.java:338)
                                                                          at android.widget.TextView.setText(TextView.java:5480)
                                                                          at com.example.genesis.flames.MainActivity$1.onClick(MainActivity.java:56)
                                                                          at android.view.View.performClick(View.java:6219)
                                                                          at android.view.View$PerformClick.run(View.java:24482)
                                                                          at android.os.Handler.handleCallback(Handler.java:769)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                          at android.os.Looper.loop(Looper.java:164)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

答:
```<code>  result.setText(String.valueOf(resultS));
</code>```

because of textview expecting a string and you send the parameter as integer
also result.setText(""+resultS); should work (this one is not tested)

ContentLicense: CC BY-SA 3.0

Title: Android application keeps on stopping

Body:
I am new to android programming. I need an enlightenment on my android application. I don't know what's wrong but when I pressed my "calculate" button, it will stop working (crash). My program is about the FLAMES game where in you count each instance a character of a string intersects in another string. I am hoping to learn more, each help will be greatly appreciated. Thanks!

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

    Button button1 = (Button) findViewById(R.id.button);
    button1.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
         EditText edittext1 =  (EditText) findViewById(R.id.editText);
         final String name1 = edittext1.toString().replaceAll("\\s+","");
         EditText edittext2 = (EditText) findViewById(R.id.editText2);
         final String name2 = edittext2.toString().replaceAll("\\s+","");
         final TextView result = (TextView) findViewById(R.id.textView);

         int common = 0;
         int resultS = common % 6;

         if (name1.length() > name2.length()){

             for (int i = 0; i < name1.length(); i++) {
                 for (int j = 0; j < name2.length(); j++) {
                     if (name1.charAt(i) == name2.charAt(j)) {
                         common++;

                     }
                         result.setText(resultS);
                 }
             }

         }

         if(name2.length() > name1.length())
         {

             for (int i = 0; i < name2.length(); i++) {
                 for (int j = 0; j < name1.length(); j++) {
                     if (name2.charAt(i) == name1.charAt(j)) {
                         common++;

                     }
                     result.setText(resultS);

                 }

             }

         }

    }
});

Logcat:

07-09 14:53:06.852 8302-8302/com.example.genesis.flames E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: com.example.genesis.flames, PID: 8302
                                                                      android.content.res.Resources$NotFoundException: String resource ID #0x0
                                                                          at android.content.res.Resources.getText(Resources.java:338)
                                                                          at android.widget.TextView.setText(TextView.java:5480)
                                                                          at com.example.genesis.flames.MainActivity$1.onClick(MainActivity.java:56)
                                                                          at android.view.View.performClick(View.java:6219)
                                                                          at android.view.View$PerformClick.run(View.java:24482)
                                                                          at android.os.Handler.handleCallback(Handler.java:769)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                          at android.os.Looper.loop(Looper.java:164)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6540)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

Body:
  result.setText(String.valueOf(resultS));

because of textview expecting a string and you send the parameter as integer
also result.setText(""+resultS); should work (this one is not tested)


问:
How do I write the exception from printStackTrace() into a text file in Java?
I need to capture the exception in a text file in Java.  For example:

```<code>try {
  File f = new File("");
}
catch(FileNotFoundException f) {
  f.printStackTrace();  // instead of printing into console it should write into a text file
  writePrintStackTrace(f.getMessage()); // this is my own method where I store f.getMessage() into a text file.
}
</code>```

Using getMessage() works, but it only shows the error message.  I want all the information in the printStackTrace() including line numbers.

答:
Hope below example helps you-

```<code>package com.kodehelp.javaio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class PrintStackTraceToFile {
   public static void main(String[] args) {
      PrintStream ps= null;
      try {
          ps = new PrintStream(new File("/sample.log"));
          throw new FileNotFoundException("Sample Exception");
      } catch (FileNotFoundException e) {
        e.printStackTrace(ps);
      }
    }
}
</code>```

For more detail, refer to this link here

Body:
I need to capture the exception in a text file in Java.  For example:

try {
  File f = new File("");
}
catch(FileNotFoundException f) {
  f.printStackTrace();  // instead of printing into console it should write into a text file
  writePrintStackTrace(f.getMessage()); // this is my own method where I store f.getMessage() into a text file.
}

Using getMessage() works, but it only shows the error message.  I want all the information in the printStackTrace() including line numbers.

Body:
Hope below example helps you-

package com.kodehelp.javaio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

public class PrintStackTraceToFile {
   public static void main(String[] args) {
      PrintStream ps= null;
      try {
          ps = new PrintStream(new File("/sample.log"));
          throw new FileNotFoundException("Sample Exception");
      } catch (FileNotFoundException e) {
        e.printStackTrace(ps);
      }
    }
}

For more detail, refer to this link here

ContentLicense: CC BY-SA 4.0


问:
How to properly set width of a div within li
I'm trying to give my div inside a li a width value and the div's border has the width I want, but the text I have in that div is ignoring that width and it seems to be inheriting the container width. It's just the text that is doing that, though.

I don't usually work with li tags, so I don't really know what the problem is.

This is basically the HTML I'm working with:

           ...

```

<p>This is the CSS:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#container {
    margin:0 auto;
    width: 900px;
    height: 500px;
    box-sizing:border-box;
    position:relative;
    right: 160px;
    -webkit-user-select: none;
    user-select:none;
}

#container div.inner {
    position:relative;
    overflow:hidden;
    padding:0;
    margin:0;
}

#container div.inner ul {
    white-space:nowrap;
    position:relative;
    left:0; top:0;
    list-style:none;
    font-size:0;
    padding:0;
    margin:0;
    float:left!important;
    width:auto!important;
    height:auto!important;
}

#container ul li {
    display:inline-block;
    margin-top:20px;
    margin-bottom:200px;
    margin-left:-45px; margin-right:-30px;
    -webkit-transform:scale(0.6);
    transform:scale(0.6);
    -webkit-transition:-webkit-transform 0.5s;
    transition:transform 0.5s;
    box-sizing:content-box;
    text-align:center;
    vertical-align:middle;
    padding:0;
    position:relative;
    list-style:none;
    backface-visibility:hidden;

}

#container ul li.active {
    -webkit-transform:scale(1);
    transform:scale(1);
    background-color:transparent;
}

      #container ul li.active .desc {
      display: block;
}

      .desc {
    display: none;
    width: 310px!important;
    height: 200px;
    border: 1px solid #fff;
    position: relative;
    right: 350px;
    top: 275px;
    color: #fff;
    font-family: Arial;
    font-size: 11px;
    padding: 15px;
    text-align: justify;
      }

#container .img {
    width: 200px;
    height: 320px;
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center center;
    display:block;
    position:absolute;
    font-size:0;
    cursor:inherit;
    transition:all linear 0.4s;
}</code>```

答:
in your .desc {} is the second from the bottom padding: 15px;
Try deleting that one.

Body:
I'm trying to give my div inside a li a width value and the div's border has the width I want, but the text I have in that div is ignoring that width and it seems to be inheriting the container width. It's just the text that is doing that, though.

I don't usually work with li tags, so I don't really know what the problem is.

This is basically the HTML I'm working with:

           ...

This is the CSS:

#container {
    margin:0 auto;
    width: 900px;
    height: 500px;
    box-sizing:border-box;
    position:relative;
    right: 160px;
    -webkit-user-select: none;
    user-select:none;
}

#container div.inner {
    position:relative;
    overflow:hidden;
    padding:0;
    margin:0;
}

#container div.inner ul {
    white-space:nowrap;
    position:relative;
    left:0; top:0;
    list-style:none;
    font-size:0;
    padding:0;
    margin:0;
    float:left!important;
    width:auto!important;
    height:auto!important;
}

#container ul li {
    display:inline-block;
    margin-top:20px;
    margin-bottom:200px;
    margin-left:-45px; margin-right:-30px;
    -webkit-transform:scale(0.6);
    transform:scale(0.6);
    -webkit-transition:-webkit-transform 0.5s;
    transition:transform 0.5s;
    box-sizing:content-box;
    text-align:center;
    vertical-align:middle;
    padding:0;
    position:relative;
    list-style:none;
    backface-visibility:hidden;

}

#container ul li.active {
    -webkit-transform:scale(1);
    transform:scale(1);
    background-color:transparent;
}

      #container ul li.active .desc {
      display: block;
}

      .desc {
    display: none;
    width: 310px!important;
    height: 200px;
    border: 1px solid #fff;
    position: relative;
    right: 350px;
    top: 275px;
    color: #fff;
    font-family: Arial;
    font-size: 11px;
    padding: 15px;
    text-align: justify;
      }

#container .img {
    width: 200px;
    height: 320px;
    background-size:contain;
    background-repeat:no-repeat;
    background-position:center center;
    display:block;
    position:absolute;
    font-size:0;
    cursor:inherit;
    transition:all linear 0.4s;
}


问:
iPhone SDK CCCrypt 3DES and ECB mode always returns PARAM ERROR
I've seen quite a lot of posts about CCCrypt and 3DES on the iPhone at various places around the Net, but there does not seem to be a working example of using it with ECB mode, always with PKCS7Padding.

Does anyone have any working code to encrypt and decrypt a passed string using 3DES and ECB mode using the CCCrypt function?

Currently my code (which I admit came from a site somewhere, I think it was Apple's own developer forums) is as follows:

```<code>+ (NSString*)doCipher:(NSString*)plainText action:(CCOperation)encryptOrDecrypt {
 const void *vplainText;
 size_t plainTextBufferSize;

 if (encryptOrDecrypt == kCCDecrypt) {
  NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:plainText];
  plainTextBufferSize = [EncryptData length];
  vplainText = [EncryptData bytes];
 }
 else {
  //plainTextBufferSize = [plainText length];
  //vplainText = (const void *)[plainText UTF8String];

  NSData *plainTextData = [plainText dataUsingEncoding: NSUTF8StringEncoding];
  plainTextBufferSize = [plainTextData length];
  vplainText = [plainTextData bytes];
 }

 CCCryptorStatus ccStatus;
 uint8_t *bufferPtr = NULL;
 size_t bufferPtrSize = 0;
 size_t movedBytes = 0;
 // uint8_t ivkCCBlockSize3DES;

 bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
 bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
 memset((void *)bufferPtr, 0x0, bufferPtrSize);
 // memset((void *) iv, 0x0, (size_t) sizeof(iv));

 NSString *key = @"123456789012345678901234";
 NSString *initVec = @"init Vec";
 const void *vkey = (const void *)[key UTF8String];
 const void *vinitVec = (const void *)[initVec UTF8String];

 ccStatus = CCCrypt(encryptOrDecrypt,
        kCCAlgorithm3DES,
        kCCOptionECBMode,
        vkey, //"123456789012345678901234", //key
        kCCKeySize3DES,
        nil, //"init Vec", //iv,
        vplainText, //"Your Name", //plainText,
        plainTextBufferSize,
        (void *)bufferPtr,
        bufferPtrSize,
        &movedBytes);

 //if (ccStatus == kCCSuccess) NSLog(@"SUCCESS");
 /*else*/ if (ccStatus == kCCParamError) return @"PARAM ERROR";
 else if (ccStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
 else if (ccStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
 else if (ccStatus == kCCAlignmentError) return @"ALIGNMENT";
 else if (ccStatus == kCCDecodeError) return @"DECODE ERROR";
 else if (ccStatus == kCCUnimplemented) return @"UNIMPLEMENTED";

 NSString *result;

 if (encryptOrDecrypt == kCCDecrypt) {
  result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding] autorelease];
 }
 else {
  NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
  result = [myData base64EncodingWithLineLength:movedBytes];
 }

 return result; }
</code>```

The above ALWAYS fails with PARAM ERROR.

答:
The above code worked for me, with some changes. The changes are i decelare the moveBytes and bufferPtf as instance variable and did following chandge.

```<code>if (encryptOrDecrypt == kCCDecrypt) {
  plainTextBufferSize = movedBytes;
  vplainText = bufferPtr;
}
else {
  plainTextBufferSize = [plainText length];
  vplainText = (const void *)[plainText UTF8String];
}
</code>```

instead base64encoding use nsasciiencoding.

Body:
I've seen quite a lot of posts about CCCrypt and 3DES on the iPhone at various places around the Net, but there does not seem to be a working example of using it with ECB mode, always with PKCS7Padding.

Does anyone have any working code to encrypt and decrypt a passed string using 3DES and ECB mode using the CCCrypt function?

Currently my code (which I admit came from a site somewhere, I think it was Apple's own developer forums) is as follows:

+ (NSString*)doCipher:(NSString*)plainText action:(CCOperation)encryptOrDecrypt {
 const void *vplainText;
 size_t plainTextBufferSize;

 if (encryptOrDecrypt == kCCDecrypt) {
  NSData *EncryptData = [[NSData alloc] initWithBase64EncodedString:plainText];
  plainTextBufferSize = [EncryptData length];
  vplainText = [EncryptData bytes];
 }
 else {
  //plainTextBufferSize = [plainText length];
  //vplainText = (const void *)[plainText UTF8String];

  NSData *plainTextData = [plainText dataUsingEncoding: NSUTF8StringEncoding];
  plainTextBufferSize = [plainTextData length];
  vplainText = [plainTextData bytes];
 }

 CCCryptorStatus ccStatus;
 uint8_t *bufferPtr = NULL;
 size_t bufferPtrSize = 0;
 size_t movedBytes = 0;
 // uint8_t ivkCCBlockSize3DES;

 bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
 bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
 memset((void *)bufferPtr, 0x0, bufferPtrSize);
 // memset((void *) iv, 0x0, (size_t) sizeof(iv));

 NSString *key = @"123456789012345678901234";
 NSString *initVec = @"init Vec";
 const void *vkey = (const void *)[key UTF8String];
 const void *vinitVec = (const void *)[initVec UTF8String];

 ccStatus = CCCrypt(encryptOrDecrypt,
        kCCAlgorithm3DES,
        kCCOptionECBMode,
        vkey, //"123456789012345678901234", //key
        kCCKeySize3DES,
        nil, //"init Vec", //iv,
        vplainText, //"Your Name", //plainText,
        plainTextBufferSize,
        (void *)bufferPtr,
        bufferPtrSize,
        &movedBytes);

 //if (ccStatus == kCCSuccess) NSLog(@"SUCCESS");
 /*else*/ if (ccStatus == kCCParamError) return @"PARAM ERROR";
 else if (ccStatus == kCCBufferTooSmall) return @"BUFFER TOO SMALL";
 else if (ccStatus == kCCMemoryFailure) return @"MEMORY FAILURE";
 else if (ccStatus == kCCAlignmentError) return @"ALIGNMENT";
 else if (ccStatus == kCCDecodeError) return @"DECODE ERROR";
 else if (ccStatus == kCCUnimplemented) return @"UNIMPLEMENTED";

 NSString *result;

 if (encryptOrDecrypt == kCCDecrypt) {
  result = [[[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes] encoding:NSASCIIStringEncoding] autorelease];
 }
 else {
  NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
  result = [myData base64EncodingWithLineLength:movedBytes];
 }

 return result; }

The above ALWAYS fails with PARAM ERROR.

Body:
The above code worked for me, with some changes. The changes are i decelare the moveBytes and bufferPtf as instance variable and did following chandge.

if (encryptOrDecrypt == kCCDecrypt) {
  plainTextBufferSize = movedBytes;
  vplainText = bufferPtr;
}
else {
  plainTextBufferSize = [plainText length];
  vplainText = (const void *)[plainText UTF8String];
}

instead base64encoding use nsasciiencoding.


问:
Change UISearchBar Shap
I used UISearchBar in the project, but I can't change the view of it. I want to set border around the search bar.

Can I change UIsearchbar as the same as this image?

答:
If you have many custom search bar in different viewControllers. I used the correct answer and made custom class for searchBar. I used it in storyboard.

```<code>import UIKit

class CustomSearchBar: UISearchBar {

    func setup(){
        // set Search Bar tintColor.
        self.backgroundImage = UIImage()
        self.barTintColor = UIColor.white

        // Get UISearchBar UITextFiled
        guard let textSearchField = self.value(forKey: "_searchField") as? UITextField else {
            return
        }

        // set Search Bar texfield corder radius
        textSearchField.layer.cornerRadius = 6.0

        // set Search Bar texfield border colour and width
        textSearchField.layer.borderColor = UIColor("#446D95").cgColor
        textSearchField.layer.borderWidth = 1.0
        textSearchField.layer.masksToBounds = true
    }
}
</code>```

Only Call setup function in viewDidLoad of the viewController that you want to use the searchBar.

```<code>override func viewDidLoad(){
    searchBar.setup()
}
</code>```

Title: Change UISearchBar Shap

Body:
If you have many custom search bar in different viewControllers. I used the correct answer and made custom class for searchBar. I used it in storyboard.

import UIKit

class CustomSearchBar: UISearchBar {

    func setup(){
        // set Search Bar tintColor.
        self.backgroundImage = UIImage()
        self.barTintColor = UIColor.white

        // Get UISearchBar UITextFiled
        guard let textSearchField = self.value(forKey: "_searchField") as? UITextField else {
            return
        }

        // set Search Bar texfield corder radius
        textSearchField.layer.cornerRadius = 6.0

        // set Search Bar texfield border colour and width
        textSearchField.layer.borderColor = UIColor("#446D95").cgColor
        textSearchField.layer.borderWidth = 1.0
        textSearchField.layer.masksToBounds = true
    }
}

Only Call setup function in viewDidLoad of the viewController that you want to use the searchBar.

override func viewDidLoad(){
    searchBar.setup()
}


问:
Download images from google image search (python)
I am web scraping beginner.
I am firstly refer to https://www.youtube.com/watch?v=ZAUNEEtzsrg to download image with the specific tag(e.g. cat), and it works!
But I encountered new problem which only can download about 100 images, and this problem seems like "ajax" which only load the first page html and not load all. Therefore, it seem like we must simulate scroll down to download next 100 images or more.

My code: https://drive.google.com/file/d/0Bwjk-LKe_AohNk9CNXVQbGRxMHc/edit?usp=sharing

To sum up,the problems are following:

how to download all images in google image search by source code in python( Please give me some examples :) )

Have any web scraping technique I must need to know?

答:
For any questions about icrawler, you can raise an issue on Github, which may get faster response.

The number limit for google search results seems to be 1000. A work around is to define a date range like the following.

```<code>from datetime import date
from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(
    parser_threads=2,
    downloader_threads=4,
    storage={'root_dir': 'your_image_dir'})
google_crawler.crawl(
    keyword='sunny',
    max_num=1000,
    date_min=date(2014, 1, 1),
    date_max=date(2015, 1, 1))
google_crawler.crawl(
    keyword='sunny',
    max_num=1000,
    date_min=date(2015, 1, 1),
    date_max=date(2016, 1, 1))
</code>```

Body:
For any questions about icrawler, you can raise an issue on Github, which may get faster response.

The number limit for google search results seems to be 1000. A work around is to define a date range like the following.

from datetime import date
from icrawler.builtin import GoogleImageCrawler

google_crawler = GoogleImageCrawler(
    parser_threads=2,
    downloader_threads=4,
    storage={'root_dir': 'your_image_dir'})
google_crawler.crawl(
    keyword='sunny',
    max_num=1000,
    date_min=date(2014, 1, 1),
    date_max=date(2015, 1, 1))
google_crawler.crawl(
    keyword='sunny',
    max_num=1000,
    date_min=date(2015, 1, 1),
    date_max=date(2016, 1, 1))


问:
java.lang.NullPointerException in netbeans
i'm writing a bit of code and i keep getting this error, it's to do with where i call network.addstation

here's the code, there are other methods in the network method but i thought i'd just show one, but it appears when you call any method. any help would be much appreaciated. thanks.

```<code>public class MyNetworkReader implements NetworkReader {

    Network network = null;

    @Override
    public Network read(InputStream stream) {
        Scanner scan = null;
        scan = new Scanner(stream);
        while (scan.hasNext()) {
            String fromStation = scan.next();
            if (!fromStation.equalsIgnoreCase("connection:")) ;
            network.addStation(fromStation)
            System.out.println(fromStation);
        }
    }

    return network;
}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class MyNetwork implements Network {

    HashMap<String, ArrayList> stations = new HashMap<String, ArrayList>();

    public void addStation(String station) {
        stations.put(station, null);
    }
}
</code>```

答: As DragonLord said, it is not a source code issue. You will be able to tell because that should happen whenever you run any C++ code. I had the same problem. I did something slightly different than DragonLord, though. I set the output of the program to Project Properties>Run>Console Type and set it to Standard Output.</p>

Body:
i'm writing a bit of code and i keep getting this error, it's to do with where i call network.addstation

here's the code, there are other methods in the network method but i thought i'd just show one, but it appears when you call any method. any help would be much appreaciated. thanks.

public class MyNetworkReader implements NetworkReader {

    Network network = null;

    @Override
    public Network read(InputStream stream) {
        Scanner scan = null;
        scan = new Scanner(stream);
        while (scan.hasNext()) {
            String fromStation = scan.next();
            if (!fromStation.equalsIgnoreCase("connection:")) ;
            network.addStation(fromStation)
            System.out.println(fromStation);
        }
    }

    return network;
}

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;

public class MyNetwork implements Network {

    HashMap<String, ArrayList> stations = new HashMap<String, ArrayList>();

    public void addStation(String station) {
        stations.put(station, null);
    }
}


问:
Replace some accented letters from word in python
I'm trying to replace some accented letters from Portuguese words in Python.

```<code>accentedLetters = ['à', 'á', 'â', 'ã', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü']
letters         = ['a', 'a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u']
</code>```

So the accentedLetters will be replaced by the letter in the letters array.

In this way, my expected results are for example:

```<code>ação    => açao
frações => fraçoes
</code>```

How can I do that?

答:
Another simple option using regex:</p>

```<code>import re

def remove_accents(string):
    if type(string) is not unicode:
        string = unicode(string, encoding='utf-8')

    string = re.sub(u"[àáâãäå]", 'a', string)
    string = re.sub(u"[èéêë]", 'e', string)
    string = re.sub(u"[ìíîï]", 'i', string)
    string = re.sub(u"[òóôõö]", 'o', string)
    string = re.sub(u"[ùúûü]", 'u', string)
    string = re.sub(u"[ýÿ]", 'y', string)

    return string
</code>```

Body:
I'm trying to replace some accented letters from Portuguese words in Python.

accentedLetters = ['à', 'á', 'â', 'ã', 'é', 'ê', 'í', 'ó', 'ô', 'õ', 'ú', 'ü']
letters         = ['a', 'a', 'a', 'a', 'e', 'e', 'i', 'o', 'o', 'o', 'u', 'u']

So the accentedLetters will be replaced by the letter in the letters array.

In this way, my expected results are for example:

ação    => açao
frações => fraçoes

How can I do that?

Body:
Another simple option using regex:

import re

def remove_accents(string):
    if type(string) is not unicode:
        string = unicode(string, encoding='utf-8')

    string = re.sub(u"[àáâãäå]", 'a', string)
    string = re.sub(u"[èéêë]", 'e', string)
    string = re.sub(u"[ìíîï]", 'i', string)
    string = re.sub(u"[òóôõö]", 'o', string)
    string = re.sub(u"[ùúûü]", 'u', string)
    string = re.sub(u"[ýÿ]", 'y', string)

    return string


问:
Calling child_process with Node.js vs calling child process from C and creating a C++ bind to call from node.js
I would like to call pdftotext to extract the content of 100.000 files (and i need to be fast), so, which of these two implementations would be the fastest?

Implementation 1:

Create a child_process from node.js, for every extraction:

```<code>export default (file) => new Promise((resove, reject) => {
  const command = 'pdftotext'
  const args = ['-layout', '-enc', 'UTF-8', file, '-']
  const process = spawn(command, args)
  const stdout = []
  const stderr = []

  process.stdout.on('data', (data) => {
    stdout.push(data)
  })

  process.stderr.on('data', (data) => {
    stderr.push(data)
  })

  process.on('error', (error) => {
    if (error.code === 'ENOENT')
      error.message = 'pdftotext is not installed, so will be unable to extract the file content'
    reject(error)
  })

  process.on('close', () => {
    if (stderr.length)
      return reject(stderr.map(Error))
    resolve(stdout.join())
  })
}
</code>```

Implementation 2:

Create a child_process from C, and create a C++ binding to call from node.js

-- Without code because I'm still learning how to do it --

答: Most likely process invocation code will have nonessential impact on performance and the speed of document processing depends on pdftotext implementation and disk io. So I guess there is no point to bother with writing custom process launcher.</p>

Body:
I would like to call pdftotext to extract the content of 100.000 files (and i need to be fast), so, which of these two implementations would be the fastest?

Implementation 1:

Create a child_process from node.js, for every extraction:

export default (file) => new Promise((resove, reject) => {
  const command = 'pdftotext'
  const args = ['-layout', '-enc', 'UTF-8', file, '-']
  const process = spawn(command, args)
  const stdout = []
  const stderr = []

  process.stdout.on('data', (data) => {
    stdout.push(data)
  })

  process.stderr.on('data', (data) => {
    stderr.push(data)
  })

  process.on('error', (error) => {
    if (error.code === 'ENOENT')
      error.message = 'pdftotext is not installed, so will be unable to extract the file content'
    reject(error)
  })

  process.on('close', () => {
    if (stderr.length)
      return reject(stderr.map(Error))
    resolve(stdout.join())
  })
}

Implementation 2:

Create a child_process from C, and create a C++ binding to call from node.js

-- Without code because I'm still learning how to do it --


问:
Exception: Service 'voltService' wasn't found in the dependency injection container
I am trying to replicate the examples in the Volt tutorial here, using the basic example of phalcon here, so nothing complicated.

So I created this app/controllers/PostsControllers like this:

```<code><?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {
/*        $post = Post::findFirst();
        $menu = Menu::findFirst();*/

        $post = array("title"=>"The titre");
        $menu = "menu1";

        $this->view->show_navigation = true;
        $this->view->menu            = $menu;
        $this->view->title           = $post["title"];
        $this->view->post            = $post;

        // Or...

        $this->view->setVar('show_navigation', true);
        $this->view->setVar('menu',            $menu);
        $this->view->setVar('title',           $post["title"]);
        $this->view->setVar('post',            $post);
    }
}
</code>```

And its corresponding app/views/posts/index.phtml like this:

```<code>{# app/views/posts/show.phtml #}
<!DOCTYPE html>
<html>
    <head>
        <title>{{ title }} - An example blog</title>
    </head>
    <body>

        {% if show_navigation %}
            <ul id='navigation'>
                {% for item in menu %}
                    <li>
                        <a href='{{ item.href }}'>
                            {{ item.caption }}
                        </a>
                    </li>
                {% endfor %}
            </ul>
        {% endif %}

        <h1>{{ post.title }}</h1>

        <div class='content'>
            {{ post.content }}
        </div>

    </body>
</html>
</code>```

I also registered volt in my bootstrap file (/public/index.php) which looks like that:

```<code><?php

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt;

// Register an autoloader
$loader = new Loader();

$loader->registerDirs(
    [
        "../app/controllers/",
        "../app/models/",
    ]
);

$loader->register();

// Create a DI
$di = new FactoryDefault();

// Setup the view component
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../app/views/");

        $view->registerEngines(
            [
                '.volt' => 'voltService',
            ]
        );

        return $view;
    }
);

// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set(
    "url",
    function () {
        $url = new UrlProvider();

        $url->setBaseUri("/care/");

        return $url;
    }
);

$application = new Application($di);

try {
    // Handle the request
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo "Exception: ", $e->getMessage();
}
</code>```

But when I try to access to /posts directory (localhost/care/posts) I get the following error:

Exception: Service 'voltService' wasn't found in the dependency injection container

I checked if Volt service was not already declared in Services.php as it is said in a similar post here but it is not.

Thank you

答:
The issue is with this block of code. You are telling your view that it should use the volt extension and process it using a service called voltService.

```<code>// Setup the view component
$di->set(
    "view",
    function () {
        $view = new View();
        $view->setViewsDir("../app/views/");
        $view->registerEngines(
            [
                '.volt' => 'voltService',
            ]
        );

        return $view;
    }
);
</code>```

If you look at your snippet, there is no service called voltService defined.

However if you add this to your services, it should work:

```<code>// Register Volt as a service
$di->set(
    'voltService',
    function ($view, $di) {
        $volt = new Volt($view, $di);

        $volt->setOptions(
            [
                'compiledPath'      => '../app/compiled-templates/',
                'compiledExtension' => '.compiled',
            ]
        );

        return $volt;
    }
);
</code>```

Reference: https://docs.phalconphp.com/en/3.2/volt#setup

Body:
I am trying to replicate the examples in the Volt tutorial here, using the basic example of phalcon here, so nothing complicated.

So I created this app/controllers/PostsControllers like this:

<?php

use Phalcon\Mvc\Controller;

class PostsController extends Controller
{
    public function indexAction()
    {
/*        $post = Post::findFirst();
        $menu = Menu::findFirst();*/

        $post = array("title"=>"The titre");
        $menu = "menu1";

        $this->view->show_navigation = true;
        $this->view->menu            = $menu;
        $this->view->title           = $post["title"];
        $this->view->post            = $post;

        // Or...

        $this->view->setVar('show_navigation', true);
        $this->view->setVar('menu',            $menu);
        $this->view->setVar('title',           $post["title"]);
        $this->view->setVar('post',            $post);
    }
}

And its corresponding app/views/posts/index.phtml like this:

{# app/views/posts/show.phtml #}
<!DOCTYPE html>

        <title>{{ title }} - An example blog</title>

        {% if show_navigation %}

                {% for item in menu %}

                            {{ item.caption }}

                {% endfor %}

        {% endif %}

{{ post.title }}

            {{ post.content }}

I also registered volt in my bootstrap file (/public/index.php) which looks like that:

<?php

use Phalcon\Loader;
use Phalcon\Mvc\View;
use Phalcon\Mvc\Application;
use Phalcon\Di\FactoryDefault;
use Phalcon\Mvc\Url as UrlProvider;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Mvc\View\Engine\Volt;

// Register an autoloader
$loader = new Loader();

$loader->registerDirs(
    [
        "../app/controllers/",
        "../app/models/",
    ]
);

$loader->register();

// Create a DI
$di = new FactoryDefault();

// Setup the view component
$di->set(
    "view",
    function () {
        $view = new View();

        $view->setViewsDir("../app/views/");

        $view->registerEngines(
            [
                '.volt' => 'voltService',
            ]
        );

        return $view;
    }
);

// Setup a base URI so that all generated URIs include the "tutorial" folder
$di->set(
    "url",
    function () {
        $url = new UrlProvider();

        $url->setBaseUri("/care/");

        return $url;
    }
);

$application = new Application($di);

try {
    // Handle the request
    $response = $application->handle();

    $response->send();
} catch (\Exception $e) {
    echo "Exception: ", $e->getMessage();
}

But when I try to access to /posts directory (localhost/care/posts) I get the following error:

Exception: Service 'voltService' wasn't found in the dependency injection container

I checked if Volt service was not already declared in Services.php as it is said in a similar post here but it is not.

Thank you

Body:
The issue is with this block of code. You are telling your view that it should use the volt extension and process it using a service called voltService.

// Setup the view component
$di->set(
    "view",
    function () {
        $view = new View();
        $view->setViewsDir("../app/views/");
        $view->registerEngines(
            [
                '.volt' => 'voltService',
            ]
        );

        return $view;
    }
);

If you look at your snippet, there is no service called voltService defined.

However if you add this to your services, it should work:

// Register Volt as a service
$di->set(
    'voltService',
    function ($view, $di) {
        $volt = new Volt($view, $di);

        $volt->setOptions(
            [
                'compiledPath'      => '../app/compiled-templates/',
                'compiledExtension' => '.compiled',
            ]
        );

        return $volt;
    }
);

Reference: https://docs.phalconphp.com/en/3.2/volt#setup


问:
Python : Redirecting device with MITM
I have built a MITM with python and scapy.I want to make the "victim" device be redirected to a specific page each time it tried to access a website. Any suggestions on how to do it?

*Keep in mind that all the traffic from the device already passes through my machine before being routed.

答: You can directly answer HTTP requests to pages different to that specific webpage with HTTP redirections (e.g. HTTP 302). Moreover, you should only route packets going to the desired webpage and block the rest (you can do so with a firewall such as iptables).</p>

Title: Python : Redirecting device with MITM


问:
Use existing HTML 5 themes with Angular 4+
I bought a theme from theme Forest and want to use it with angular 4, the theme has a lot of scripts and once i integrated it with angular cli every thing broke, i kept the css file references in the html head tag and js references at the end of the body tag and it worked fine but some of the js functionality didn't work specially jquery stuff, how can i solve this. </p>

答:
Angular is framework, which means that

It gives you certain rules

It gives you project structure

You have to abide by the rules to make it work in Angular way

Solution
 4. Take the pages, break them to  component
 6. Add css on component level
 7. Avoid using Jquery or Js to manipulate DOM, do it the angular way


问:
Can't delete from a table with two conditions using PHP
I am trying to delete a row from a table using two conditions. this is my current code :

```<code><?php
require 'database.php';
$id=0;
$od=0;
if(!empty($_GET['id_espece'])){
    $id=$_REQUEST['id_espece'];
}
if(!empty($_GET['id_valor'])){
    $od=$_REQUEST['id_valor'];
}
if(!empty($_POST)){
    $id= $_POST['id_espece'];
    $od= $_POST ['id_valor'];
    $pdo=Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         $sql = 'DELETE FROM mode_valorisation WHERE "id_espece" = ? and "id_valor" = ? ';
            $q = $pdo->prepare($sql);
            $q->execute(array($id,$od));
            Database::disconnect();

             header("Location: page-valo.php");
        }
    ?>

<form class="form-horizontal" action="page-supprimervalo.php" method="post" style="background: #89e29a; border-color: black; border-radius: 20px; padding: 5px;width: 500px; position: relative;right: -480px;" >
      <input type="hidden" name="id_espece" value="<?php echo $id;?>"/>
      <input type="hidden" name="id_valor" value="<?php echo $od;?>"/>
</form>
</code>```

I Tried the solution proposed here:
How to Delete a Record in php that has composite (multi-column) primary key

```<code>$sql = "DELETE FROM mode_valorisation WHERE id_espece = ? and id_valor = ? limit 1";
</code>```

but it gives me the following error :

syntax error at or near "limit" LINE 1: ..._valorisation WHERE
  id_espece = $1 and id_valor = $2 limit 1 ^

Thank you ;

答:
First of all, do not use quotes for table names/column names.
Second, there is no 'limit' in your query.
I run the code at my end with the same parameters and table and it worked just fine.</p>

Body:
I am trying to delete a row from a table using two conditions. this is my current code :

<?php
require 'database.php';
$id=0;
$od=0;
if(!empty($_GET['id_espece'])){
    $id=$_REQUEST['id_espece'];
}
if(!empty($_GET['id_valor'])){
    $od=$_REQUEST['id_valor'];
}
if(!empty($_POST)){
    $id= $_POST['id_espece'];
    $od= $_POST ['id_valor'];
    $pdo=Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

         $sql = 'DELETE FROM mode_valorisation WHERE "id_espece" = ? and "id_valor" = ? ';
            $q = $pdo->prepare($sql);
            $q->execute(array($id,$od));
            Database::disconnect();

             header("Location: page-valo.php");
        }
    ?>

<form class="form-horizontal" action="page-supprimervalo.php" method="post" style="background: #89e29a; border-color: black; border-radius: 20px; padding: 5px;width: 500px; position: relative;right: -480px;" >
      <input type="hidden" name="id_espece" value="<?php echo $id;?>"/>
      <input type="hidden" name="id_valor" value="<?php echo $od;?>"/>
</form>

I Tried the solution proposed here:
How to Delete a Record in php that has composite (multi-column) primary key

$sql = "DELETE FROM mode_valorisation WHERE id_espece = ? and id_valor = ? limit 1";

but it gives me the following error :

syntax error at or near "limit" LINE 1: ..._valorisation WHERE
  id_espece = $1 and id_valor = $2 limit 1 ^

Thank you ;


问:
Give attribute to wordpress post titles
I am working on a Wordpress site where multiple posts are to be displayed in a single page. The title of each post is displayed with h2 tags. Now I want to be able to give each of these an id (html id attribute), preferably of my choice so I can link to them (use as anchor).

Link to my page is
https://www.risingidiots.com/photoshop-opening/

答:
If you wanted to add id in h2 tag you need to change the code in page-blog.php file.

there is two way to add the id.

if you wanted to add different id for each post as you want then you can just add custom field in each and every post.

then edit file and add the custom field value in h2 tag as ID.
as below.

```<code><?php
   $post_id = get_post_meta( get_the_ID(), 'post_id', true );
?>
<h2 id="<?php echo $post_id; ?>"><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h2>
</code>```

another way is you just use post id as id for h2 tag.

Title: Give attribute to wordpress post titles

Body:
If you wanted to add id in h2 tag you need to change the code in page-blog.php file.

there is two way to add the id.

if you wanted to add different id for each post as you want then you can just add custom field in each and every post.

then edit file and add the custom field value in h2 tag as ID.
as below.

<?php
   $post_id = get_post_meta( get_the_ID(), 'post_id', true );
?>
<h2 id="<?php echo $post_id; ?>"><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?></a></h2>

another way is you just use post id as id for h2 tag.


问:
Unable to find htdocs on xampp
I have installed XAMPP for macOS Sierra.

I have one icon in application for XAMPP.

I am able to run the server & it's services but I am not able to find the htdocs folder.

I have not found it under \Library\Webserver

答: I was able to find the htdocs directory. On mac,Under volume tab there is button called 'explore' from there there is the directory.

Title: Unable to find htdocs on xampp


问:
How can I create a string in english letters from another language word?
I need to find a way to rewrite words(translit) from some languages into English language. For example привет (in Russian) sounds like privet (in English).

Meaning and grammar don't matter, but I'd like it to have a more similar sounding. Everything should be in Python, I have diligently looked up on the internet and haven't found a good approach.

For example, something similar to this:

```<code>translit("юу со беутифул", "ru") = juu so beutiful

translit("кар", "ru") = kar
</code>```

答:
This is another possible solution using regex, you can configure this function to replace the special characters for the characters you want:</p>

```<code>import re

def remove_accents(string):
    if type(string) is not unicode:
        string = unicode(string, encoding='utf-8')

    string = re.sub(u"[àáâãäå]", 'a', string)
    string = re.sub(u"[èéêë]", 'e', string)
    string = re.sub(u"[ìíîï]", 'i', string)
    string = re.sub(u"[òóôõö]", 'o', string)
    string = re.sub(u"[ùúûü]", 'u', string)
    string = re.sub(u"[ýÿ]", 'y', string)

    return string
</code>```

Body:
I need to find a way to rewrite words(translit) from some languages into English language. For example привет (in Russian) sounds like privet (in English).

Meaning and grammar don't matter, but I'd like it to have a more similar sounding. Everything should be in Python, I have diligently looked up on the internet and haven't found a good approach.

For example, something similar to this:

translit("юу со беутифул", "ru") = juu so beutiful

translit("кар", "ru") = kar

Body:
This is another possible solution using regex, you can configure this function to replace the special characters for the characters you want:

import re

def remove_accents(string):
    if type(string) is not unicode:
        string = unicode(string, encoding='utf-8')

    string = re.sub(u"[àáâãäå]", 'a', string)
    string = re.sub(u"[èéêë]", 'e', string)
    string = re.sub(u"[ìíîï]", 'i', string)
    string = re.sub(u"[òóôõö]", 'o', string)
    string = re.sub(u"[ùúûü]", 'u', string)
    string = re.sub(u"[ýÿ]", 'y', string)

    return string


问:
Javascript: Inserting data from an array into function parameter
I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.

I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:

```<code>//functions

function simpleCalc (a,b) {
    var result = a + b;
    return result;
}

//array

var myArray = [12,567];

//final calculation

var total = simpleCalc([0],[1]);

alert("The total is " + total);
</code>```

Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"

Thanks

答:
You don't specify the array but only indexes :

```<code>var total = simpleCalc([0],[1]);
</code>```

So, it passes two array objects : [0] and [1].

The concatenation of them here :

```<code>var result = a + b;
</code>```

has as result the 01 String.

To pass the two first elements of myArray, try it :

```<code>var total = simpleCalc(myArray[0],myArray[1]);
</code>```

Body:
I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.

I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:

//functions

function simpleCalc (a,b) {
    var result = a + b;
    return result;
}

//array

var myArray = [12,567];

//final calculation

var total = simpleCalc([0],[1]);

alert("The total is " + total);

Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"

Thanks

Body:
You don't specify the array but only indexes :

var total = simpleCalc([0],[1]);

So, it passes two array objects : [0] and [1].

The concatenation of them here :

var result = a + b;

has as result the 01 String.

To pass the two first elements of myArray, try it :

var total = simpleCalc(myArray[0],myArray[1]);


问:
Two way comparison in Pandas DataFrame?
I have just started my journey with Pandas Library. Actually I was trying to explore the Kaggle | Titanic Dataset.

So, there is actually a column called "Fare".

I want to find out who has "Fare" == 0

I can do it using,

```<code>print titanic_df[titanic_df["Fare"] == 0] #titanic_df is my DataFrame
</code>```

and I fully understand the process.

Now I saw someone saying an use of 2 way comparison on the Pandas DataFrame and is given by

```<code>print titanic_df["Fare"][titanic_df["Fare"] == 0]
</code>```

This also got the same number of rows printed. I'm quite confused as to how the code is executed (what is he meaning of the second index). I might be asking a very stupid question, but I searched a lot before this, without any success.

Please bear with me. Any help is appreciated. Thanks in advance.

答:
The difference between those two types of selections is that the first returns 'pandas.core.frame.DataFrame' and the second returns 'pandas.core.series.Series'

```<code>print type(titanic_train_df[titanic_train_df["Fare"] == 0])
<class 'pandas.core.frame.DataFrame'>
</code>```

Which is all of the columns for the selected rows, where 'Fare' == 0.

```<code>print type(titanic_train_df["Fare"][titanic_train_df["Fare"] == 0])
<class 'pandas.core.series.Series'>
</code>```

Which is only the 'Fare' column of the selected rows, where 'Fare' == 0.

Title: Two way comparison in Pandas DataFrame?

Body:
I have just started my journey with Pandas Library. Actually I was trying to explore the Kaggle | Titanic Dataset.

So, there is actually a column called "Fare".

I want to find out who has "Fare" == 0

I can do it using,

print titanic_df[titanic_df["Fare"] == 0] #titanic_df is my DataFrame

and I fully understand the process.

Now I saw someone saying an use of 2 way comparison on the Pandas DataFrame and is given by

print titanic_df["Fare"][titanic_df["Fare"] == 0]

This also got the same number of rows printed. I'm quite confused as to how the code is executed (what is he meaning of the second index). I might be asking a very stupid question, but I searched a lot before this, without any success.

Please bear with me. Any help is appreciated. Thanks in advance.

Body:
The difference between those two types of selections is that the first returns 'pandas.core.frame.DataFrame' and the second returns 'pandas.core.series.Series'

print type(titanic_train_df[titanic_train_df["Fare"] == 0])
<class 'pandas.core.frame.DataFrame'>

Which is all of the columns for the selected rows, where 'Fare' == 0.

print type(titanic_train_df["Fare"][titanic_train_df["Fare"] == 0])
<class 'pandas.core.series.Series'>

Which is only the 'Fare' column of the selected rows, where 'Fare' == 0.


问:
Django Rest Framework - "Got a `TypeError` when calling `Note.objects.create()'"
When i am trying to POST using the browsable API of DRF, i get the following error:

Got a TypeError when calling Note.objects.create(). This may be
  because you have a writable field on the serializer class that is not
  a valid argument to Note.objects.create(). You may need to make the
  field read-only, or override the NoteSerializer.create() method to
  handle this correctly.

I don't know what is generating this error or how to overcome it. Literally spent hours google searching or changing the code. Can someone explain how to overcome this error? (Please note i am new to Django and DRF!)

Here is the models.py:

```<code>from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
import uuid

class Stock(models.Model):
    '''
    Model representing the stock info.
    '''
    user = models.ForeignKey(User)
    book_code = models.CharField(max_length=14, null=True, blank=True)

    def __str__(self):
        return self.book_code

class Note(models.Model):
    '''
    Model representing the stock note.
    '''
    user = models.ForeignKey(User)
    note = models.TextField(max_length=560)
    stock = models.ForeignKey(Stock, related_name='notes')
    date_note_created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.note
</code>```

This is the views.py:

```<code>from rest_framework import generics
from stocknoter.models import Stock, Note
from api.serializers import StockSerializer, NoteSerializer

# Create your views here.

class StockList(generics.ListCreateAPIView):
    serializer_class = StockSerializer
    def get_queryset(self):
        user = self.request.user
        return Stock.objects.filter(user=user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)

class NoteList(generics.ListCreateAPIView):
    serializer_class = NoteSerializer
    def get_queryset(self):
        user = self.request.user
        return Note.objects.filter(user=user)

    def perform_create(self, serializer):
        serializer.save(data=self.request.data)

    def perform_update(self, serializer):
        serializer.save(data=self.request.data)
</code>```

This is the serializers.py:

```<code>from stocknoter.models import Stock, Note
from rest_framework import serializers

class StockSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    notes = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Stock
        fields = ('id', 'user', 'book_code', 'notes')

class NoteSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Note
        fields = ('user', 'note', 'stock')
</code>```

答:
I think this is because you are providing keyword argument data to save method. This is unnecessary. save() dont have such argument. Try just this:

```<code>def perform_create(self, serializer):
    serializer.save()
</code>```

Body:
When i am trying to POST using the browsable API of DRF, i get the following error:

Got a TypeError when calling Note.objects.create(). This may be
  because you have a writable field on the serializer class that is not
  a valid argument to Note.objects.create(). You may need to make the
  field read-only, or override the NoteSerializer.create() method to
  handle this correctly.

I don't know what is generating this error or how to overcome it. Literally spent hours google searching or changing the code. Can someone explain how to overcome this error? (Please note i am new to Django and DRF!)

Here is the models.py:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
import uuid

class Stock(models.Model):
    '''
    Model representing the stock info.
    '''
    user = models.ForeignKey(User)
    book_code = models.CharField(max_length=14, null=True, blank=True)

    def __str__(self):
        return self.book_code

class Note(models.Model):
    '''
    Model representing the stock note.
    '''
    user = models.ForeignKey(User)
    note = models.TextField(max_length=560)
    stock = models.ForeignKey(Stock, related_name='notes')
    date_note_created = models.DateTimeField(default=timezone.now)

    def __str__(self):
        return self.note

This is the views.py:

from rest_framework import generics
from stocknoter.models import Stock, Note
from api.serializers import StockSerializer, NoteSerializer

# Create your views here.

class StockList(generics.ListCreateAPIView):
    serializer_class = StockSerializer
    def get_queryset(self):
        user = self.request.user
        return Stock.objects.filter(user=user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

    def perform_update(self, serializer):
        serializer.save(user=self.request.user)

class NoteList(generics.ListCreateAPIView):
    serializer_class = NoteSerializer
    def get_queryset(self):
        user = self.request.user
        return Note.objects.filter(user=user)

    def perform_create(self, serializer):
        serializer.save(data=self.request.data)

    def perform_update(self, serializer):
        serializer.save(data=self.request.data)

This is the serializers.py:

from stocknoter.models import Stock, Note
from rest_framework import serializers

class StockSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())
    notes = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Stock
        fields = ('id', 'user', 'book_code', 'notes')

class NoteSerializer(serializers.ModelSerializer):
    user = serializers.HiddenField(default=serializers.CurrentUserDefault())

    class Meta:
        model = Note
        fields = ('user', 'note', 'stock')

Body:
I think this is because you are providing keyword argument data to save method. This is unnecessary. save() dont have such argument. Try just this:

def perform_create(self, serializer):
    serializer.save()


问:
bootstrap panel is not working properly
```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>GMP APP</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/custom.css" type="text/css"/>
</head>
<body>
    <div class="container">
    <div class="panel panel-default">
        <div class="panel-heading"> SignUp to the system </div>
        <div class="panel-body">
            <<panel content goes here>>
        </div>
        <div class="panel-footer"> You have 3 More attempts left! </div>
    </div>
        <script src="javascript/jquery.js"> </script>
        <script src="javascript/bootstrap.js"> </script>
    </div>
</body>
</html>
</code>```

bootstrap is linked correctly. But the panel is not working.! I tried everything. I do assume i have correctly linked relevant libraries. This is the output of the browser page source...

答:
Here you go with fiddle https://jsfiddle.net/nh2g8mLb/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

 SignUp to the system

            Test Panel

 You have 3 More attempts left!

```

Title: bootstrap panel is not working properly

Body:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>GMP APP</title>
    <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
    <link rel="stylesheet" href="css/custom.css" type="text/css"/>

 SignUp to the system

            <<panel content goes here>>

 You have 3 More attempts left!

bootstrap is linked correctly. But the panel is not working.! I tried everything. I do assume i have correctly linked relevant libraries. This is the output of the browser page source...

Body:
Here you go with fiddle https://jsfiddle.net/nh2g8mLb/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
    <div class="panel panel-default">
        <div class="panel-heading"> SignUp to the system </div>
        <div class="panel-body">
            Test Panel
        </div>
        <div class="panel-footer"> You have 3 More attempts left! </div>
    </div>
</div>


问:
What's the LINQ expression of this SQL code?
This is my SQL statement:

```<code>SELECT p.*
FROM p
LEFT JOIN q ON p.id = q.id AND p.name = q.name
WHERE q.id IS null
</code>```

I'm trying to convert this code to a LINQ expression.

答:
```<code>   var data = (from a in p
               from b in q.Where(x => x.id == a.id && x.name == a.name).DefaultIfEmpty()
               WHERE b.id == null
               select a).ToList();
</code>```

Moreover you can try Linqer to convert your SQL query to Linq

Body:
This is my SQL statement:

SELECT p.*
FROM p
LEFT JOIN q ON p.id = q.id AND p.name = q.name
WHERE q.id IS null

I'm trying to convert this code to a LINQ expression.

Body:
   var data = (from a in p
               from b in q.Where(x => x.id == a.id && x.name == a.name).DefaultIfEmpty()
               WHERE b.id == null
               select a).ToList();

Moreover you can try Linqer to convert your SQL query to Linq


问:
javascript match hebrew word inside double curly brackets
i have a js function that working in english but i get error in hebrew

the function match all the words in string that inside  {{ }} and return the word inside the double curly bracket in a array without the curly bracket
the string can Contains both english and non english words like this:    {{test}} {{בדיקה}} hi this is my test {{test2}}

```<code>var str_eng =  "{{test}} {{test1}}";
var str_non_eng = "{{בדיקה}} {{עעע}}";

str_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) //array[ "test","test1" ] //ok

str_non_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) // error not working
</code>```

Thanks!

答:
you can't use \w for Hebrew chars.
use the following : </p>

```<code>/{{\s*[\w\u0590-\u05FF\.]+\s*}}/g
</code>```

Body:
i have a js function that working in english but i get error in hebrew

the function match all the words in string that inside  {{ }} and return the word inside the double curly bracket in a array without the curly bracket
the string can Contains both english and non english words like this:    {{test}} {{בדיקה}} hi this is my test {{test2}}

var str_eng =  "{{test}} {{test1}}";
var str_non_eng = "{{בדיקה}} {{עעע}}";

str_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) //array[ "test","test1" ] //ok

str_non_eng.match(/{{\s*[\w\.]+\s*}}/g).map(function(x) { return x.match(/[\w\.]+/)[0];  }) // error not working

Thanks!

Body:
you can't use \w for Hebrew chars.
use the following :

/{{\s*[\w\u0590-\u05FF\.]+\s*}}/g


问:
Rollback on node.js install on Windows 7 x64 PC
I've been trying to get node.js installed on my home PC for a while now with no luck. I've tried different versions for the past couple months and no matter what I try it starts rolling back the install at "Creating shortcuts" and it fails to install. I created an install log for anyone who wants to look at it and take a stab at helping me solve the problem. Thanks!

https://dl.dropbox.com/u/177486/MSIf99e3.LOG

答:
```<code>msiexec /i node.msi /qn+ ADDLOCAL=ALL REMOVE=NodePerfCtrSupport,NodeEtwSupport
</code>```

This might help

Body:
msiexec /i node.msi /qn+ ADDLOCAL=ALL REMOVE=NodePerfCtrSupport,NodeEtwSupport

This might help


答:
You need to access the array values by index. You do this using the brackets WITH the name of the array. If you pass the brackets with numbers inside, you're creating new arrays.

It should be:

```<code> var total = simpleCalc(myArray[0],myArray[1]);
</code>```

Title: Javascript: Inserting data from an array into function parameter

Body:
You need to access the array values by index. You do this using the brackets WITH the name of the array. If you pass the brackets with numbers inside, you're creating new arrays.

It should be:

 var total = simpleCalc(myArray[0],myArray[1]);


问:
how to get miglayout-swing in gradle
I am trying to get the miglayout jar file: miglayout-3.7.2-swing.jar.

I want only this jar. I don't want all the jars of miglayout-3.7.2.

If I give com.miglayout:miglayout:3.7.2@jar it downloads everything.

Any one help me how to download miglayout-3.7.2-swing.jar in gradle?

答:
i got the answer!!

com.miglayout:miglayout:3.7.2:swing@jar    swing must be next to version. i tried before the version! :)

Title: how to get miglayout-swing in gradle


问:
How to debug prepare statement with PHP?
I am trying to insert value in my database using below code.But it does not enter value.I want to debug & print any error message i tried $stmt->error or $stmt->errorInfo() but nothing worked for me.

```<code>$stmt = $this->conn->prepare("INSERT INTO users(name) values(?)");
$stmt->bind_param("s", "dhieaj");

$result = $stmt->execute();
echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
    // User successfully inserted
    return USER_CREATED_SUCCESSFULLY;
}
</code>```

答: Actually the code mentioned here by 'DLastCodeBender' is correct but still i was not able to solve my issue.The issue is with MAMP sever.I was not able to run Slim framework with MAMP.So i installed XAMPP on my mac & there all API worked for me.

Body:
I am trying to insert value in my database using below code.But it does not enter value.I want to debug & print any error message i tried $stmt->error or $stmt->errorInfo() but nothing worked for me.

$stmt = $this->conn->prepare("INSERT INTO users(name) values(?)");
$stmt->bind_param("s", "dhieaj");

$result = $stmt->execute();
echo $stmt->errorInfo();
$stmt->close();
// Check for successful insertion
if ($result){
    // User successfully inserted
    return USER_CREATED_SUCCESSFULLY;
}


问:
Parsing nested JSON in go language
How could I parse and extract certain values from below JSON

Here is the sample JSON response

```<code>{
   "success":true,
   "endpoint":"https://api.abcxyz.com",
   "info":{
      "Guestconnected":134,
      "Guestratio":100000.06963,
      "symbol1":{
         "code":"NY",
         "symbol":"*",
         "name":"newyear",
         "codev":391.78161,
         "symbolAppearsAfter":false,
         "local":true
      },
      "symbol2":{
         "code":"HNY",
         "symbol":"@",
         "name":"HappyNewYear",
         "codev":1000000.0960,
         "symbolAppearsAfter":true,
         "local":false
      },
      "latest":{
         "value":1597509,
         "autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height":474696,
         "time":1499527696
      }
   },
   "Allguest":{
      "all":4,
      "filtered":4,
      "total_invitations":15430,
      "sent_invitations":15430,
      "final_invitations":0
   },
   "Guestlist":[
      {
         "GuestCode":"369AR",
         "all":2,
         "total_invitations":5430,
         "sent_invitations":5430,
         "final_invitations":0,
         "change":0,
         "accounts":0
      },
      {
         "GuestCode":"6POIA96TY",
         "all":2,
         "total_invitations":10000,
         "sent_invitations":10000,
         "final_invitations":0,
         "change":0,
         "accounts":0
      }
   ]
}
</code>```

My Code is :

```<code>package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func main() {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

 var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)

}
</code>```

The problem is :

If the response is null it is giving index out of range error how can we avoid this ?

Applying condition if TotalInvitations value is greater than 100 then save in 100.csv else save in others.csv

答: If you need only certain entries from JSON you can define a structure with only those fields you are interested in. And if value can be null it is better to declare a pointer in the structure. Please take a look at an example at go playground: https://play.golang.org/p/mEwSXvPg3D </p>

Title: Parsing nested JSON in go language

Body:
How could I parse and extract certain values from below JSON

Here is the sample JSON response

{
   "success":true,
   "endpoint":"https://api.abcxyz.com",
   "info":{
      "Guestconnected":134,
      "Guestratio":100000.06963,
      "symbol1":{
         "code":"NY",
         "symbol":"*",
         "name":"newyear",
         "codev":391.78161,
         "symbolAppearsAfter":false,
         "local":true
      },
      "symbol2":{
         "code":"HNY",
         "symbol":"@",
         "name":"HappyNewYear",
         "codev":1000000.0960,
         "symbolAppearsAfter":true,
         "local":false
      },
      "latest":{
         "value":1597509,
         "autovalue":"00099cf8da58a36c08f2ef98650ff6043ddfb",
         "height":474696,
         "time":1499527696
      }
   },
   "Allguest":{
      "all":4,
      "filtered":4,
      "total_invitations":15430,
      "sent_invitations":15430,
      "final_invitations":0
   },
   "Guestlist":[
      {
         "GuestCode":"369AR",
         "all":2,
         "total_invitations":5430,
         "sent_invitations":5430,
         "final_invitations":0,
         "change":0,
         "accounts":0
      },
      {
         "GuestCode":"6POIA96TY",
         "all":2,
         "total_invitations":10000,
         "sent_invitations":10000,
         "final_invitations":0,
         "change":0,
         "accounts":0
      }
   ]
}

My Code is :

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type object struct {
    Success bool `json:"success"`
    Endpoint string `json:"endpoint"`
    Allguest struct {
        All int `json:"all"`
        Filtered int `json:"filtered"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
    } `json:"Allguest"`
    Guestlist []struct {
        GuestCode string `json:"GuestCode"`
        All int `json:"all"`
        TotalInvitations int `json:"total_invitations"`
        SentInvitations int `json:"sent_invitations"`
        FinalInvitations int `json:"final_invitations"`
        Change int `json:"change"`
        Accounts int `json:"accounts"`
    } `json:"Guestlist"`
}

func main() {

uri := "https://siteurl.com/api?lists=1"
res, err := http.Get(uri)
fmt.Println(uri)
if err != nil {
fmt.Println("Error:", err)
    log.Fatal(err)
}
defer res.Body.Close()

 var s object
err := json.NewDecoder(res.Body).Decode(&s)
if err != nil {
    log.Fatal(err)
    fmt.Println("Error:", err)
}
fmt.Println(s.Success)
fmt.Println(s.Allguest.TotalInvitations)
for i := 0; i < 6; i++ {
fmt.Println(s.Guestlist[i].TotalInvitations)
)

}

The problem is :

If the response is null it is giving index out of range error how can we avoid this ?

Applying condition if TotalInvitations value is greater than 100 then save in 100.csv else save in others.csv


问:
Manipulating Inserted Fields from Checkbox and Select via Jquery - Cocoon Rails
I'm having trouble accessing and using the value of a checkbox and then select field for forms dynamically added via the Cocoon Gem for Rails. I've read through many SO posts and the official Cocoon documentation and I just can't seem to get it right.

The idea is that after adding a form via Cocoon, there are hidden fields that only show up if a specific checkbox is :checked, with one of those fields that being a f.select and upon the selection of that value more fields will either show or hide.

_mortgage_fields.html.erb

```<code>...

<%= f.form_group :misc_mortgage do %>
  <%= f.check_box :misc_mortgage, label: "Miscellaneous Mortgage" %>
<% end %>

<%= f.select :misc_mortgage_context, [["Assignment", "Assignment"], ["Subordination", "Subordination"], ["Modification", "Modification"]],
               { label: "Miscellaneous Mortgage Type" }, wrapper: { class: 'mtgHidden' }%>

<%= f.text_field :reference_mortgage, class: 'form-control', wrapper: { class: 'mtgHidden' } %>

<%= f.text_field :subordinated_mortgage, class: 'form-control', wrapper: { class: 'Subordination' } %>

<%= f.text_field :modification_amount, class: 'form-control', wrapper: { class: 'Modification' } %>

...
</code>```

The top level form is wrapped with
..

cocoonoptions.js

```<code>$(document.ready(function() {

  $('#mtgForm').on('cocoon:after-insert', function(e, misc_checkbox) {

    alert('getting there');

    $(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]').change(function() {

            alert('almost there');

            if ($(this).is(':checked'))
                alert('there!');
                $('.mtgHidden').show();
            else
                $('.mtgHidden').hide();
        });

    $(misc_checkbox).find("select[name*='misc_mortgage_context']").change(function() {
        var mtg = $(this).val();

        if (mtg == "Subordination") {
            $('.Subordination').show();
            $('.Modification').hide();
        }
        else if (mtg == "Modification") {
            $('.Modification').show();
            $('.Subordination').hide();
        }
        else {
            $('.Subordination').hide();
            $('.Modification').hide();
        }
    });
});
</code>```

The wrapper: { ... } fields are set to display: none by CSS and then shown or hidden according to the above values via JS. This same code works (without the cocoon:after-insert part of course) on a static HTML page for adding a single item without the necessity of adding multiple items at once like Cocoon is beautifully made to do.

I've tried the code above many different ways based on different posts or sites I've found online but I can only seem to get the first test alert to fire. Including misc_checkbox.find('...') without the $(...) wrapper.

Am I going about this the wrong way or is my code just incorrect? Thanks in advance for any and all help!

Update

Of course as soon as I post the question I figured it out. The + in [id*="+misc_mortgage"] was throwing it off and I wasn't loading cocoonoptions.js correctly. Going to leave this question up so maybe it will help someone in the future.

答:
So my code was almost correct. Once I changed
$(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]')
to $(misc_checkbox).find('input[type=checkbox][id*="misc_mortgage"]') and loaded the JS via

```<code><% content_for :javascript do %>

  <script type="text/javascript">

  </script>

<% end %>
</code>```

function at the bottom of view, everything worked.

Body:
I'm having trouble accessing and using the value of a checkbox and then select field for forms dynamically added via the Cocoon Gem for Rails. I've read through many SO posts and the official Cocoon documentation and I just can't seem to get it right.

The idea is that after adding a form via Cocoon, there are hidden fields that only show up if a specific checkbox is :checked, with one of those fields that being a f.select and upon the selection of that value more fields will either show or hide.

_mortgage_fields.html.erb

...

<%= f.form_group :misc_mortgage do %>
  <%= f.check_box :misc_mortgage, label: "Miscellaneous Mortgage" %>
<% end %>

<%= f.select :misc_mortgage_context, [["Assignment", "Assignment"], ["Subordination", "Subordination"], ["Modification", "Modification"]],
               { label: "Miscellaneous Mortgage Type" }, wrapper: { class: 'mtgHidden' }%>

<%= f.text_field :reference_mortgage, class: 'form-control', wrapper: { class: 'mtgHidden' } %>

<%= f.text_field :subordinated_mortgage, class: 'form-control', wrapper: { class: 'Subordination' } %>

<%= f.text_field :modification_amount, class: 'form-control', wrapper: { class: 'Modification' } %>

...

The top level form is wrapped with
..

cocoonoptions.js

$(document.ready(function() {

  $('#mtgForm').on('cocoon:after-insert', function(e, misc_checkbox) {

    alert('getting there');

    $(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]').change(function() {

            alert('almost there');

            if ($(this).is(':checked'))
                alert('there!');
                $('.mtgHidden').show();
            else
                $('.mtgHidden').hide();
        });

    $(misc_checkbox).find("select[name*='misc_mortgage_context']").change(function() {
        var mtg = $(this).val();

        if (mtg == "Subordination") {
            $('.Subordination').show();
            $('.Modification').hide();
        }
        else if (mtg == "Modification") {
            $('.Modification').show();
            $('.Subordination').hide();
        }
        else {
            $('.Subordination').hide();
            $('.Modification').hide();
        }
    });
});

The wrapper: { ... } fields are set to display: none by CSS and then shown or hidden according to the above values via JS. This same code works (without the cocoon:after-insert part of course) on a static HTML page for adding a single item without the necessity of adding multiple items at once like Cocoon is beautifully made to do.

I've tried the code above many different ways based on different posts or sites I've found online but I can only seem to get the first test alert to fire. Including misc_checkbox.find('...') without the $(...) wrapper.

Am I going about this the wrong way or is my code just incorrect? Thanks in advance for any and all help!

Update

Of course as soon as I post the question I figured it out. The + in [id*="+misc_mortgage"] was throwing it off and I wasn't loading cocoonoptions.js correctly. Going to leave this question up so maybe it will help someone in the future.

Body:
So my code was almost correct. Once I changed
$(misc_checkbox).find('input[type=checkbox][id*="+misc_mortgage"]')
to $(misc_checkbox).find('input[type=checkbox][id*="misc_mortgage"]') and loaded the JS via

<% content_for :javascript do %>

  <script type="text/javascript">

  </script>

<% end %>

function at the bottom of view, everything worked.


问:
Firebase: responding to http POST request
I was thinking of import my server Java code to firebase, basically replace my Dynamic web app with Jeresy and mongoDB to Firebase using hosting and functions .
I have implemented the sendWelcomeEmail and sendByeEmail with events user.created and user.deleted.

But now I want to do something more complicated.
Based on post request that comes from the mobile I want to extract the JSON data and then update the DataBase.

So I created js file with plenty of functions but now I am not sure it will actually work.
Is that the best way to implement this workflow.

The workflow goes like this.

Image is taken on the android device => extract information from image ==> upload the Json Data to the server (Firebase Hosting) => functions is been execute is response to POST request ==> extarct the data ==> save it to the Firebase Database.

Let me know if this sound ok, or I need to implent another workflow.
Thanks
Eran

答:
The whole idea of Firebase is that your app talks directly to backend services (such as the database, or cloud storage), and you only write server-side code (with cloud functions) for functionality that Firebase doesn't provide a client-side API for.

Why don't you simply let the Android client write directly to the Firebase Database?


问:
Convert List<V> in Map<K,V> with stream Java 8
I have a these model classes:

```<code>public class Student extends Person;

public class Professor extends Person;

public class University {
    private long id;
    private String name;
    private List<Person> employers;
....
}
</code>```

I have a List of University and I want to convert it into a Map; Person is an abstract class and has implemented hashCode and equals method.
This is an implementation with a for iteration:

```<code>Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
    for (Person p : u.getEmployers()) {
       mapList.put(p,u);
    }
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));
</code>```

I am not so familiar with Java 8 stream, but how can I covert this code with lambda expression?

答:
I would make it like this:</p>

```<code>universities.stream().forEach((uni) -> uni.getEmployers().stream().forEach((p) -> mapList.put(p, uni)));
</code>```

Body:
I have a these model classes:

public class Student extends Person;

public class Professor extends Person;

public class University {
    private long id;
    private String name;
    private List<Person> employers;
....
}

I have a List of University and I want to convert it into a Map; Person is an abstract class and has implemented hashCode and equals method.
This is an implementation with a for iteration:

Map<Person, University> mapList = new HashMap<Person, University>();
for (University u : universities) {
    for (Person p : u.getEmployers()) {
       mapList.put(p,u);
    }
}
mapList.forEach((k,v) -> System.out.println(k.toString() + v.getName()));

I am not so familiar with Java 8 stream, but how can I covert this code with lambda expression?

Body:
I would make it like this:

universities.stream().forEach((uni) -> uni.getEmployers().stream().forEach((p) -> mapList.put(p, uni)));