问:
Binary coded GA with NSGA-II in R
I have a multiobjective minimization function. I want to use NSGA-II in R. There are packages for this: nsga2R and mco. But these packages do not support binary coded chromosomes. In my fitness function I need binary chromosomes to achive best solution because of my problem's structure. Is there any way to use binary coded chromosome in nsga2 (or maybe with different algorithm) for R? Thanks.</p>

答:
I got the same problem so I decided to fix it on my own. But no guarentee if it's the right way.

The following part is for the package 'mco'

I copied parts out of the offical nsga2 implementation into the 'mco' package.
This workaround is only for binary (0-1) variables.

1. In /src/nsga2.c rewrite the functions as follows:

static void mutate_ind (nsga2_ctx *ctx, individual *ind) {
  int j;
  double prob;
  GetRNGstate();
  for (j = 0; j < ctx->input_dim; j++)
    {
    //for (k=0; k < ctx[j]->input_dim; k++)
    //{
      //prob = randomperc();
      prob = unif_rand();
      if (prob <= ctx->mutation_probability) {
        if (ind->input[j] == 0)
        {
          ind->input[j] = 1;
        }
        else
        {
          ind->input[j] = 0;
        }
        ctx->input_mutations+=1;
      }
    //}
  }
  PutRNGstate();```
</div>
</div>
</p>

<p>then</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-html lang-html prettyprint-override"><code>static void crossover (nsga2_ctx *ctx,
                       individual *parent1, individual *parent2,
                       individual *child1, individual *child2) {

  int i;
  int nbits=1;
  double rand;
  int temp, site1, site2, temp2, temp3;

  GetRNGstate();

    rand=unif_rand();
    if (rand <= ctx->crossing_probability)
    {
      ctx->input_crossings++;
      //site1 = rnd(0,ctx->input_dim);
      //site2 = rnd(0,ctx->input_dim);
      if(unif_rand()<=0.5){
        temp2=0;
      }else{
        temp2=1;
      }

      if(unif_rand()<=0.5){
        temp3=0;
      }else{
        temp3=1;
      }

      site1=temp2;
      site2=temp3;

      if (site1 > site2)
      {
        temp = site1;
        site1 = site2;
        site2 = temp;
      }
      for (i=0; i<site1; i++)
      {
        child1->input[i] = parent1->input[i];
        child2->input[i] = parent2->input[i];
      }
      for (i=site1; i<site2; i++)
      {
        child1->input[i] = parent2->input[i];
        child2->input[i] = parent1->input[i];
      }
      for (i=site2; i<nbits; i++)
      {
        child1->input[i] = parent1->input[i];
        child2->input[i] = parent2->input[i];
      }
    }
    else
    {
      for (i=0; i<nbits; i++)
      {
        child1->input[i] = parent1->input[i];
        child2->input[i] = parent2->input[i];
      }
    }

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

and

static void population_initialize(nsga2_ctx *ctx, population *pop) {
  GetRNGstate();
  int i, j;
  for (i = 0; i < pop->size; ++i)  {
    for (j=0; j<ctx->input_dim; ++j) {
      /* Generate random value between lower and upper bound */
      //double delta = ctx->upper_input_bound[j] - ctx->lower_input_bound[j];
      //pop->ind[i].input[j] = ctx->lower_input_bound[j] + delta*unif_rand();
   if(unif_rand() <= 0.5){
    pop->ind[i].input[j] = 0;
   }
   else{
    pop->ind[i].input[j] = 1;
   }
    }
  }
  PutRNGstate();
}```
</div>
</div>
</p>

<p><strong>2.</strong> define the function randomperc() as follows</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-html lang-html prettyprint-override"><code>double seed;
double oldrand[55];
int jrand;

/* Create next batch of 55 random numbers */
void advance_random ()
{
  int j1;
  double new_random;
  for(j1=0; j1<24; j1++)
  {
    new_random = oldrand[j1]-oldrand[j1+31];
    if(new_random<0.0)
    {
      new_random = new_random+1.0;
    }
    oldrand[j1] = new_random;
  }
  for(j1=24; j1<55; j1++)
  {
    new_random = oldrand[j1]-oldrand[j1-24];
    if(new_random<0.0)
    {
      new_random = new_random+1.0;
    }
    oldrand[j1] = new_random;
  }
}

/* Fetch a single random number between 0.0 and 1.0 */
double randomperc()
{
  jrand++;
  if(jrand>=55)
  {
    jrand = 1;
    advance_random();
  }
  return((double)oldrand[jrand]);
}</code>```

3. replace every unif_rand() with randomperc() in 'nsga2.c'

4. build the package in R

Title: Binary coded GA with NSGA-II in R

Body:
I got the same problem so I decided to fix it on my own. But no guarentee if it's the right way.

The following part is for the package 'mco'

I copied parts out of the offical nsga2 implementation into the 'mco' package.
This workaround is only for binary (0-1) variables.

1. In /src/nsga2.c rewrite the functions as follows:

static void mutate_ind (nsga2_ctx *ctx, individual *ind) {
  int j;
  double prob;
  GetRNGstate();
  for (j = 0; j < ctx->input_dim; j++)
    {
    //for (k=0; k < ctx[j]->input_dim; k++)
    //{
      //prob = randomperc();
      prob = unif_rand();
      if (prob <= ctx->mutation_probability) {
        if (ind->input[j] == 0)
        {
          ind->input[j] = 1;
        }
        else
        {
          ind->input[j] = 0;
        }
        ctx->input_mutations+=1;
      }
    //}
  }
  PutRNGstate();

then

static void crossover (nsga2_ctx *ctx,
                       individual *parent1, individual *parent2,
                       individual *child1, individual *child2) {

  int i;
  int nbits=1;
  double rand;
  int temp, site1, site2, temp2, temp3;

  GetRNGstate();

    rand=unif_rand();
    if (rand <= ctx->crossing_probability)
    {
      ctx->input_crossings++;
      //site1 = rnd(0,ctx->input_dim);
      //site2 = rnd(0,ctx->input_dim);
      if(unif_rand()<=0.5){
        temp2=0;
      }else{
        temp2=1;
      }

      if(unif_rand()<=0.5){
        temp3=0;
      }else{
        temp3=1;
      }

      site1=temp2;
      site2=temp3;

      if (site1 > site2)
      {
        temp = site1;
        site1 = site2;
        site2 = temp;
      }
      for (i=0; i<site1; i++)
      {
        child1->input[i] = parent1->input[i];
        child2->input[i] = parent2->input[i];
      }
      for (i=site1; i<site2; i++)
      {
        child1->input[i] = parent2->input[i];
        child2->input[i] = parent1->input[i];
      }
      for (i=site2; i<nbits; i++)
      {
        child1->input[i] = parent1->input[i];
        child2->input[i] = parent2->input[i];
      }
    }
    else
    {
      for (i=0; i<nbits; i++)
      {
        child1->input[i] = parent1->input[i];
        child2->input[i] = parent2->input[i];
      }
    }

  PutRNGstate();
}

and

static void population_initialize(nsga2_ctx *ctx, population *pop) {
  GetRNGstate();
  int i, j;
  for (i = 0; i < pop->size; ++i)  {
    for (j=0; j<ctx->input_dim; ++j) {
      /* Generate random value between lower and upper bound */
      //double delta = ctx->upper_input_bound[j] - ctx->lower_input_bound[j];
      //pop->ind[i].input[j] = ctx->lower_input_bound[j] + delta*unif_rand();
   if(unif_rand() <= 0.5){
    pop->ind[i].input[j] = 0;
   }
   else{
    pop->ind[i].input[j] = 1;
   }
    }
  }
  PutRNGstate();
}

2. define the function randomperc() as follows

double seed;
double oldrand[55];
int jrand;

/* Create next batch of 55 random numbers */
void advance_random ()
{
  int j1;
  double new_random;
  for(j1=0; j1<24; j1++)
  {
    new_random = oldrand[j1]-oldrand[j1+31];
    if(new_random<0.0)
    {
      new_random = new_random+1.0;
    }
    oldrand[j1] = new_random;
  }
  for(j1=24; j1<55; j1++)
  {
    new_random = oldrand[j1]-oldrand[j1-24];
    if(new_random<0.0)
    {
      new_random = new_random+1.0;
    }
    oldrand[j1] = new_random;
  }
}

/* Fetch a single random number between 0.0 and 1.0 */
double randomperc()
{
  jrand++;
  if(jrand>=55)
  {
    jrand = 1;
    advance_random();
  }
  return((double)oldrand[jrand]);
}

3. replace every unif_rand() with randomperc() in 'nsga2.c'

4. build the package in R


来源: stackexchange

问:
Actions on Google where to start with no experience in JSON
Where I can learn about actions on google? I have read the documentations but still confused I don't have any experience in JSON </p>

答:
Start by reading about JSON and understanding it, you should probably get to know some basic JavaScript.
This is a very basic getting started website:
https://www.w3schools.com/js/js_json_intro.asp</p>

ContentLicense: CC BY-SA 3.0


问:
Golang: Unexpected EOF error while reading Gzip Reader
I'm currently working on a project in which a client python script compresses the input by using gzip package, then, encrypts the compressed data according to AES, and, finally, it encodes the encrypted data in base64 encoding scheme. On the server side, which was written in golang I'm following the same steps in the reverse order to reach the original data.

As can be seen from the output, I can decode, decrypt and decompress the data received from the client on my test script. However, while reading the gzip.NewReader type it throws unexpected EOF error. (see the output at the very bottom of the question)

So far, I've done it without trimming the padding, however, then it gave me an invalid gzip header error. Then, just to verify if there are any significant differences between a valid gzip Reader and the one being created by the script, I gzipped the original data into a compressed form. Apparently, there were no notable differences I could see from outputs, but the differences in bytes which were most likely caused by the change in time that the readers are created:

Original data: {"i": "MB88", "p": [{"d": [54.3, 0, 99, 49.35, 3, 99, 51.533, 1, 98, 28964, 7348, 43590, 97107, 10350, 55200, 49.7], "t": 1499089212.136789, "dt": "p"}]}

Gzipped data: "\x1f\x8b\x08\x00\xf9w[Y\x02\xff%\x8e=\x0e\xc30\x08F\xaf\x82\x98\x91\x05\xe6\xc7\xa6c\xf7\x9e\xa0\xca\x96\xa5[\x86lQ\xee^\xdcN\xf0\xf4\xc1\x83\x0b?\xf8\x00|=\xe7D\x02<\n\xde\x17\xee\xab\xb85%\x82L\x02\xcb\xa6N\xa0\x7fri\xae\xd5K\xe1$\xe83\xc3\x08\x86Z\x81\xa9g-y\x88\xf6\x9a\xf5E\xde\x99\x7f\x96\xb1\xd5\x99\xb3\xfcb\x99\x121D\x1bG\xe7^.\xdcWPO\xdc\xdb\xfd\x05\x0ev\x15\x1d\x99\x00\x00\x00"

Gzip Reader created from the request by client

GzReader:  &{{ [] 2017-07-03 15:40:12 +0200 CEST  255} 0xc42007e150 0xc4200a8000 0 0 [31 139 8 0 60 73 90 89 2 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]  true}

Gzip Reader created by directly reading the original data

GzReader2:  &{{ [] 2017-07-04 13:11:53 +0200 CEST  255} 0xc4200741e0 0xc4200a9300 0 0 [31 139 8 0 249 119 91 89 2 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]  true}

Now, I'm quite curious about what might be causing this error and how this issue can be solved. I couldn't post the original scripts here due to some restrictions but these are the actual test scripts that I'm currently testing my code. I've tried to give as much as information I could think of at the moment, however, please feel free to ask me if you need any more explanation. I'd really appreciate if you can help me solve this!

Cheers!

Client Code (Tester):

```<code>import time
import json
import requests
import random
import gzip
import base64

from Crypto.Cipher import AES

baseurl = 'http://0.0.0.0:80'
key = b'TfvY7I358yospfWKcoviZizOShpm5hyH'
iv = b'mb13KcoviZizvYhp'

MODE = AES.MODE_CFB
BLOCK_SIZE = 16
SEGMENT_SIZE = 128

def http_post(url, data):
    print('Going to make a request to {} with the following data: {}'.format(url, data))
    r = requests.post(url,
                      data=data,
                      headers={'Content-type': 'application/json; charset=utf-8',
                               'Connection': 'keep-alive'}, )
    if r.status_code != 200:
        print('Server returned unexpected response code {}, and content: {}'.format(r.status_code, r.content))
        return False
    else:
        data = r.json()
        return data

def post_sample_data(key, iv):
    fake_device_id = "MB88"
    Load_VA_Total_Mean = random.randint(1000, 100000)
    print('Data that should come back: {}'.format(Load_VA_Total_Mean))
    data = {"i": fake_device_id, "p": [
        {"d": [54.3, 0, 99, 49.35, 3, 99, 51.533, 1, 98, 28964, 7348, 43590, Load_VA_Total_Mean, 10350, 55200, 49.7],
         "t": time.time(), "dt": "p"}]}
    url = baseurl + '/realtimedata'
    encryption_key_reference = 1
    payload = '{}\n{}'.format(convert_pack(data, key, iv), encryption_key_reference)
    return http_post(url, payload)

def check_sample_request():
    fake_device_id = "MB88"
    url = baseurl + '/datapoints/powerzones/status'
    data = [{"name": "P1", "field": "Load_VA_Total_Mean", "devices": [{"id": fake_device_id, "multiplier": 1}]}]
    return http_post(url, json.dumps(data))

def convert_pack(inputdict, key, iv):
    print('input: {}'.format(inputdict))
    print('key: {}'.format(key))

    jsonpayload = json.dumps(inputdict)  # encode dict to json string
    print('json: {}'.format(jsonpayload))

    gzippayload = gzip.compress(jsonpayload.encode('utf-8'))  # compress with gzip
    print('gzip: {}'.format(gzippayload))

    encryptedpayload = base64.b64encode(encrypt(key, iv, gzippayload))
    print('encrypted: {}'.format(encryptedpayload))
    return str(encryptedpayload, encoding='utf-8')

def _pad_string(value):
    length = len(value)
    pad_size = BLOCK_SIZE - (length % BLOCK_SIZE)
    return value.ljust(length + pad_size, b'\x00')

def encrypt(key, iv, plaintext):
    aes = AES.new(key, MODE, iv, segment_size=SEGMENT_SIZE)
    plaintext = _pad_string(plaintext)
    encrypted_text = aes.encrypt(plaintext)
    return encrypted_text

post_sample_data(key, iv)
check_sample_request()
</code>```

Server Code (Tester):

```<code>package main

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "compress/gzip"
    "io/ioutil"
    "bytes"
    "strings"
)

func main() {
    //a sample input text generated by the client script
    originalText := "xhhpLqMJs4g8+8Hb751bcalljkeHDJfbGdMqr9E9im1OkiJzmdLr7pWv/Grh0+uzdeMQBMzefqzTrzetf1fZcBm93IEF6wl8WYE5x2uAZ5XY39bxlRWDt4cTNk/wWisbAMSzNJqQUq2UmqBLaWcI0LU1NGPZd8EKHK36Iwlp8NuP+YsQIJSmQdN2cvNFOLGv"
    fmt.Println("Original request: ", originalText)
    key := []byte("TfvY7I358yospfWKcoviZizOShpm5hyH")
    text := decrypt(key, originalText)

    gzReader, err1 := gzip.NewReader(bytes.NewReader(text))
    fmt.Println("GzReader: ", gzReader)
    if err1 != nil {
        fmt.Println("error1: ", err1)
    }

    content, err2 := ioutil.ReadAll(gzReader)
    if err2 != nil {
        fmt.Println("error2: ",err2)
    }

    fmt.Printf("\nReading: \n -> Content in bytes: %v \n -> Content in string: %s\n", content, string(content))
}

func decrypt(key []byte, cryptoText string) []byte {
    ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)
    fmt.Printf("\nDecoding: \n -> Original: %v \n -> Decoded in bytes: %v \n -> Decoded in string: %s\n", cryptoText, ciphertext, ciphertext)
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    iv := []byte("mb13KcoviZizvYhp")
    stream := cipher.NewCFBDecrypter(block, iv)
    stream.XORKeyStream(ciphertext, ciphertext)
    fmt.Printf("\nDecrypting: \n -> Decrypted in bytes: %v \n -> Decrypted in string: %s\n", ciphertext, ciphertext)

    ciphertext = bytes.Trim(ciphertext, "\x00")
    fmt.Printf("\nTrimming the padding: \n -> Decrypted in bytes: %v \n -> Decrypted in string: %s\n\n", ciphertext, ciphertext)
    return ciphertext
}
</code>```

The output in terminal:

Original request:

xhhpLqMJs4g8+8Hb751bcalljkeHDJfbGdMqr9E9im1OkiJzmdLr7pWv/Grh0+uzdeMQBMzefqzTrzetf1fZcBm93IEF6wl8WYE5x2uAZ5XY39bxlRWDt4cTNk/wWisbAMSzNJqQUq2UmqBLaWcI0LU1NGPZd8EKHK36Iwlp8NuP+YsQIJSmQdN2cvNFOLGv

Decoding:

-> Original: xhhpLqMJs4g8+8Hb751bcalljkeHDJfbGdMqr9E9im1OkiJzmdLr7pWv/Grh0+uzdeMQBMzefqzTrzetf1fZcBm93IEF6wl8WYE5x2uAZ5XY39bxlRWDt4cTNk/wWisbAMSzNJqQUq2UmqBLaWcI0LU1NGPZd8EKHK36Iwlp8NuP+YsQIJSmQdN2cvNFOLGv

-> Decoded in bytes: [198 24 105 46 163 9 179 136 60 251 193 219 239 157 91 113 169 101 142 71 135 12 151 219 25 211 42 175 209 61 138 109 78 146 34 115 153 210 235 238 149 175 252 106 225 211 235 179 117 227 16 4 204 222 126 172 211 175 55 173 127 87 217 112 25 189 220 129 5 235 9 124 89 129 57 199 107 128 103 149 216 223 214 241 149 21 131 183 135 19 54 79 240 90 43 27 0 196 179 52 154 144 82 173 148 154 160 75 105 103 8 208 181 53 52 99 217 119 193 10 28 173 250 35 9 105 240 219 143 249 139 16 32 148 166 65 211 118 114 243 69 56 177 175]

-> Decoded in string: �i.�     ��<����[q�e�G�
                                                ���*��=�mN�"s����j���u���~�ӯ7�W�p�܁�    |Y�9�k�g��������6O�Z+ĳ4��R����Kiе54c�w�
  ��#     i�ۏ�� ��A�vr�E8��

Decrypting:

-> Decrypted in bytes: [31 139 8 0 60 73 90 89 2 255 37 142 49 14 2 65 8 69 175 66 168 201 4 6 88 192 210 222 19 152 237 182 177 179 176 219 236 221 101 180 130 151 15 15 78 124 225 13 240 113 207 68 2 124 55 60 79 60 86 113 27 74 192 4 85 4 86 67 157 64 255 228 50 92 187 151 198 36 152 89 155 17 132 90 131 169 215 90 10 225 232 9 86 111 114 159 204 63 75 236 125 230 211 126 177 42 206 154 50 135 232 22 217 90 60 86 208 79 92 251 245 5 234 198 128 61 153 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  �q�D|7

Trimming the padding:

-> Decrypted in bytes: [31 139 8 0 60 73 90 89 2 255 37 142 49 14 2 65 8 69 175 66 168 201 4 6 88 192 210 222 19 152 237 182 177 179 176 219 236 221 101 180 130 151 15 15 78 124 225 13 240 113 207 68 2 124 55 60 79 60 86 113 27 74 192 4 85 4 86 67 157 64 255 228 50 92 187 151 198 36 152 89 155 17 132 90 131 169 215 90 10 225 232 9 86 111 114 159 204 63 75 236 125 230 211 126 177 42 206 154 50 135 232 22 217 90 60 86 208 79 92 251 245 5 234 198 128 61 153]
  �q�D|7

GzReader:  &{{ [] 2017-07-03 15:40:12 +0200 CEST  255} 0xc42007e150 0xc4200a8000 0 0 [31 139 8 0 60 73 90 89 2 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]  true}

error2:  unexpected EOF

Reading:

-> Content in bytes: [123 34 105 34 58 32 34 77 66 56 56 34 44 32 34 112 34 58 32 91 123 34 100 34 58 32 91 53 52 46 51 44 32 48 44 32 57 57 44 32 52 57 46 51 53 44 32 51 44 32 57 57 44 32 53 49 46 53 51 51 44 32 49 44 32 57 56 44 32 50 56 57 54 52 44 32 55 51 52 56 44 32 52 51 53 57 48 44 32 57 55 49 48 55 44 32 49 48 51 53 48 44 32 53 53 50 48 48 44 32 52 57 46 55 93 44 32 34 116 34 58 32 49 52 57 57 48 56 57 50 49 50 46 49 51 54 55 56 57 44 32 34 100 116 34 58 32 34 112 34 125 93 125]

-> Content in string: {"i": "MB88", "p": [{"d": [54.3, 0, 99, 49.35, 3, 99, 51.533, 1, 98, 28964, 7348, 43590, 97107, 10350, 55200, 49.7], "t": 1499089212.136789, "dt": "p"}]}

答:
When you think you're "trimming the padding", you're removing three zeros that belong on the end of the gzip stream. Just because it's a zero doesn't mean it's padding. Keep the three zeros after the 153.

When you're not trimming the padding, a gzip decoder will look for another gzip stream after it successfully decompresses the first one. Seeing zeros instead of a gzip header results in the invalid gzip header error.

You need to keep track of the size of the gzip stream, so that you know what's padding and what isn't. Or you can decode a gzip stream at a time, and when you see following zeros, you can conclude that that's padding.

Body:
I'm currently working on a project in which a client python script compresses the input by using gzip package, then, encrypts the compressed data according to AES, and, finally, it encodes the encrypted data in base64 encoding scheme. On the server side, which was written in golang I'm following the same steps in the reverse order to reach the original data.

As can be seen from the output, I can decode, decrypt and decompress the data received from the client on my test script. However, while reading the gzip.NewReader type it throws unexpected EOF error. (see the output at the very bottom of the question)

So far, I've done it without trimming the padding, however, then it gave me an invalid gzip header error. Then, just to verify if there are any significant differences between a valid gzip Reader and the one being created by the script, I gzipped the original data into a compressed form. Apparently, there were no notable differences I could see from outputs, but the differences in bytes which were most likely caused by the change in time that the readers are created:

Original data: {"i": "MB88", "p": [{"d": [54.3, 0, 99, 49.35, 3, 99, 51.533, 1, 98, 28964, 7348, 43590, 97107, 10350, 55200, 49.7], "t": 1499089212.136789, "dt": "p"}]}

Gzipped data: "\x1f\x8b\x08\x00\xf9w[Y\x02\xff%\x8e=\x0e\xc30\x08F\xaf\x82\x98\x91\x05\xe6\xc7\xa6c\xf7\x9e\xa0\xca\x96\xa5[\x86lQ\xee^\xdcN\xf0\xf4\xc1\x83\x0b?\xf8\x00|=\xe7D\x02<\n\xde\x17\xee\xab\xb85%\x82L\x02\xcb\xa6N\xa0\x7fri\xae\xd5K\xe1$\xe83\xc3\x08\x86Z\x81\xa9g-y\x88\xf6\x9a\xf5E\xde\x99\x7f\x96\xb1\xd5\x99\xb3\xfcb\x99\x121D\x1bG\xe7^.\xdcWPO\xdc\xdb\xfd\x05\x0ev\x15\x1d\x99\x00\x00\x00"

Gzip Reader created from the request by client

GzReader:  &{{ [] 2017-07-03 15:40:12 +0200 CEST  255} 0xc42007e150 0xc4200a8000 0 0 [31 139 8 0 60 73 90 89 2 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]  true}

Gzip Reader created by directly reading the original data

GzReader2:  &{{ [] 2017-07-04 13:11:53 +0200 CEST  255} 0xc4200741e0 0xc4200a9300 0 0 [31 139 8 0 249 119 91 89 2 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]  true}

Now, I'm quite curious about what might be causing this error and how this issue can be solved. I couldn't post the original scripts here due to some restrictions but these are the actual test scripts that I'm currently testing my code. I've tried to give as much as information I could think of at the moment, however, please feel free to ask me if you need any more explanation. I'd really appreciate if you can help me solve this!

Cheers!

Client Code (Tester):

import time
import json
import requests
import random
import gzip
import base64

from Crypto.Cipher import AES

baseurl = 'http://0.0.0.0:80'
key = b'TfvY7I358yospfWKcoviZizOShpm5hyH'
iv = b'mb13KcoviZizvYhp'

MODE = AES.MODE_CFB
BLOCK_SIZE = 16
SEGMENT_SIZE = 128

def http_post(url, data):
    print('Going to make a request to {} with the following data: {}'.format(url, data))
    r = requests.post(url,
                      data=data,
                      headers={'Content-type': 'application/json; charset=utf-8',
                               'Connection': 'keep-alive'}, )
    if r.status_code != 200:
        print('Server returned unexpected response code {}, and content: {}'.format(r.status_code, r.content))
        return False
    else:
        data = r.json()
        return data

def post_sample_data(key, iv):
    fake_device_id = "MB88"
    Load_VA_Total_Mean = random.randint(1000, 100000)
    print('Data that should come back: {}'.format(Load_VA_Total_Mean))
    data = {"i": fake_device_id, "p": [
        {"d": [54.3, 0, 99, 49.35, 3, 99, 51.533, 1, 98, 28964, 7348, 43590, Load_VA_Total_Mean, 10350, 55200, 49.7],
         "t": time.time(), "dt": "p"}]}
    url = baseurl + '/realtimedata'
    encryption_key_reference = 1
    payload = '{}\n{}'.format(convert_pack(data, key, iv), encryption_key_reference)
    return http_post(url, payload)

def check_sample_request():
    fake_device_id = "MB88"
    url = baseurl + '/datapoints/powerzones/status'
    data = [{"name": "P1", "field": "Load_VA_Total_Mean", "devices": [{"id": fake_device_id, "multiplier": 1}]}]
    return http_post(url, json.dumps(data))

def convert_pack(inputdict, key, iv):
    print('input: {}'.format(inputdict))
    print('key: {}'.format(key))

    jsonpayload = json.dumps(inputdict)  # encode dict to json string
    print('json: {}'.format(jsonpayload))

    gzippayload = gzip.compress(jsonpayload.encode('utf-8'))  # compress with gzip
    print('gzip: {}'.format(gzippayload))

    encryptedpayload = base64.b64encode(encrypt(key, iv, gzippayload))
    print('encrypted: {}'.format(encryptedpayload))
    return str(encryptedpayload, encoding='utf-8')

def _pad_string(value):
    length = len(value)
    pad_size = BLOCK_SIZE - (length % BLOCK_SIZE)
    return value.ljust(length + pad_size, b'\x00')

def encrypt(key, iv, plaintext):
    aes = AES.new(key, MODE, iv, segment_size=SEGMENT_SIZE)
    plaintext = _pad_string(plaintext)
    encrypted_text = aes.encrypt(plaintext)
    return encrypted_text

post_sample_data(key, iv)
check_sample_request()

Server Code (Tester):

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "compress/gzip"
    "io/ioutil"
    "bytes"
    "strings"
)

func main() {
    //a sample input text generated by the client script
    originalText := "xhhpLqMJs4g8+8Hb751bcalljkeHDJfbGdMqr9E9im1OkiJzmdLr7pWv/Grh0+uzdeMQBMzefqzTrzetf1fZcBm93IEF6wl8WYE5x2uAZ5XY39bxlRWDt4cTNk/wWisbAMSzNJqQUq2UmqBLaWcI0LU1NGPZd8EKHK36Iwlp8NuP+YsQIJSmQdN2cvNFOLGv"
    fmt.Println("Original request: ", originalText)
    key := []byte("TfvY7I358yospfWKcoviZizOShpm5hyH")
    text := decrypt(key, originalText)

    gzReader, err1 := gzip.NewReader(bytes.NewReader(text))
    fmt.Println("GzReader: ", gzReader)
    if err1 != nil {
        fmt.Println("error1: ", err1)
    }

    content, err2 := ioutil.ReadAll(gzReader)
    if err2 != nil {
        fmt.Println("error2: ",err2)
    }

    fmt.Printf("\nReading: \n -> Content in bytes: %v \n -> Content in string: %s\n", content, string(content))
}

func decrypt(key []byte, cryptoText string) []byte {
    ciphertext, _ := base64.StdEncoding.DecodeString(cryptoText)
    fmt.Printf("\nDecoding: \n -> Original: %v \n -> Decoded in bytes: %v \n -> Decoded in string: %s\n", cryptoText, ciphertext, ciphertext)
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    iv := []byte("mb13KcoviZizvYhp")
    stream := cipher.NewCFBDecrypter(block, iv)
    stream.XORKeyStream(ciphertext, ciphertext)
    fmt.Printf("\nDecrypting: \n -> Decrypted in bytes: %v \n -> Decrypted in string: %s\n", ciphertext, ciphertext)

    ciphertext = bytes.Trim(ciphertext, "\x00")
    fmt.Printf("\nTrimming the padding: \n -> Decrypted in bytes: %v \n -> Decrypted in string: %s\n\n", ciphertext, ciphertext)
    return ciphertext
}

The output in terminal:

Original request:

xhhpLqMJs4g8+8Hb751bcalljkeHDJfbGdMqr9E9im1OkiJzmdLr7pWv/Grh0+uzdeMQBMzefqzTrzetf1fZcBm93IEF6wl8WYE5x2uAZ5XY39bxlRWDt4cTNk/wWisbAMSzNJqQUq2UmqBLaWcI0LU1NGPZd8EKHK36Iwlp8NuP+YsQIJSmQdN2cvNFOLGv

Decoding:

-> Original: xhhpLqMJs4g8+8Hb751bcalljkeHDJfbGdMqr9E9im1OkiJzmdLr7pWv/Grh0+uzdeMQBMzefqzTrzetf1fZcBm93IEF6wl8WYE5x2uAZ5XY39bxlRWDt4cTNk/wWisbAMSzNJqQUq2UmqBLaWcI0LU1NGPZd8EKHK36Iwlp8NuP+YsQIJSmQdN2cvNFOLGv

-> Decoded in bytes: [198 24 105 46 163 9 179 136 60 251 193 219 239 157 91 113 169 101 142 71 135 12 151 219 25 211 42 175 209 61 138 109 78 146 34 115 153 210 235 238 149 175 252 106 225 211 235 179 117 227 16 4 204 222 126 172 211 175 55 173 127 87 217 112 25 189 220 129 5 235 9 124 89 129 57 199 107 128 103 149 216 223 214 241 149 21 131 183 135 19 54 79 240 90 43 27 0 196 179 52 154 144 82 173 148 154 160 75 105 103 8 208 181 53 52 99 217 119 193 10 28 173 250 35 9 105 240 219 143 249 139 16 32 148 166 65 211 118 114 243 69 56 177 175]

-> Decoded in string: �i.�     ��<����[q�e�G�
                                                ���*��=�mN�"s����j���u���~�ӯ7�W�p�܁�    |Y�9�k�g��������6O�Z+ĳ4��R����Kiе54c�w�
  ��#     i�ۏ�� ��A�vr�E8��

Decrypting:

-> Decrypted in bytes: [31 139 8 0 60 73 90 89 2 255 37 142 49 14 2 65 8 69 175 66 168 201 4 6 88 192 210 222 19 152 237 182 177 179 176 219 236 221 101 180 130 151 15 15 78 124 225 13 240 113 207 68 2 124 55 60 79 60 86 113 27 74 192 4 85 4 86 67 157 64 255 228 50 92 187 151 198 36 152 89 155 17 132 90 131 169 215 90 10 225 232 9 86 111 114 159 204 63 75 236 125 230 211 126 177 42 206 154 50 135 232 22 217 90 60 86 208 79 92 251 245 5 234 198 128 61 153 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
  �q�D|7

Trimming the padding:

-> Decrypted in bytes: [31 139 8 0 60 73 90 89 2 255 37 142 49 14 2 65 8 69 175 66 168 201 4 6 88 192 210 222 19 152 237 182 177 179 176 219 236 221 101 180 130 151 15 15 78 124 225 13 240 113 207 68 2 124 55 60 79 60 86 113 27 74 192 4 85 4 86 67 157 64 255 228 50 92 187 151 198 36 152 89 155 17 132 90 131 169 215 90 10 225 232 9 86 111 114 159 204 63 75 236 125 230 211 126 177 42 206 154 50 135 232 22 217 90 60 86 208 79 92 251 245 5 234 198 128 61 153]
  �q�D|7

GzReader:  &{{ [] 2017-07-03 15:40:12 +0200 CEST  255} 0xc42007e150 0xc4200a8000 0 0 [31 139 8 0 60 73 90 89 2 255 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]  true}

error2:  unexpected EOF

Reading:

-> Content in bytes: [123 34 105 34 58 32 34 77 66 56 56 34 44 32 34 112 34 58 32 91 123 34 100 34 58 32 91 53 52 46 51 44 32 48 44 32 57 57 44 32 52 57 46 51 53 44 32 51 44 32 57 57 44 32 53 49 46 53 51 51 44 32 49 44 32 57 56 44 32 50 56 57 54 52 44 32 55 51 52 56 44 32 52 51 53 57 48 44 32 57 55 49 48 55 44 32 49 48 51 53 48 44 32 53 53 50 48 48 44 32 52 57 46 55 93 44 32 34 116 34 58 32 49 52 57 57 48 56 57 50 49 50 46 49 51 54 55 56 57 44 32 34 100 116 34 58 32 34 112 34 125 93 125]

-> Content in string: {"i": "MB88", "p": [{"d": [54.3, 0, 99, 49.35, 3, 99, 51.533, 1, 98, 28964, 7348, 43590, 97107, 10350, 55200, 49.7], "t": 1499089212.136789, "dt": "p"}]}


问:
sails.js Getting a POST payload with text/plain content type
I'm developing a sails.js (node.js framework based on express) aplication, which is going great but ]I can't solve this detail...

I need to send POST requests cross domain from internet explorer 8 and 9. For that I'm forced to use xDomainRequest object, wich doesn't allow to set a Content type header.

So, when the request gets to the server the content type is "text/plain", which doesn't fire the bodyParser express middleware, so my req.body is an empty object and I can't see the payload I'm sending from the client.

For this I've tried two things with no luck:

First I wanted to set a header to the request in my first middleware, which is of course not available:

```<code>  req.set("Content-type", "Apli.....
</code>```

Then, I created a middleware that listens to req.on('data'), like this:

```<code>        var data = "";
    req.on('data', function(chunk){
        data += chunk;
    });
    req.on('end', function(){
       req.rawBody = data;
       next();
    });
</code>```

But the data event never fires!

Does anyone know how can I access my raw payload, so I can parse it myself.
Thanks!

答:
with newest version of Sails, using express is deprecated.
I needed to use a specific parser to get raw data from Stripe API.
Here is my code, maybe it will help somebody :</p>

```<code>bodyParser: function(req, res, next) {
  var skipper = require('skipper')();
  var rawParser = require("body-parser").raw({type: "*/*"});

  // Create and return the middleware function
  return function(req, res, next) {
    sails.log.debug(req.headers);
    if (req.headers && req.headers['stripe-signature']) {
      sails.log.info('request using raw parser middleware');
      return rawParser(req, res, next);
    }
    // Otherwise use Skipper to parse the body
    sails.log.info('request using skipper middleware');
    return skipper(req, res, next);
  };
},
</code>```

Body:
I'm developing a sails.js (node.js framework based on express) aplication, which is going great but ]I can't solve this detail...

I need to send POST requests cross domain from internet explorer 8 and 9. For that I'm forced to use xDomainRequest object, wich doesn't allow to set a Content type header.

So, when the request gets to the server the content type is "text/plain", which doesn't fire the bodyParser express middleware, so my req.body is an empty object and I can't see the payload I'm sending from the client.

For this I've tried two things with no luck:

First I wanted to set a header to the request in my first middleware, which is of course not available:

  req.set("Content-type", "Apli.....

Then, I created a middleware that listens to req.on('data'), like this:

        var data = "";
    req.on('data', function(chunk){
        data += chunk;
    });
    req.on('end', function(){
       req.rawBody = data;
       next();
    });

But the data event never fires!

Does anyone know how can I access my raw payload, so I can parse it myself.
Thanks!

Body:
with newest version of Sails, using express is deprecated.
I needed to use a specific parser to get raw data from Stripe API.
Here is my code, maybe it will help somebody :

bodyParser: function(req, res, next) {
  var skipper = require('skipper')();
  var rawParser = require("body-parser").raw({type: "*/*"});

  // Create and return the middleware function
  return function(req, res, next) {
    sails.log.debug(req.headers);
    if (req.headers && req.headers['stripe-signature']) {
      sails.log.info('request using raw parser middleware');
      return rawParser(req, res, next);
    }
    // Otherwise use Skipper to parse the body
    sails.log.info('request using skipper middleware');
    return skipper(req, res, next);
  };
},


问:
How to dynamic change component template at runtime?. Angular 4
I have a menu bar and action panel. A action panel is just simple div in which inside I want to display different components.

For example:
User click button A -> display Component A in action panel;
User click button B -> display Component B in action panel;

What is the best way to do this?

I thought to use ngswtich in my template, for example (pseudocode!).

```<code><div id="action-panel">
    <div [ngSwitch]="componentType">
        <div *ngSwitchCase="userComponent">
            <user-component></user-component>
        </div>
   </div>
</div>
</code>```

答:
Take a look at the routing and use sub routing for it.
Place a new <router-outlet></router-outlet> inside or instead of your action-panel and do sub state component.

This is a really good read and might enlighten you:
http://blog.angular-university.io/angular2-router/

Possible duplicate of Angular 2 - Submodule routing and nested <router-outlet>

Body:
I have a menu bar and action panel. A action panel is just simple div in which inside I want to display different components.

For example:
User click button A -> display Component A in action panel;
User click button B -> display Component B in action panel;

What is the best way to do this?

I thought to use ngswtich in my template, for example (pseudocode!).

            <user-component></user-component>


问:
Rerun (reschedule) onetime pipeline
I've created a new onetime pipeline in Azure Data Factory using Copy Data wizard.

The pipeline has 4 activities and it was run just fine - all 4 activities succeeded.

Now I'd like to rerun the pipeline. So I do:

Clone the pipeline.

Change name to [name]_rev2.

Remove start and end properties.

Deploy the cloned pipeline.

Now the status of the new cloned pipeline is Running.
But no activities are executed at all.

What's wrong?

答:
Mmmmm. Where to start!

In short. You can't just clone the pipeline. If its a one time data factory that you've created it won't have a schedule attached and therefore won't have any time slices provisioned that now require execution.

If your unsure how time slices in ADF work a recommend some reading around this concept.

Next, I recommend opening up a Visual Studio 2015 solution and downloading the data factory that did run as a project. Check out the various JSON blocks for scheduling and interval availability in the datasets, activities and the time frame in the pipeline.

Here's a handy guide for scheduling and execution to understand how to control your pipelines.

https://learn.microsoft.com/en-us/azure/data-factory/data-factory-scheduling-and-execution

Once you've made all the required changes (not just the name) publish the project to a new ADF service.

Hope this helps

Title: Rerun (reschedule) onetime pipeline


问:
Can you get the previous value of a variable in Java?
Say way have a variable (let's say String Str) and the value of Str starts of as " " then as some code is running it is set to "test" then somewhere else in the code it is changed again to say "tester". Now in the program I want to find out what the previous value of Str was. Is this possible in Java?

So I am saying that the variable gets changed twice, and you want to find out what Str was before it got changed for the second time. So in the example above the latest value of Str would be "tester" but I wanted to find out what Str was before this (assuming you had no idea what it was before it was changed to tester) in this case I would want to be able to find out that Str was "test".

Is it at all possible to do this in Java?

答:
Yes!! When you change the value, the value is changed only for the particular object. See the ex:</p>

```<code> class Test{
int a=100; //original value
 Test(int b){
    this.a=b;
 }
 Test(){
 }
void print(){
 System.out.println(a);
}
 public static void main(String args[]){
     Test t=new Test(9);
     Test t2=new Test();
     t.print();      //output: 9
     t2.print();     //output: 100
 }
}
</code>```

OwnerDisplayName: The Special One

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

Body:
Yes!! When you change the value, the value is changed only for the particular object. See the ex:

 class Test{
int a=100; //original value
 Test(int b){
    this.a=b;
 }
 Test(){
 }
void print(){
 System.out.println(a);
}
 public static void main(String args[]){
     Test t=new Test(9);
     Test t2=new Test();
     t.print();      //output: 9
     t2.print();     //output: 100
 }
}


问:
keyboard overlapping UITextField in Swift 4
i am trying to handle the scrolling of UITextField to avoid the keyboard to overlap it. Click here to view  current OUTPUT i am getting ]StoryBoard Screenshot. I tried to scroll the view when i click on the last textfield ..ie password field. When i click on the password field, only the email field ie the 2nd one is scrolling up. No scroll occur ion the first and last field. How can i solve this issue?

`

```<code>//
//  ViewController.swift

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var name: UITextField!

    @IBOutlet weak var email: UITextField!

    @IBOutlet weak var password: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Begin
        switch textField.tag {
        case 0...1:
            print("DO NOTHING")
        default:
            print("Do Scroll")

            scrollView.setContentOffset(CGPoint(x:0,y:100) , animated: true)
        }

    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // End
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         // Return

        if textField.tag == 0
        {
            email.becomeFirstResponder()
        }
        else if textField.tag == 1
        {
            password.becomeFirstResponder()

        }
        else if textField.tag == 2
        {
            textField.resignFirstResponder()

        }
        return true
    }

}
</code>```

`

答:
Unless you really want to handle the logic yourself, I recommend you give IQKeyboardManager a try!

It's a simple CocoaPod library that you import and enable in your appDelegate and well... that's all.

It's a codeless library so you really don't have to think about it ever again as it takes over and handles the repositioning of every textfields in the entire application.

Body:
i am trying to handle the scrolling of UITextField to avoid the keyboard to overlap it. Click here to view  current OUTPUT i am getting ]StoryBoard Screenshot. I tried to scroll the view when i click on the last textfield ..ie password field. When i click on the password field, only the email field ie the 2nd one is scrolling up. No scroll occur ion the first and last field. How can i solve this issue?

`

//
//  ViewController.swift

import UIKit

class ViewController: UIViewController,UITextFieldDelegate {

    @IBOutlet weak var scrollView: UIScrollView!

    @IBOutlet weak var name: UITextField!

    @IBOutlet weak var email: UITextField!

    @IBOutlet weak var password: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        // Begin
        switch textField.tag {
        case 0...1:
            print("DO NOTHING")
        default:
            print("Do Scroll")

            scrollView.setContentOffset(CGPoint(x:0,y:100) , animated: true)
        }

    }

    func textFieldDidEndEditing(_ textField: UITextField) {
        // End
        scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true)

    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
         // Return

        if textField.tag == 0
        {
            email.becomeFirstResponder()
        }
        else if textField.tag == 1
        {
            password.becomeFirstResponder()

        }
        else if textField.tag == 2
        {
            textField.resignFirstResponder()

        }
        return true
    }

}

`


问:
Ruby/PgSQL error on Rails start : cannot load such file -- pg_ext (LoadError)
I'm new to Ruby (coming from a Java background) and was given access to a RoR project from a Git repository.  I was able to get Ruby built with rbenv and Postgres installed via homebrew, installed the "pg" gem using the correct flags.  Any ways I did "bundle install" on the project and it created a bundle, when I went to start the server:...  any help will be definitely appreciated!</p>

```<code>$ rails s
/Users//Projects/The /vendor/bundle/gems/pg-0.14.1/lib/pg.rb:4:in require': cannot load such file -- pg_ext (LoadError)

from /Users//Projects/The Usic/vendor/bundle/gems/pg-0.14.1/lib/pg.rb:4:in <top (required)>'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:72:in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:72:in block (2 levels) in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:70:in each'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:70:in block in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:59:in each'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:59:in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler.rb:132:in require'
</code>```

答:
I've already installed the pg
gem list pg

I also encountered this problem and I made it work.
First, you run the command:
$ gem install pg --pre

Successfully installed pg-0.21.0-x64-mingw32

Next, you update your Gemfile: gem 'pg', '~> 0.21.0'. That's it.

My rubygems environment are as follow:

```<code>RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.12
  - RUBY VERSION: 2.3.3 (2016-11-21 patchlevel 222) [x64-mingw32]
  - INSTALLATION DIRECTORY: C:/Ruby23-x64/lib/ruby/gems/2.3.0
  - USER INSTALLATION DIRECTORY: C:/Users/armano/.gem/ruby/2.3.0
  - RUBY EXECUTABLE: C:/Ruby23-x64/bin/ruby.exe
  - EXECUTABLE DIRECTORY: C:/Ruby23-x64/bin
  - SPEC CACHE DIRECTORY: C:/Users/armano/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: C:/ProgramData
  - RUBYGEMS PLATFORMS:
    - ruby
    - x64-mingw32
  - GEM PATHS:
     - C:/Ruby23-x64/lib/ruby/gems/2.3.0
     - C:/Users/armano/.gem/ruby/2.3.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--no-ri --no-rdoc"
  - REMOTE SOURCES:
     - https://rubygems.org/
</code>```

Body:
I'm new to Ruby (coming from a Java background) and was given access to a RoR project from a Git repository.  I was able to get Ruby built with rbenv and Postgres installed via homebrew, installed the "pg" gem using the correct flags.  Any ways I did "bundle install" on the project and it created a bundle, when I went to start the server:...  any help will be definitely appreciated!

$ rails s
/Users//Projects/The /vendor/bundle/gems/pg-0.14.1/lib/pg.rb:4:in require': cannot load such file -- pg_ext (LoadError)

from /Users//Projects/The Usic/vendor/bundle/gems/pg-0.14.1/lib/pg.rb:4:in <top (required)>'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:72:in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:72:in block (2 levels) in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:70:in each'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:70:in block in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:59:in each'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler/runtime.rb:59:in require'

from /Users//.rbenv/versions/1.9.3-p392/lib/ruby/gems/1.9.1/gems/bundler-1.3.0/lib/bundler.rb:132:in require'

Body:
I've already installed the pg
gem list pg

I also encountered this problem and I made it work.
First, you run the command:
$ gem install pg --pre

Successfully installed pg-0.21.0-x64-mingw32

Next, you update your Gemfile: gem 'pg', '~> 0.21.0'. That's it.

My rubygems environment are as follow:

RubyGems Environment:
  - RUBYGEMS VERSION: 2.6.12
  - RUBY VERSION: 2.3.3 (2016-11-21 patchlevel 222) [x64-mingw32]
  - INSTALLATION DIRECTORY: C:/Ruby23-x64/lib/ruby/gems/2.3.0
  - USER INSTALLATION DIRECTORY: C:/Users/armano/.gem/ruby/2.3.0
  - RUBY EXECUTABLE: C:/Ruby23-x64/bin/ruby.exe
  - EXECUTABLE DIRECTORY: C:/Ruby23-x64/bin
  - SPEC CACHE DIRECTORY: C:/Users/armano/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: C:/ProgramData
  - RUBYGEMS PLATFORMS:
    - ruby
    - x64-mingw32
  - GEM PATHS:
     - C:/Ruby23-x64/lib/ruby/gems/2.3.0
     - C:/Users/armano/.gem/ruby/2.3.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
     - "gem" => "--no-ri --no-rdoc"
  - REMOTE SOURCES:
     - https://rubygems.org/


问:
Adding a const to an object literal in ES6
i am new to JS and i am trying to learn more about namespaces.

i am rewriting some animation tasks in ES6 and since use different animations for mobile and desktop animations i decided to put the mobile and desktop animations into their own namespaces.

however i am struggling  to create scrollmagic controller in this namespace so i would be able to use the same controller for all mobile animations.

this is my animation.js

```<code>export const controller = new ScrollMagic.Controller();

/**
 * Mobile animations
 */

export const mobile = {

  servicesHome: {
    init: () => {
      const trigger = document.querySelectorAll('.js-service-trigger');
      const elements = document.getElementsByClassName('js-service-tile__fig');

      trigger.forEach((id, i) => {
        const scene = new ScrollMagic.Scene({
          triggerElement: id,
          reverse: true,
          triggerHook: 1,
          offset: 0,
          duration: 280,
        })
          .on('enter', () => {
            elements[i].classList.add('js-service-tile__fig--is-active');
          })
          .on('leave', () => {
            elements[i].classList.remove('js-service-tile__fig--is-active');
          })
          .addTo(controller);
      });
    },
  },
 };
</code>```

i would prefer to achieve something like :

```<code>export const mobile = {

  controller: {
    const controller = new ScrollMagic.Controller();
  },

  servicesHome: {
    init: () => {
    .
    .
    .
          .addTo(this.controller);
      });
    },
  },
};
</code>```

so the controller could sit inside the namespace its used but i get 'const is a reserved word' error as well as i can't access the controller with this.controller

答:
It should be

```<code>const controller = new ScrollMagic.Controller();
export const mobile = {
  controller,
  ...
</code>```

Or if controller variable isn't used anywhere else, just

```<code>export const mobile = {
  controller: new ScrollMagic.Controller(),
  ...
</code>```

Body:
i am new to JS and i am trying to learn more about namespaces.

i am rewriting some animation tasks in ES6 and since use different animations for mobile and desktop animations i decided to put the mobile and desktop animations into their own namespaces.

however i am struggling  to create scrollmagic controller in this namespace so i would be able to use the same controller for all mobile animations.

this is my animation.js

export const controller = new ScrollMagic.Controller();

/**
 * Mobile animations
 */

export const mobile = {

  servicesHome: {
    init: () => {
      const trigger = document.querySelectorAll('.js-service-trigger');
      const elements = document.getElementsByClassName('js-service-tile__fig');

      trigger.forEach((id, i) => {
        const scene = new ScrollMagic.Scene({
          triggerElement: id,
          reverse: true,
          triggerHook: 1,
          offset: 0,
          duration: 280,
        })
          .on('enter', () => {
            elements[i].classList.add('js-service-tile__fig--is-active');
          })
          .on('leave', () => {
            elements[i].classList.remove('js-service-tile__fig--is-active');
          })
          .addTo(controller);
      });
    },
  },
 };

i would prefer to achieve something like :

export const mobile = {

  controller: {
    const controller = new ScrollMagic.Controller();
  },

  servicesHome: {
    init: () => {
    .
    .
    .
          .addTo(this.controller);
      });
    },
  },
};

so the controller could sit inside the namespace its used but i get 'const is a reserved word' error as well as i can't access the controller with this.controller

Body:
It should be

const controller = new ScrollMagic.Controller();
export const mobile = {
  controller,
  ...

Or if controller variable isn't used anywhere else, just

export const mobile = {
  controller: new ScrollMagic.Controller(),
  ...


问:
Input field validation for two numbers
I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.

JSFiddle

```<code><input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
<span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
</code>```

答: Your Fiddle seems to work, except maybe that the message is showing also when num2 is empty. Changing type="text" to "type="number" makes it behave more like you would expect.

Title: Input field validation for two numbers

Body:
I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.

JSFiddle

<input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
num2">Num2 cannot be lesser than num1


问:
Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)?
I have multiple selects:

```<code><select id="one">
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<select id="two">
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
</code>```

What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.

Here's the JS I have currently:

```<code>$(function () {
    var $one = $("#one");
    var $two = $("#two");

    var selectOptions = [];
    $("select").each(function (index) {
        selectOptions[index] = [];
        for (var i = 0; i < this.options.length; i++) {
            selectOptions[index][i] = this.options[i];
        }
    });

    $one.change(function () {
        var selectedValue = $("option:selected", this).val();
        for (var i = 0; i < selectOptions[1].length; i++) {
            var exists = false;
            for (var x = 0; x < $two[0].options.length; x++) {
                if ($two[0].options[x].value == selectOptions[1][i].value)
                    exists = true;
            }
            if (!exists)
                $two.append(selectOptions[1][i]);
        }

        $("option[value='" + selectedValue + "']", $two).remove();
    });
    $two.change(function () {
        var selectedValue = $("option:selected", this).val();
        for (var i = 0; i < selectOptions[0].length; i++) {
            var exists = false;
            for (var x = 0; x < $one[0].options.length; x++) {
                if ($one[0].options[x].value == selectOptions[0][i].value)
                    exists = true;
            }
            if (!exists)
                $one.append(selectOptions[0][i]);
        }

        $("option[value='" + selectedValue + "']", $one).remove();
    });
});
</code>```

But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6.

答: I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change.</p>

OwnerDisplayName: travis

Body:
I have multiple selects:

<select id="one">
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>
<select id="two">
  <option value="1">one</option>
  <option value="2">two</option>
  <option value="3">three</option>
</select>

What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.

Here's the JS I have currently:

$(function () {
    var $one = $("#one");
    var $two = $("#two");

    var selectOptions = [];
    $("select").each(function (index) {
        selectOptions[index] = [];
        for (var i = 0; i < this.options.length; i++) {
            selectOptions[index][i] = this.options[i];
        }
    });

    $one.change(function () {
        var selectedValue = $("option:selected", this).val();
        for (var i = 0; i < selectOptions[1].length; i++) {
            var exists = false;
            for (var x = 0; x < $two[0].options.length; x++) {
                if ($two[0].options[x].value == selectOptions[1][i].value)
                    exists = true;
            }
            if (!exists)
                $two.append(selectOptions[1][i]);
        }

        $("option[value='" + selectedValue + "']", $two).remove();
    });
    $two.change(function () {
        var selectedValue = $("option:selected", this).val();
        for (var i = 0; i < selectOptions[0].length; i++) {
            var exists = false;
            for (var x = 0; x < $one[0].options.length; x++) {
                if ($one[0].options[x].value == selectOptions[0][i].value)
                    exists = true;
            }
            if (!exists)
                $one.append(selectOptions[0][i]);
        }

        $("option[value='" + selectedValue + "']", $one).remove();
    });
});

But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6.

OwnerDisplayName: JasonBunting


问:
How to prevent from downloading and running script?
I wonder if it is possible in JavaScript to prevent  object from running?

I need to make it like it never existed. Is there an event where I can prevent from executing a script (based on src argument)?

I'm targeting Internet Explorer 8 but solution for other browsers are also welcomed (though it won't help me in anything ;)).

And please no JQuery or other libraries. I'm writing in C++ an IE add-on but I can use interfaces from MSHTML to 'use' JavaScript.

答:
Trying to block a free hosting websites ads? If you do that your site can be deleted by the hosting company so watch out.

There is really nothing you can do about it other than wrap it in conditional comments

```<code><!--[if IE 5]>
    <script src="foo.js"></script>
<![endif]-->
</code>```

but if it is being injected into the page, you probably can not wrap it.

Body:
Trying to block a free hosting websites ads? If you do that your site can be deleted by the hosting company so watch out.

There is really nothing you can do about it other than wrap it in conditional comments

<!--[if IE 5]>
    <script src="foo.js"></script>
<![endif]-->

but if it is being injected into the page, you probably can not wrap it.


问:
Using slick.js in autoplay mode for a single slide
I want to use slick.js for a simple news ticker. So I have a box where text is coming from the right and automatically scrolls to the left in a loop. The problem is that slick.js refuses to move the text if there is just one slide. I want the slide to move from the right to the left and after passing the left edge it should start moving from the right again. Does anyone know how to achieve this? Here is a little fiddle showing my problem. It uses this javascript code:</p>

```<code>$(function(){
    $('.slider').slick({
        speed: 10000,
        autoplay: true,
        autoplaySpeed: 0,
        cssEase: 'linear',
        slidesToShow: 1,
        slidesToScroll: 1,
        variableWidth: true,
        infinite: true
    });
});
</code>```

答:
Jon's answer is good, but it will give you two same slides which you can slide (change). If you wish to show single slide without cloning, you can use initialSlide setting.

$(function() {
    var start = 0;

  if ($('.slider div').length == 1) {
      start = -1;
  }

  $('.slider').slick({
    speed: 10000,
    autoplay: true,
    autoplaySpeed: 0,
    cssEase: 'linear',
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    infinite: true,
    initialSlide: start
  });
});
```

Body:
I want to use slick.js for a simple news ticker. So I have a box where text is coming from the right and automatically scrolls to the left in a loop. The problem is that slick.js refuses to move the text if there is just one slide. I want the slide to move from the right to the left and after passing the left edge it should start moving from the right again. Does anyone know how to achieve this? Here is a little fiddle showing my problem. It uses this javascript code:

$(function(){
    $('.slider').slick({
        speed: 10000,
        autoplay: true,
        autoplaySpeed: 0,
        cssEase: 'linear',
        slidesToShow: 1,
        slidesToScroll: 1,
        variableWidth: true,
        infinite: true
    });
});


问:
How to get ngtemplate-loader working with Webpack 3, Angular 1, TypeScript and ES 6 modules?
I am trying configure ngtemplate-loader to be able to use my angular template in a TypeScript file like so:

```<code>import myTemplateUrl from './hello-angular2-template.thtml';
angular
    .module('pd')
    .component('helloAngular2', {
        templateUrl: myTemplateUrl,
    });
</code>```

Loader definition in webpack.config:

```<code>module: {
    rules: [
        // Angular Template HTML
        {
            test: /\.thtml$/,
            use: [
                {
                    loader: 'ngtemplate-loader',
                },
                {
                    loader: 'html-loader',
                }
            ],
        },
</code>```

(The strange *.ththml suffix is just so, that no standard html-loader can interfere.)

However the template never gets loaded (is undefined after import).

I tried to add

```<code>options: {
    exportAsEs6Default: true
}
</code>```

to the chained html-loader, but that did not work out, too.

Full example project: https://github.com/eekboom/ng-webpack

答:
Looks like it is a bug/missing feature in ngtemplate-loader.

I created an issue:

https://github.com/WearyMonkey/ngtemplate-loader/issues/63

and a pull request that fixes it

https://github.com/WearyMonkey/ngtemplate-loader/pull/64

Hope it gets accepted soon. For now I can point my package.json to the commit containing the fix in my fork.

Body:
I am trying configure ngtemplate-loader to be able to use my angular template in a TypeScript file like so:

import myTemplateUrl from './hello-angular2-template.thtml';
angular
    .module('pd')
    .component('helloAngular2', {
        templateUrl: myTemplateUrl,
    });

Loader definition in webpack.config:

module: {
    rules: [
        // Angular Template HTML
        {
            test: /\.thtml$/,
            use: [
                {
                    loader: 'ngtemplate-loader',
                },
                {
                    loader: 'html-loader',
                }
            ],
        },

(The strange *.ththml suffix is just so, that no standard html-loader can interfere.)

However the template never gets loaded (is undefined after import).

I tried to add

options: {
    exportAsEs6Default: true
}

to the chained html-loader, but that did not work out, too.

Full example project: https://github.com/eekboom/ng-webpack


问:
Calling Fragment method from Parent Activity
I want to invoke a (tabbed)fragment method to bring the data to activity.

I read this

But I get null object reference

I tried this

But my activity is already implementing the fragment class so it's not a legal expression

So when the tab is changed I want the form of the first tab to send to details to Activity by getDetails() method

```<code>        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab.getText().equals("Owner")) {
                //invoking method here
                Log.i(TAG, tab.getText().toString() + " unselected");
            }
</code>```

I tried with FragmentManager but no luck, Please help!

EDIT- This is the method I want to invoke

```<code>public Bundle getData() {
    Bundle bundle = new Bundle();
    bundle.putString("area", area);
    bundle.putString("villageTown", villageTown.getSelectedItem().toString());
    bundle.putString("ownerName", ownerName);
    bundle.putString("fatherHusbandName", fatherHusbandName);
    bundle.putString("category", category.getSelectedItem().toString());
    bundle.putString("address", address);
    bundle.putString("mobileNumber", mobileNumber);
    bundle.putString("telephoneNumber", telephoneNumber);

    return bundle;
}
</code>```

答:
I assume you're using a ViewPager binded to a Tab. First you need to keep instances of your fragment which you use in your ViewPager.

I explained how you can get get the fragment instances which you use in ViewPager in this answer.
https://stackoverflow.com/a/39274141/1559852

You need a different onPageChangeListener implementation for your issue. You need to keep lastSelectedPosition of ViewPager and after page selected send your data to activity and than update the lastSelectedPosition. Here's an example implementation

```<code>    int lastSelectedPosition = viewPager.getCurrentItem();

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            // Here's your instance
            YourFragment fragment =(YourFragment)yourPagerAdapter.getRegisteredFragment(lastSelectedPosition);
            // Here're your details. You can update.
            YourDetails details = yourFragment.getDetils();
            lastSelectedPosition = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });
</code>```

I hope this'll help you. Good luck.

Body:
I want to invoke a (tabbed)fragment method to bring the data to activity.

I read this

But I get null object reference

I tried this

But my activity is already implementing the fragment class so it's not a legal expression

So when the tab is changed I want the form of the first tab to send to details to Activity by getDetails() method

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            if (tab.getText().equals("Owner")) {
                //invoking method here
                Log.i(TAG, tab.getText().toString() + " unselected");
            }

I tried with FragmentManager but no luck, Please help!

EDIT- This is the method I want to invoke

public Bundle getData() {
    Bundle bundle = new Bundle();
    bundle.putString("area", area);
    bundle.putString("villageTown", villageTown.getSelectedItem().toString());
    bundle.putString("ownerName", ownerName);
    bundle.putString("fatherHusbandName", fatherHusbandName);
    bundle.putString("category", category.getSelectedItem().toString());
    bundle.putString("address", address);
    bundle.putString("mobileNumber", mobileNumber);
    bundle.putString("telephoneNumber", telephoneNumber);

    return bundle;
}

Body:
I assume you're using a ViewPager binded to a Tab. First you need to keep instances of your fragment which you use in your ViewPager.

I explained how you can get get the fragment instances which you use in ViewPager in this answer.
https://stackoverflow.com/a/39274141/1559852

You need a different onPageChangeListener implementation for your issue. You need to keep lastSelectedPosition of ViewPager and after page selected send your data to activity and than update the lastSelectedPosition. Here's an example implementation

    int lastSelectedPosition = viewPager.getCurrentItem();

    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            // Here's your instance
            YourFragment fragment =(YourFragment)yourPagerAdapter.getRegisteredFragment(lastSelectedPosition);
            // Here're your details. You can update.
            YourDetails details = yourFragment.getDetils();
            lastSelectedPosition = position;
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

I hope this'll help you. Good luck.


问:
How do I rename a local Git branch?
How do I rename a local branch which has not yet been pushed to a remote repository?

Related:

Rename master branch for both local and remote Git repositories

How do I rename both a Git local and remote branch name?

答:
Changing the branch locally is quite easy...

If you are on the branch you want to change the name for, simply do this:

```<code>git branch -m my_new_branch
</code>```

Otherwise, if you are on master or any other branch other than the one you'd like to change the name, simply do:

```<code>git branch -m my_old_branch my_new_branch
</code>```

Also, I create the image below to show this in action on a command line. In this case, you are on master branch, for example:

ContentLicense: CC BY-SA 4.0

Title: How do I rename a local Git branch?

Body:
Changing the branch locally is quite easy...

If you are on the branch you want to change the name for, simply do this:

git branch -m my_new_branch

Otherwise, if you are on master or any other branch other than the one you'd like to change the name, simply do:

git branch -m my_old_branch my_new_branch

Also, I create the image below to show this in action on a command line. In this case, you are on master branch, for example:


问:
AngularJs - allow only one item to be selected in Table
I am using smart table. I have a logic behind where I only need one item to be selected. My current table code allow multiple lines to be selected.

This is my HTML:

```<code> <table st-safe-src="flow3.dataSet" st-table="flow3.displayed" class="table table-striped">

                <thead>
                <tr>
                    <th st-sort="method">Method</th>
                    <th st-sort="sample">Sample</th>
                    <th st-sort="parameters">Parameters</th>
                </tr>
                </thead>
                <tbody ui-sortable ng-model="flow3.displayed">
                <tr ng-repeat="row in flow3.displayed track by $index" style="cursor: move;" ng-click="row.selected = !row.selected; flow3.selectRow($event, row)" ng-class="{success: row.selected}">
                    <td>{{row.method.name}}</td>
                    <td>{{row.sample}}</td>
                    <td>
                        <span ng-repeat="parameter in row.parameters">{{parameter.methodInputParameter.name}} : {{parameter.value}}<br/></span>
                    </td>
                    <td>
                        <button type="button" ng-click="flow3.removeItem(row)"
                                class="btn btn-danger btn-sm btn-round pull-right"
                                ng-disabled="flow3.confirmDisabled">
                            <i class="glyphicon glyphicon-trash"></i>
                        </button>
                    </td>
                </tr>
                </tbody>
</table>
</code>```

This is my JS:

```<code> flow3.selectRow = function($event, row) {
        flow3.selectedItem = row;
}
</code>```

答:
If you want the only one row with selected property set to true, you should modify your selectRow method to accept the collection of all rows and then de-select all before selecting clicked one:

flow3.selectRow = function($event, row, rows) {
  //de-select all
  angular.forEach(rows, function(r){ r.selected = false; });
  //select clicked
  row.selected = true;
  flow3.selectedItem = row;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>ng-click="flow3.selectRow($event, row, flow3.dataSet)"</code>```

If you want to apply different css class to the clicked/selected item you probably can leave your selectRow method as is (since we have the selected item as flow3.selectedItem) and change the condition in the ngClass directive to be (if rows have some unique id property for example):

ng-class="{success: row.id === flow3.selectedItem.id}"```

Hope this helps.

Body:
I am using smart table. I have a logic behind where I only need one item to be selected. My current table code allow multiple lines to be selected.

This is my HTML:

                    Method
                    Sample
                    Parameters

                    {{row.method.name}}
                    {{row.sample}}

                        {{parameter.methodInputParameter.name}} : {{parameter.value}}

                        <button type="button" ng-click="flow3.removeItem(row)"
                                class="btn btn-danger btn-sm btn-round pull-right"
                                ng-disabled="flow3.confirmDisabled">

                        </button>

This is my JS:

 flow3.selectRow = function($event, row) {
        flow3.selectedItem = row;
}

Body:
If you want the only one row with selected property set to true, you should modify your selectRow method to accept the collection of all rows and then de-select all before selecting clicked one:

flow3.selectRow = function($event, row, rows) {
  //de-select all
  angular.forEach(rows, function(r){ r.selected = false; });
  //select clicked
  row.selected = true;
  flow3.selectedItem = row;
}

ng-click="flow3.selectRow($event, row, flow3.dataSet)"

If you want to apply different css class to the clicked/selected item you probably can leave your selectRow method as is (since we have the selected item as flow3.selectedItem) and change the condition in the ngClass directive to be (if rows have some unique id property for example):

ng-class="{success: row.id === flow3.selectedItem.id}"

Hope this helps.


问:
C#: how to use Microsoft.Win32.SafeHandles
Why does
using Microsoft.Win32.SafeHandles
cause the C# Compiler Error:

The type or namespace name
  'SafeHandles' does not exist in the
  namespace 'Microsoft.Win32'

This code is lifted from http://zachsaw.blogspot.com/2010/07/serialport-ioexception-workaround-in-c.html

答: If you want to use a SafeHandle in the Compact Framework, the SDF does include one.</p>


问:
Copy files which matches requirement to the new folder
I have original folder with 2000 files (patha), now I want to copy only the file which match my requirement (list in grdc_no) to new path (pathb). Here is my performance:

```<code>grdc_no <- grdc$grdc_no
# list of file name satisfied with my requirement

all_files <- list.files("patha", full.names = TRUE)

for (f in all_files) {

  for (i in 1:length(grdc_no)) {

    if (f == grdc_no[i]) {
      file.copy(f, "pathb")
    } else {}
  }
}
</code>```

However, it does not work. Any advice for me in this case? Many thanks

答:
You can easily do this without a loop (and especially a nested one) using lapply:

lapply(all_files[basename(all_files) %in% grdc_no],function(x) file.copy(x,"pathb"))

This will index files from all_files with a matching filename in the vector grdc_no and apply file.copy to it.

Body:
I have original folder with 2000 files (patha), now I want to copy only the file which match my requirement (list in grdc_no) to new path (pathb). Here is my performance:

grdc_no <- grdc$grdc_no
# list of file name satisfied with my requirement

all_files <- list.files("patha", full.names = TRUE)

for (f in all_files) {

  for (i in 1:length(grdc_no)) {

    if (f == grdc_no[i]) {
      file.copy(f, "pathb")
    } else {}
  }
}

However, it does not work. Any advice for me in this case? Many thanks


问:
Table keys and values in Lua - don't know how
I want make dynamic player table with two pieces of information. The player's SteamID, provided as a string, would be used as the key, and the value should be a number.

Should look like table = { "ExampleSteamID" = 3, "ExampleSteamID2" = 4 }

I found something like table.insert(table, { key = x, value = z}), but it did not work.

```<code>gameevent.Listen("player_connect")

local function AdminBotOnJoinCheck(data)
    local ply = data.networkid -- SteamID of joining player
    local tableisempty = true -- some random stuff
    for k, tableply in pairs(adminbot_players) do --checking for players already writed to table, maybe need fix
        if not ply == tableply then
            --need code here
            MsgC("\nAdminBot: Player table updated | ", ply, "\n")
        end
        tableisempty = false --clear table = table break - just dont execute code.
    end
    if tableisempty == true then
        --here same code
        MsgC("\nAdminBot: Player table updated | ", ply, "\n")
    end
    if file.Exists("adminbotplayers.txt", "DATA") == true and adminbot_teamkills_use_file == true then -- Random stuff for file writing
        local adminbot_players_json = util.TableToJSON(adminbot_players)
        file.Write("adminbotplayers.txt", adminbot_players_json)
    end
end
</code>```

答:
So if I correctly understand what you want to get...

You want to count each players teamkills and also want this value to be persistent.

Your approach however is not very ideal. The teamkill counter should be part of the player. This also would simplify and shorten your code.

Here is an example how you could do that.

```<code>-- You want to run this ASAP after the server is started and the world loaded

local playerMeta = FindMetaTable( "Player" ) -- get the meta table for player

function playerMeta:AddTeamkill() -- this function will increase the counter
    local teamkills = self:GetPData("teamkills", 0)
    self:SetPData("teamkills", teamkills + 1)
end

function playerMeta:GetTeamkills() -- this function will return the current counter
    return self:GetPData("teamkills", 0)
end

-- Feel free to add more functions here... Maybe a 'SetTeamkills' or 'ResetTeamkills'
</code>```

You can then use it like this:

```<code>-- Add a teamkill
local player_that_teamkilled = player.GetByID(1) -- you obviously would get the player a different way...
player_that_teamkilled:AddTeamkill()

-- Get teamkills
local somePlayer = player.GetByID(1) -- same as above
somePlayer:GetTeamkills()
</code>```

You do not have to mess with code for loading and saving the counter. You also don't have information related to players sitting in a different table. This means you don't have to keep track of which line in the table belongs to who. And this means, you do not have to search in a (probably huge) table for the correct line to just modify (or read) one number.

The counter will be saved into the sv.db or if you run this code on a client (which you should not do) in cl.db

Please note: You have to sync the counter to the client manually, which shouldn't be a big deal.

Further reading:

FindMetaTable()

Player:GetPData()

Player:SetPData()

Body:
I want make dynamic player table with two pieces of information. The player's SteamID, provided as a string, would be used as the key, and the value should be a number.

Should look like table = { "ExampleSteamID" = 3, "ExampleSteamID2" = 4 }

I found something like table.insert(table, { key = x, value = z}), but it did not work.

gameevent.Listen("player_connect")

local function AdminBotOnJoinCheck(data)
    local ply = data.networkid -- SteamID of joining player
    local tableisempty = true -- some random stuff
    for k, tableply in pairs(adminbot_players) do --checking for players already writed to table, maybe need fix
        if not ply == tableply then
            --need code here
            MsgC("\nAdminBot: Player table updated | ", ply, "\n")
        end
        tableisempty = false --clear table = table break - just dont execute code.
    end
    if tableisempty == true then
        --here same code
        MsgC("\nAdminBot: Player table updated | ", ply, "\n")
    end
    if file.Exists("adminbotplayers.txt", "DATA") == true and adminbot_teamkills_use_file == true then -- Random stuff for file writing
        local adminbot_players_json = util.TableToJSON(adminbot_players)
        file.Write("adminbotplayers.txt", adminbot_players_json)
    end
end

Body:
So if I correctly understand what you want to get...

You want to count each players teamkills and also want this value to be persistent.

Your approach however is not very ideal. The teamkill counter should be part of the player. This also would simplify and shorten your code.

Here is an example how you could do that.

-- You want to run this ASAP after the server is started and the world loaded

local playerMeta = FindMetaTable( "Player" ) -- get the meta table for player

function playerMeta:AddTeamkill() -- this function will increase the counter
    local teamkills = self:GetPData("teamkills", 0)
    self:SetPData("teamkills", teamkills + 1)
end

function playerMeta:GetTeamkills() -- this function will return the current counter
    return self:GetPData("teamkills", 0)
end

-- Feel free to add more functions here... Maybe a 'SetTeamkills' or 'ResetTeamkills'

You can then use it like this:

-- Add a teamkill
local player_that_teamkilled = player.GetByID(1) -- you obviously would get the player a different way...
player_that_teamkilled:AddTeamkill()

-- Get teamkills
local somePlayer = player.GetByID(1) -- same as above
somePlayer:GetTeamkills()

You do not have to mess with code for loading and saving the counter. You also don't have information related to players sitting in a different table. This means you don't have to keep track of which line in the table belongs to who. And this means, you do not have to search in a (probably huge) table for the correct line to just modify (or read) one number.

The counter will be saved into the sv.db or if you run this code on a client (which you should not do) in cl.db

Please note: You have to sync the counter to the client manually, which shouldn't be a big deal.

Further reading:

FindMetaTable()

Player:GetPData()

Player:SetPData()


问:
How to align portfolio items in height?
I would like to align these items in height:

Since I have little clue of what's going on, I'm going to paste what I THINK it's the relevant code:

#portfolio .portfolio-item {
      margin: 0 0 15px;
      right: 0;
    }
    #portfolio .portfolio-item .portfolio-link {
      display: block;
      position: relative;
      max-width: 400px;
      margin: 0 auto;
    }
    #portfolio .portfolio-item .portfolio-caption {
      max-width: 400px;
      margin: 0 auto;
      background-color: white;
      text-align: center;
      padding: 25px;
    }
    #portfolio .portfolio-item .portfolio-caption h4 {
      text-transform: none;
      margin: 0;
    }
    #portfolio .portfolio-item .portfolio-caption p {
      font-family: "Droid Serif", "Helvetica Neue", sans-serif;
      font-style: italic;
      font-size: 16px;
      margin: 0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section id="portfolio" class="bg-light-gray">
        <div class="container">
            <div class="row">
              <div class="col-lg-12 text-center">
                    <h2 class="section-heading">Portfolio</h2>
                    <h3 class="section-subheading text-muted">Here I show some of my work.</h3>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>1st job</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img2.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>2nd job</h4>
                        <p class="text-muted">Design</p>
                        <br>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img3.png" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>3rd job</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img4.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>Beach Tennis Brand</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click to watch</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img5.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>NGO "4th job"</h4>
                        <p class="text-muted">Design</p>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6 portfolio-item">

                        <div class="portfolio-hover">
                            <div class="portfolio-hover-content">
                                <i class="fa fa-plus fa-3x"></i>
                                <p>click for more</p>
                            </div>
                        </div>
                        <img src="img/portfolio/img6.jpg" class="img-responsive" alt="">

                    <div class="portfolio-caption">
                        <h4>Design</h4>
                        <p class="text-muted">5th job</p>
                    </div>
                </div>
            </div>
        </div>
    </section></code>```

Any help appreciated!

答:
There's maybe a better way of doing this but what i will recommand you to do is to wrap the img element inside a div like this :

```<code><div class="img-wrap"><img src="source.png" class="img-full"></div>
</code>```

Then you give the img-wrap 100% width and a fixed height of lets say 200px with an overflow hidden

```<code>.img-wrap{
width:100%;
height:200px;
overflow:hidden;
background:#cccccc;
}
</code>```

Last you give the img max-height of 200px;

```<code>.img-full{
max-width:100%;
max-height:200px;
}
</code>```

it should do the work. This way your image keeps it's proportions.

Title: How to align portfolio items in height?

Body:
I would like to align these items in height:

Since I have little clue of what's going on, I'm going to paste what I THINK it's the relevant code:

#portfolio .portfolio-item {
      margin: 0 0 15px;
      right: 0;
    }
    #portfolio .portfolio-item .portfolio-link {
      display: block;
      position: relative;
      max-width: 400px;
      margin: 0 auto;
    }
    #portfolio .portfolio-item .portfolio-caption {
      max-width: 400px;
      margin: 0 auto;
      background-color: white;
      text-align: center;
      padding: 25px;
    }
    #portfolio .portfolio-item .portfolio-caption h4 {
      text-transform: none;
      margin: 0;
    }
    #portfolio .portfolio-item .portfolio-caption p {
      font-family: "Droid Serif", "Helvetica Neue", sans-serif;
      font-style: italic;
      font-size: 16px;
      margin: 0;
    }

Portfolio

Here I show some of my work.

click for more

1st job

Design

click for more

2nd job

Design

click for more

3rd job

Design

click for more

Beach Tennis Brand

Design

click to watch

NGO "4th job"

Design

click for more

Design

5th job

Any help appreciated!

Body:
There's maybe a better way of doing this but what i will recommand you to do is to wrap the img element inside a div like this :

<div class="img-wrap"><img src="source.png" class="img-full"></div>

Then you give the img-wrap 100% width and a fixed height of lets say 200px with an overflow hidden

.img-wrap{
width:100%;
height:200px;
overflow:hidden;
background:#cccccc;
}

Last you give the img max-height of 200px;

.img-full{
max-width:100%;
max-height:200px;
}

it should do the work. This way your image keeps it's proportions.


问:
Unique constraint on two database columns with reverse direction
I'm stuck upon a following problem: Let's say I have a table with relations to itself:

```<code>CREATE TABLE ITEM (
    ID NUMBER(18) PRIMARY KEY,
    NAME VARCHAR2(100 CHAR) NOT NULL
);

ALTER TABLE ITEM ADD CONSTRAINT PK_ITEM PRIMARY KEY (ID);

CREATE TABLE ITEM_RELATION (
    FIRST_ITEM_ID NUMBER(18) NOT NULL,
    SECOND_ITEM_ID NUMBER(18) NOT NULL,
    RELATION_TYPE VARCHAR2(1) NOT NULL
);

ALTER TABLE ITEM_RELATION ADD CONSTRAINT PK_ITEM_RELATION PRIMARY KEY (FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE);
--ALTER TABLE ITEM_RELATION ADD CONSTRAINT UK_ITEMS UNIQUE (FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE);
ALTER TABLE ITEM_RELATION ADD CONSTRAINT FK_FIRST_ITEM FOREIGN KEY (FIRST_ITEM_ID) REFERENCES ITEM(ID);
ALTER TABLE ITEM_RELATION ADD CONSTRAINT FK_SECOND_ITEM FOREIGN KEY (SECOND_ITEM_ID) REFERENCES ITEM(ID);
</code>```

Now let's say, I wan't the relation to be directional, that is if item 1 has relation to item 2 of certain type, the item 2 shouldn't have the same relation to item 1.

That is, the following should not be permitted:

```<code>INSERT INTO ITEM (ID, NAME) VALUES (1, 'Item 1');
INSERT INTO ITEM (ID, NAME) VALUES (2, 'Item 2');
INSERT INTO ITEM_RELATION(FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE) VALUES (1, 2, 'R');
INSERT INTO ITEM_RELATION(FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE) VALUES (2, 1, 'R');
</code>```

It means that the table ITEM_RELATION defines a direction of this connection, and it shouldn't be allowed to add a reversed relation.

Is it possible with Oracle DB?

答:
You can do this with a unique index.  In Oracle, you can use functions in indexes, so this will work:

```<code>create unique index unq_item_relation_3 on
     item_relation(RELATION_TYPE ,
                   least(FIRST_ITEM_ID, SECOND_ITEM_ID),
                   greatest(FIRST_ITEM_ID, SECOND_ITEM_ID)
                  );
</code>```

You could get the same effect with a check constraint, by requiring that FIRST_ITEM_ID be less than SECOND_ITEM_ID:

```<code>alter table item_relation add constraint chk_item_relation_2
    check ((FIRST_ITEM_ID < SECOND_ITEM_ID);
</code>```

However, this requires that the items be inserted in a particular order.

Body:
I'm stuck upon a following problem: Let's say I have a table with relations to itself:

CREATE TABLE ITEM (
    ID NUMBER(18) PRIMARY KEY,
    NAME VARCHAR2(100 CHAR) NOT NULL
);

ALTER TABLE ITEM ADD CONSTRAINT PK_ITEM PRIMARY KEY (ID);

CREATE TABLE ITEM_RELATION (
    FIRST_ITEM_ID NUMBER(18) NOT NULL,
    SECOND_ITEM_ID NUMBER(18) NOT NULL,
    RELATION_TYPE VARCHAR2(1) NOT NULL
);

ALTER TABLE ITEM_RELATION ADD CONSTRAINT PK_ITEM_RELATION PRIMARY KEY (FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE);
--ALTER TABLE ITEM_RELATION ADD CONSTRAINT UK_ITEMS UNIQUE (FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE);
ALTER TABLE ITEM_RELATION ADD CONSTRAINT FK_FIRST_ITEM FOREIGN KEY (FIRST_ITEM_ID) REFERENCES ITEM(ID);
ALTER TABLE ITEM_RELATION ADD CONSTRAINT FK_SECOND_ITEM FOREIGN KEY (SECOND_ITEM_ID) REFERENCES ITEM(ID);

Now let's say, I wan't the relation to be directional, that is if item 1 has relation to item 2 of certain type, the item 2 shouldn't have the same relation to item 1.

That is, the following should not be permitted:

INSERT INTO ITEM (ID, NAME) VALUES (1, 'Item 1');
INSERT INTO ITEM (ID, NAME) VALUES (2, 'Item 2');
INSERT INTO ITEM_RELATION(FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE) VALUES (1, 2, 'R');
INSERT INTO ITEM_RELATION(FIRST_ITEM_ID, SECOND_ITEM_ID, RELATION_TYPE) VALUES (2, 1, 'R');

It means that the table ITEM_RELATION defines a direction of this connection, and it shouldn't be allowed to add a reversed relation.

Is it possible with Oracle DB?

Body:
You can do this with a unique index.  In Oracle, you can use functions in indexes, so this will work:

create unique index unq_item_relation_3 on
     item_relation(RELATION_TYPE ,
                   least(FIRST_ITEM_ID, SECOND_ITEM_ID),
                   greatest(FIRST_ITEM_ID, SECOND_ITEM_ID)
                  );

You could get the same effect with a check constraint, by requiring that FIRST_ITEM_ID be less than SECOND_ITEM_ID:

alter table item_relation add constraint chk_item_relation_2
    check ((FIRST_ITEM_ID < SECOND_ITEM_ID);

However, this requires that the items be inserted in a particular order.