问:
Cant ssh into server even though security group allows it
I have the following script:

```<code>provider "aws" {
  access_key = "xxx"
  secret_key = "xxx"
  region     = "sa-east-1"
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_internet_gateway" "igw" {
    vpc_id = "${aws_vpc.main.id}"
    tags {
        Name = "igw"
    }
}

resource "aws_subnet" "main" {
  vpc_id     = "${aws_vpc.main.id}"
  cidr_block = "10.0.1.0/24"

  tags {
    Name = "Main"
  }

  depends_on = [
        "aws_internet_gateway.igw"
    ]
}

resource "aws_security_group" "ssh" {
  name        = "ssh"
  description = "(Proxy) Allow SSH"
  vpc_id      = "${aws_vpc.main.id}"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "proxy" {
  ami             = "ami-286f2a44"
  instance_type   = "t2.micro"
  key_name        = "spkeypar"
  subnet_id       = "${aws_subnet.main.id}"
  security_groups = ["${aws_security_group.ssh.id}"]
  associate_public_ip_address  = false
}

resource "aws_eip" "pib" {
  instance = "${aws_instance.proxy.id}"
  vpc      = true
}

output "ip" {
  value = "${aws_eip.pib.public_ip}"
}
</code>```

when it finishes, I can see all was created, I can the security group with port 22 open and correctly attached to the instance, but I cannot ssh into it at all. I'm using the public ip from Elastic Ip.

This is the output of terraform plan:

```<code>Terraform will perform the following actions:

  + aws_eip.pib
      id:                                    <computed>
      allocation_id:                         <computed>
      association_id:                        <computed>
      domain:                                <computed>
      instance:                              "${aws_instance.proxy.id}"
      network_interface:                     <computed>
      private_ip:                            <computed>
      public_ip:                             <computed>
      vpc:                                   "true"

  + aws_instance.proxy
      id:                                    <computed>
      ami:                                   "ami-286f2a44"
      associate_public_ip_address:           "false"
      availability_zone:                     <computed>
      ebs_block_device.#:                    <computed>
      ephemeral_block_device.#:              <computed>
      instance_state:                        <computed>
      instance_type:                         "t2.micro"
      ipv6_address_count:                    <computed>
      ipv6_addresses.#:                      <computed>
      key_name:                              "spkeypar"
      network_interface.#:                   <computed>
      network_interface_id:                  <computed>
      placement_group:                       <computed>
      primary_network_interface_id:          <computed>
      private_dns:                           <computed>
      private_ip:                            <computed>
      public_dns:                            <computed>
      public_ip:                             <computed>
      root_block_device.#:                   <computed>
      security_groups.#:                     <computed>
      source_dest_check:                     "true"
      subnet_id:                             "${aws_subnet.main.id}"
      tenancy:                               <computed>
      volume_tags.%:                         <computed>
      vpc_security_group_ids.#:              <computed>

  + aws_internet_gateway.igw
      id:                                    <computed>
      tags.%:                                "1"
      tags.Name:                             "igw"
      vpc_id:                                "${aws_vpc.main.id}"

  + aws_security_group.ssh
      id:                                    <computed>
      description:                           "(Proxy) Allow SSH"
      egress.#:                              "1"
      egress.482069346.cidr_blocks.#:        "1"
      egress.482069346.cidr_blocks.0:        "0.0.0.0/0"
      egress.482069346.description:          ""
      egress.482069346.from_port:            "0"
      egress.482069346.ipv6_cidr_blocks.#:   "0"
      egress.482069346.prefix_list_ids.#:    "0"
      egress.482069346.protocol:             "-1"
      egress.482069346.security_groups.#:    "0"
      egress.482069346.self:                 "false"
      egress.482069346.to_port:              "0"
      ingress.#:                             "1"
      ingress.2541437006.cidr_blocks.#:      "1"
      ingress.2541437006.cidr_blocks.0:      "0.0.0.0/0"
      ingress.2541437006.description:        ""
      ingress.2541437006.from_port:          "22"
      ingress.2541437006.ipv6_cidr_blocks.#: "0"
      ingress.2541437006.protocol:           "tcp"
      ingress.2541437006.security_groups.#:  "0"
      ingress.2541437006.self:               "false"
      ingress.2541437006.to_port:            "22"
      name:                                  "ssh"
      owner_id:                              <computed>
      revoke_rules_on_delete:                "false"
      vpc_id:                                "${aws_vpc.main.id}"

  + aws_subnet.main
      id:                                    <computed>
      assign_ipv6_address_on_creation:       "false"
      availability_zone:                     <computed>
      cidr_block:                            "10.0.1.0/24"
      ipv6_cidr_block:                       <computed>
      ipv6_cidr_block_association_id:        <computed>
      map_public_ip_on_launch:               "false"
      tags.%:                                "1"
      tags.Name:                             "Main"
      vpc_id:                                "${aws_vpc.main.id}"

  + aws_vpc.main
      id:                                    <computed>
      assign_generated_ipv6_cidr_block:      "false"
      cidr_block:                            "10.0.0.0/16"
      default_network_acl_id:                <computed>
      default_route_table_id:                <computed>
      default_security_group_id:             <computed>
      dhcp_options_id:                       <computed>
      enable_classiclink:                    <computed>
      enable_classiclink_dns_support:        <computed>
      enable_dns_hostnames:                  <computed>
      enable_dns_support:                    "true"
      instance_tenancy:                      <computed>
      ipv6_association_id:                   <computed>
      ipv6_cidr_block:                       <computed>
      main_route_table_id:                   <computed>

Plan: 6 to add, 0 to change, 0 to destroy.
</code>```

I've read the docs but couldn't found any clue

答:
Looks like you lack EIP-to-instance association as described in https://www.terraform.io/docs/providers/aws/r/eip_association.html

```<code>resource "aws_eip_association" "eip_assoc" {
  instance_id   = "${aws_instance.proxy.id}"
  allocation_id = "${aws_eip.pib.id}"
}
</code>```

Ok, that wasn't it... Public routing then another possibility that I see is missing (In other words, route everything in that subnet towards IGW):

```<code># Public routing
resource "aws_route_table" "public" {
  vpc_id = "${aws_vpc.main.id}"
}

resource "aws_route" "public_default" {
  route_table_id = "${aws_route_table.public.id}"
  gateway_id     = "${aws_internet_gateway.igw.id}"

  destination_cidr_block = "0.0.0.0/0"
}

resource "aws_route_table_association" "public" {
  subnet_id      = "${aws_subnet.main.id}"
  route_table_id = "${aws_route_table.public.id}"
}
</code>```

And in your subnet definition you need:

```<code>  map_public_ip_on_launch = true
</code>```

Otherwise it will be a private subnet.

Body:
I have the following script:

provider "aws" {
  access_key = "xxx"
  secret_key = "xxx"
  region     = "sa-east-1"
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_internet_gateway" "igw" {
    vpc_id = "${aws_vpc.main.id}"
    tags {
        Name = "igw"
    }
}

resource "aws_subnet" "main" {
  vpc_id     = "${aws_vpc.main.id}"
  cidr_block = "10.0.1.0/24"

  tags {
    Name = "Main"
  }

  depends_on = [
        "aws_internet_gateway.igw"
    ]
}

resource "aws_security_group" "ssh" {
  name        = "ssh"
  description = "(Proxy) Allow SSH"
  vpc_id      = "${aws_vpc.main.id}"

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  egress {
    from_port       = 0
    to_port         = 0
    protocol        = "-1"
    cidr_blocks     = ["0.0.0.0/0"]
  }
}

resource "aws_instance" "proxy" {
  ami             = "ami-286f2a44"
  instance_type   = "t2.micro"
  key_name        = "spkeypar"
  subnet_id       = "${aws_subnet.main.id}"
  security_groups = ["${aws_security_group.ssh.id}"]
  associate_public_ip_address  = false
}

resource "aws_eip" "pib" {
  instance = "${aws_instance.proxy.id}"
  vpc      = true
}

output "ip" {
  value = "${aws_eip.pib.public_ip}"
}

when it finishes, I can see all was created, I can the security group with port 22 open and correctly attached to the instance, but I cannot ssh into it at all. I'm using the public ip from Elastic Ip.

This is the output of terraform plan:

Terraform will perform the following actions:

  + aws_eip.pib
      id:                                    <computed>
      allocation_id:                         <computed>
      association_id:                        <computed>
      domain:                                <computed>
      instance:                              "${aws_instance.proxy.id}"
      network_interface:                     <computed>
      private_ip:                            <computed>
      public_ip:                             <computed>
      vpc:                                   "true"

  + aws_instance.proxy
      id:                                    <computed>
      ami:                                   "ami-286f2a44"
      associate_public_ip_address:           "false"
      availability_zone:                     <computed>
      ebs_block_device.#:                    <computed>
      ephemeral_block_device.#:              <computed>
      instance_state:                        <computed>
      instance_type:                         "t2.micro"
      ipv6_address_count:                    <computed>
      ipv6_addresses.#:                      <computed>
      key_name:                              "spkeypar"
      network_interface.#:                   <computed>
      network_interface_id:                  <computed>
      placement_group:                       <computed>
      primary_network_interface_id:          <computed>
      private_dns:                           <computed>
      private_ip:                            <computed>
      public_dns:                            <computed>
      public_ip:                             <computed>
      root_block_device.#:                   <computed>
      security_groups.#:                     <computed>
      source_dest_check:                     "true"
      subnet_id:                             "${aws_subnet.main.id}"
      tenancy:                               <computed>
      volume_tags.%:                         <computed>
      vpc_security_group_ids.#:              <computed>

  + aws_internet_gateway.igw
      id:                                    <computed>
      tags.%:                                "1"
      tags.Name:                             "igw"
      vpc_id:                                "${aws_vpc.main.id}"

  + aws_security_group.ssh
      id:                                    <computed>
      description:                           "(Proxy) Allow SSH"
      egress.#:                              "1"
      egress.482069346.cidr_blocks.#:        "1"
      egress.482069346.cidr_blocks.0:        "0.0.0.0/0"
      egress.482069346.description:          ""
      egress.482069346.from_port:            "0"
      egress.482069346.ipv6_cidr_blocks.#:   "0"
      egress.482069346.prefix_list_ids.#:    "0"
      egress.482069346.protocol:             "-1"
      egress.482069346.security_groups.#:    "0"
      egress.482069346.self:                 "false"
      egress.482069346.to_port:              "0"
      ingress.#:                             "1"
      ingress.2541437006.cidr_blocks.#:      "1"
      ingress.2541437006.cidr_blocks.0:      "0.0.0.0/0"
      ingress.2541437006.description:        ""
      ingress.2541437006.from_port:          "22"
      ingress.2541437006.ipv6_cidr_blocks.#: "0"
      ingress.2541437006.protocol:           "tcp"
      ingress.2541437006.security_groups.#:  "0"
      ingress.2541437006.self:               "false"
      ingress.2541437006.to_port:            "22"
      name:                                  "ssh"
      owner_id:                              <computed>
      revoke_rules_on_delete:                "false"
      vpc_id:                                "${aws_vpc.main.id}"

  + aws_subnet.main
      id:                                    <computed>
      assign_ipv6_address_on_creation:       "false"
      availability_zone:                     <computed>
      cidr_block:                            "10.0.1.0/24"
      ipv6_cidr_block:                       <computed>
      ipv6_cidr_block_association_id:        <computed>
      map_public_ip_on_launch:               "false"
      tags.%:                                "1"
      tags.Name:                             "Main"
      vpc_id:                                "${aws_vpc.main.id}"

  + aws_vpc.main
      id:                                    <computed>
      assign_generated_ipv6_cidr_block:      "false"
      cidr_block:                            "10.0.0.0/16"
      default_network_acl_id:                <computed>
      default_route_table_id:                <computed>
      default_security_group_id:             <computed>
      dhcp_options_id:                       <computed>
      enable_classiclink:                    <computed>
      enable_classiclink_dns_support:        <computed>
      enable_dns_hostnames:                  <computed>
      enable_dns_support:                    "true"
      instance_tenancy:                      <computed>
      ipv6_association_id:                   <computed>
      ipv6_cidr_block:                       <computed>
      main_route_table_id:                   <computed>

Plan: 6 to add, 0 to change, 0 to destroy.

I've read the docs but couldn't found any clue

Body:
Looks like you lack EIP-to-instance association as described in https://www.terraform.io/docs/providers/aws/r/eip_association.html

resource "aws_eip_association" "eip_assoc" {
  instance_id   = "${aws_instance.proxy.id}"
  allocation_id = "${aws_eip.pib.id}"
}

Ok, that wasn't it... Public routing then another possibility that I see is missing (In other words, route everything in that subnet towards IGW):

# Public routing
resource "aws_route_table" "public" {
  vpc_id = "${aws_vpc.main.id}"
}

resource "aws_route" "public_default" {
  route_table_id = "${aws_route_table.public.id}"
  gateway_id     = "${aws_internet_gateway.igw.id}"

  destination_cidr_block = "0.0.0.0/0"
}

resource "aws_route_table_association" "public" {
  subnet_id      = "${aws_subnet.main.id}"
  route_table_id = "${aws_route_table.public.id}"
}

And in your subnet definition you need:

  map_public_ip_on_launch = true

Otherwise it will be a private subnet.


来源: stackexchange

问:
Color regions in a D3 map based on external data
I am trying to make a map in D3 of the 12 provinces of the Netherlands and color them based on some mock data in an external JSON file:

```<code>[{"_id":"Groningen","value":52},
{"_id":"Friesland","value":18},
{"_id":"Drenthe","value":87},
{"_id":"Overijssel","value":93},
{"_id":"Flevoland","value":60},
{"_id":"Gelderland","value":7},
{"_id":"Utrecht","value":26},
{"_id":"Noord-Holland","value":52},
{"_id":"Zuid-Holland","value":72},
{"_id":"Zeeland","value":41},
{"_id":"Noord-Brabant","value":78},
{"_id":"Limburg","value":19}]
</code>```

This is the code I have thus far. It successfully generates them map but right now colors each province as a function of the length of the province name (which is silly ofcourse):

```<code>var width = 960,
height = 500,
centered;

// Define color scale
var color = d3.scaleLinear()
   .domain([1, 20])
   .clamp(true)
   .range(['steelblue', "yellow"]);

var projection = d3.geoMercator()
   .scale(5500)
   .center([6, 52.1])
   .translate([width / 2, height / 2]);

var path = d3.geoPath()
   .projection(projection);

// Set svg width & height
var svg = d3.select('svg')
    .attr('width', width)
    .attr('height', height);

// Add background
svg.append('rect')
   .attr('class', 'background')
   .attr('width', width)
   .attr('height', height)

var g = svg.append('g');

var effectLayer = g.append('g')
   .classed('effect-layer', true);

var mapLayer = g.append('g')
   .classed('map-layer', true);

// Load map data
d3.json('data/provincesNL2.json', function(error, mapData) {
    var features = mapData.features;

    // Draw each province as a path
    mapLayer.selectAll('path')
      .data(features)
      .enter().append('path')
      .attr('d', path)
      .attr('vector-effect', 'non-scaling-stroke')
      .attr('fill', fillFn)
});

// Get province name
function nameFn(d){
   return d && d.properties ? d.properties.PROVINCIE : null;
}

// Get province name length
function nameLength(d){
   var n = nameFn(d);
   return n ? n.length : 0;
}

// Get province color
function fillFn(d){
   return color(nameLength(d));
};
</code>```

I just do not know how to implement the values from the JSON file to represent the color of each province along the color scale. I am not to experienced with javascript and I thought this shouldnt be too hard but I just can not figure it out. Many thanks for any help!

答:
There are a few ways you can do this, one would be to use d3.map. This allows you to look up values in the map with map.get(key).

The general set up looks like:

var lookup = d3.map(array, function(d) { return d.key; })

Where array is your data array, and key is some property of each item in the data array that can be used as an identifier. To lookup a value, you can use:

lookup.get(value)

Where value is an identifying value/key - this will return the entire object that was in the data array. For your data this might look like:

```<code>var lookup = d3.map(data, function(d) { return d._id; });

lookup.get("Drenthe") // {"_id":"Drenthe","value":87}
</code>```

To color the map you can get the identifying value/key from the element's datum. Here's a working example of d3.map used to color your data:

var color = d3.scaleLinear()
  .domain([0,100])
  .range(["orange", "steelblue"])

var data = [{"_id":"Groningen","value":52},
{"_id":"Friesland","value":18},
{"_id":"Drenthe","value":87},
{"_id":"Overijssel","value":93},
{"_id":"Flevoland","value":60},
{"_id":"Gelderland","value":7},
{"_id":"Utrecht","value":26},
{"_id":"Noord-Holland","value":52},
{"_id":"Zuid-Holland","value":72},
{"_id":"Zeeland","value":41},
{"_id":"Noord-Brabant","value":78},
{"_id":"Limburg","value":19}];

var lookup = d3.map(data, function(d) { return d._id; });

// test a value:
console.log(lookup.get("Drenthe").value);

var svg = d3.select("body")
  .append("svg")
  .attr("width",400)
  .attr("height",100);

var squares = svg.selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("fill",function(d) { return color(lookup.get(d._id).value) })
  .attr("x", function(d,i) { return i * 20; })
  .attr("y", 40)
  .attr("width",16)
  .attr("height",16);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a map in D3 of the 12 provinces of the Netherlands and color them based on some mock data in an external JSON file:

[{"_id":"Groningen","value":52},
{"_id":"Friesland","value":18},
{"_id":"Drenthe","value":87},
{"_id":"Overijssel","value":93},
{"_id":"Flevoland","value":60},
{"_id":"Gelderland","value":7},
{"_id":"Utrecht","value":26},
{"_id":"Noord-Holland","value":52},
{"_id":"Zuid-Holland","value":72},
{"_id":"Zeeland","value":41},
{"_id":"Noord-Brabant","value":78},
{"_id":"Limburg","value":19}]

This is the code I have thus far. It successfully generates them map but right now colors each province as a function of the length of the province name (which is silly ofcourse):

var width = 960,
height = 500,
centered;

// Define color scale
var color = d3.scaleLinear()
   .domain([1, 20])
   .clamp(true)
   .range(['steelblue', "yellow"]);

var projection = d3.geoMercator()
   .scale(5500)
   .center([6, 52.1])
   .translate([width / 2, height / 2]);

var path = d3.geoPath()
   .projection(projection);

// Set svg width & height
var svg = d3.select('svg')
    .attr('width', width)
    .attr('height', height);

// Add background
svg.append('rect')
   .attr('class', 'background')
   .attr('width', width)
   .attr('height', height)

var g = svg.append('g');

var effectLayer = g.append('g')
   .classed('effect-layer', true);

var mapLayer = g.append('g')
   .classed('map-layer', true);

// Load map data
d3.json('data/provincesNL2.json', function(error, mapData) {
    var features = mapData.features;

    // Draw each province as a path
    mapLayer.selectAll('path')
      .data(features)
      .enter().append('path')
      .attr('d', path)
      .attr('vector-effect', 'non-scaling-stroke')
      .attr('fill', fillFn)
});

// Get province name
function nameFn(d){
   return d && d.properties ? d.properties.PROVINCIE : null;
}

// Get province name length
function nameLength(d){
   var n = nameFn(d);
   return n ? n.length : 0;
}

// Get province color
function fillFn(d){
   return color(nameLength(d));
};

I just do not know how to implement the values from the JSON file to represent the color of each province along the color scale. I am not to experienced with javascript and I thought this shouldnt be too hard but I just can not figure it out. Many thanks for any help!

Body:
There are a few ways you can do this, one would be to use d3.map. This allows you to look up values in the map with map.get(key).

The general set up looks like:

var lookup = d3.map(array, function(d) { return d.key; })

Where array is your data array, and key is some property of each item in the data array that can be used as an identifier. To lookup a value, you can use:

lookup.get(value)

Where value is an identifying value/key - this will return the entire object that was in the data array. For your data this might look like:

var lookup = d3.map(data, function(d) { return d._id; });

lookup.get("Drenthe") // {"_id":"Drenthe","value":87}

To color the map you can get the identifying value/key from the element's datum. Here's a working example of d3.map used to color your data:

var color = d3.scaleLinear()
  .domain([0,100])
  .range(["orange", "steelblue"])

var data = [{"_id":"Groningen","value":52},
{"_id":"Friesland","value":18},
{"_id":"Drenthe","value":87},
{"_id":"Overijssel","value":93},
{"_id":"Flevoland","value":60},
{"_id":"Gelderland","value":7},
{"_id":"Utrecht","value":26},
{"_id":"Noord-Holland","value":52},
{"_id":"Zuid-Holland","value":72},
{"_id":"Zeeland","value":41},
{"_id":"Noord-Brabant","value":78},
{"_id":"Limburg","value":19}];

var lookup = d3.map(data, function(d) { return d._id; });

// test a value:
console.log(lookup.get("Drenthe").value);

var svg = d3.select("body")
  .append("svg")
  .attr("width",400)
  .attr("height",100);

var squares = svg.selectAll("rect")
  .data(data)
  .enter()
  .append("rect")
  .attr("fill",function(d) { return color(lookup.get(d._id).value) })
  .attr("x", function(d,i) { return i * 20; })
  .attr("y", 40)
  .attr("width",16)
  .attr("height",16);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>


问:
Case insensitive search in arrays for CosmosDB / DocumentDB
Lets say I have these documents in my CosmosDB. (DocumentDB API, .NET SDK)

```<code>{
    // partition key of the collection
    "userId" : "0000-0000-0000-0000",
    "emailAddresses": [
        "someaddress@somedomain.com", "Another.Address@someotherdomain.com"
    ]
    // some more fields
}
</code>```

I now need to find out if I have a document for a given email address. However, I need the query to be case insensitive.

There are ways to search case insensitive on a field (they do a full scan however):

How to do a Case Insensitive search on Azure DocumentDb?

```<code>select * from json j where LOWER(j.name) = 'timbaktu'
e => e.Id.ToLower() == key.ToLower()
</code>```

These do not work for arrays. Is there an alternative way? A user defined function looks like it could help.

I am mainly looking for a temporary low-effort solution to support the scenario (I have multiple collections like this). I probably need to switch to a data structure like this at some point:

```<code>{
    "userId" : "0000-0000-0000-0000",
    // Option A
    "emailAddresses": [
        {
            "displayName": "someaddress@somedomain.com",
            "normalizedName" : "someaddress@somedomain.com"
        },
        {
            "displayName": "Another.Address@someotherdomain.com",
            "normalizedName" : "another.address@someotherdomain.com"
        }
    ],
    // Option B
    "emailAddressesNormalized": {
        "someaddress@somedomain.com", "another.address@someotherdomain.com"
    }
}
</code>```

Unfortunately, my production database already contains documents that would need to be updated to support the new structure.
My production collections contain only 100s of these items, so I am even tempted to just get all items and do the comparison in memory on the client.

答:
If performance matters then you should consider one of the normalization solution you have proposed yourself in question. Then you could index the normalized field and get results without doing a full scan.

If for some reason you really don't want to retouch the documents then perhaps the feature you are missing is simple join?

Example query which will do case-insensitive search from within array with a scan:

```<code>SELECT c FROM c
join email in c.emailAddresses
where lower(email) = lower('ANOTHER.ADDRESS@someotherdomain.com')
</code>```

You can find more examples about joining from Getting started with SQL commands in Cosmos DB.

Note that where-criteria in given example cannot use an index, so consider using it only along another more selective (indexed) criteria.

Body:
Lets say I have these documents in my CosmosDB. (DocumentDB API, .NET SDK)

{
    // partition key of the collection
    "userId" : "0000-0000-0000-0000",
    "emailAddresses": [
        "someaddress@somedomain.com", "Another.Address@someotherdomain.com"
    ]
    // some more fields
}

I now need to find out if I have a document for a given email address. However, I need the query to be case insensitive.

There are ways to search case insensitive on a field (they do a full scan however):

How to do a Case Insensitive search on Azure DocumentDb?

select * from json j where LOWER(j.name) = 'timbaktu'
e => e.Id.ToLower() == key.ToLower()

These do not work for arrays. Is there an alternative way? A user defined function looks like it could help.

I am mainly looking for a temporary low-effort solution to support the scenario (I have multiple collections like this). I probably need to switch to a data structure like this at some point:

{
    "userId" : "0000-0000-0000-0000",
    // Option A
    "emailAddresses": [
        {
            "displayName": "someaddress@somedomain.com",
            "normalizedName" : "someaddress@somedomain.com"
        },
        {
            "displayName": "Another.Address@someotherdomain.com",
            "normalizedName" : "another.address@someotherdomain.com"
        }
    ],
    // Option B
    "emailAddressesNormalized": {
        "someaddress@somedomain.com", "another.address@someotherdomain.com"
    }
}

Unfortunately, my production database already contains documents that would need to be updated to support the new structure.
My production collections contain only 100s of these items, so I am even tempted to just get all items and do the comparison in memory on the client.

Body:
If performance matters then you should consider one of the normalization solution you have proposed yourself in question. Then you could index the normalized field and get results without doing a full scan.

If for some reason you really don't want to retouch the documents then perhaps the feature you are missing is simple join?

Example query which will do case-insensitive search from within array with a scan:

SELECT c FROM c
join email in c.emailAddresses
where lower(email) = lower('ANOTHER.ADDRESS@someotherdomain.com')

You can find more examples about joining from Getting started with SQL commands in Cosmos DB.

Note that where-criteria in given example cannot use an index, so consider using it only along another more selective (indexed) criteria.


问:
Automated Cropping of images using Python
I'm trying to write a script to assist with my Industry Porject but I'm having trouble getting this code working. What it should do is take all Images in a directory Crop them, the crop being the same for every image, then export the cropped image.</p>

```<code>import sys
import os
from PIL import Image

filepath = "C:\Users\Ellis\Desktop\bunny_test"
os.listdir = filepath

# Loop through all provided arguments
for i in range(1, len(filepath)):
try:
    # Attempt to open an image file
    #filepath = sys.argv[i]
    image = Image.open(filepath)
except IOError, e:
    # Report error, and then skip to the next argument
    print "Problem opening", filepath, ":", e
    continue

# Perform operations on the image here
image = image.crop(261, 435, 153, 343)

# Split our origional filename into name and extension
(name, extension) = os.path.splittext(filepath)

# Save the image as "(origional_name)_thumb.jpg
image.save("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg')
</code>```

答:
There were quite some errors in your source code.

wrong indentation (though I think that happened when you copy-pasted your code, since the program above would not even pass the parse step)

missing loop over filenames, do this with os.listdir()

image.crop takes one tuple, instead you provided 4 arguments

join path and filename with os.path.join (image.save does not take two arguments)

it's splitext, not splittext

Here is something which should work:

```<code>import sys
import os
from PIL import Image

filepath = "C:\Users\Ellis\Desktop\bunny_test"

# Loop through all provided arguments
for filename in os.listdir(filepath):
    if "." not in filename:
        continue
    ending = filename.split(".")[1]
    if ending not in ["jpg", "gif", "png"]:
        continue

    try:
        # Attempt to open an image file
        image = Image.open(os.path.join(filepath, filename))
    except IOError, e:
        # Report error, and then skip to the next argument
        print "Problem opening", filepath, ":", e
        continue

    # Perform operations on the image here
    image = image.crop((261, 435, 153, 343))

    # Split our origional filename into name and extension
    name, extension = os.path.splitext(filename)

    # Save the image as "(origional_name)_thumb.jpg
    print(name + '_cropped.jpg')
    image.save(os.path.join("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg'))
</code>```

Body:
I'm trying to write a script to assist with my Industry Porject but I'm having trouble getting this code working. What it should do is take all Images in a directory Crop them, the crop being the same for every image, then export the cropped image.

import sys
import os
from PIL import Image

filepath = "C:\Users\Ellis\Desktop\bunny_test"
os.listdir = filepath

# Loop through all provided arguments
for i in range(1, len(filepath)):
try:
    # Attempt to open an image file
    #filepath = sys.argv[i]
    image = Image.open(filepath)
except IOError, e:
    # Report error, and then skip to the next argument
    print "Problem opening", filepath, ":", e
    continue

# Perform operations on the image here
image = image.crop(261, 435, 153, 343)

# Split our origional filename into name and extension
(name, extension) = os.path.splittext(filepath)

# Save the image as "(origional_name)_thumb.jpg
image.save("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg')

Body:
There were quite some errors in your source code.

wrong indentation (though I think that happened when you copy-pasted your code, since the program above would not even pass the parse step)

missing loop over filenames, do this with os.listdir()

image.crop takes one tuple, instead you provided 4 arguments

join path and filename with os.path.join (image.save does not take two arguments)

it's splitext, not splittext

Here is something which should work:

import sys
import os
from PIL import Image

filepath = "C:\Users\Ellis\Desktop\bunny_test"

# Loop through all provided arguments
for filename in os.listdir(filepath):
    if "." not in filename:
        continue
    ending = filename.split(".")[1]
    if ending not in ["jpg", "gif", "png"]:
        continue

    try:
        # Attempt to open an image file
        image = Image.open(os.path.join(filepath, filename))
    except IOError, e:
        # Report error, and then skip to the next argument
        print "Problem opening", filepath, ":", e
        continue

    # Perform operations on the image here
    image = image.crop((261, 435, 153, 343))

    # Split our origional filename into name and extension
    name, extension = os.path.splitext(filename)

    # Save the image as "(origional_name)_thumb.jpg
    print(name + '_cropped.jpg')
    image.save(os.path.join("C:\Users\Ellis\Desktop\cropped", name + '_cropped.jpg'))


问:
Mask domain email address using regular expression
my client wants to mask the emails in a message, following this way:

Original email:

1 userone@domain.com

2 usertwo@domain.com.co --- > can be anything like gov.co, .com.mx.. etc

masked email:

1 u*****e@d****n.com

2 u*****o@d****n.com.co

For First case, I have this

```<code>string pattern = @"(?<=[\w]{1})[\w-\._\+%]*(?=[\w]{1}@)"; // ---> mask before "@"
string p2 = @"(?<=[\w]{1})[\w-\+%]*(?=[\w]{1}[.])"; // --- > mask after "@"
string result = Regex.Replace(mail, pattern, m => new string('*', m.Length));
string newresult = Regex.Replace(result, p2, m => new string('*', m.Length));
Console.WriteLine("Masked email: {0}", newresult);
</code>```

and works fine:

but... doesn't work for the second case...

so, what is the regular expression that applies to both cases for mask after "@" ?

答:
Original Answer

See the edit at the bottom of my answer for the second method by which this can be accomplished in .net (much shorter).

Code

See regex in use here

```<code>(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?
</code>```

Replacement: $1*$2

Usage

See code in use here

```<code>using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?";
        string substitution = @"$1*$2";
        string input = @"userone@domain.com
usertwo@domain.com.co";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        Console.WriteLine(regex.Replace(input, substitution));
    }
}
</code>```

Results

Input

```<code>userone@domain.com
usertwo@domain.com.co
</code>```

Output

```<code>u*****e@d****n.com
u*****o@d****n.com.co
</code>```

Explanation

(?:(?:^|(?<=@))([^.@])|\G(?!\A)) Match either of the following

(?:^|(?<=@))([^.@]) Match the following

(?:^|(?<=@)) Match either of the following

^ Assert position at the start of the line

(?<=@) Positive lookbehind ensuring what precedes is the at sign character @ literally

([^.@]) Capture any character not present in the list (any character except the dot . or at sign @ characters literally) into capture group 1

\G(?!\A) Assert position at the end of the previous match

[^.@] Match any character not present in the list (any character except the dot . or at sign @ characters literally)

(?:([^.@])(?=[.@]))? Match the following zero or once

([^.@]) Capture any character not present in the list (any character except the dot . or at sign @ characters literally) into capture group 2

(?=[.@]) Positive lookahead ensuring what follows is a dot . or at sign @ character literally

Edit

This pattern obtains the same results as my original answer (unless a string of length 2 is given: i.e. un@domain.com is left alone while the original answer will make this u*@domain.com).

C# (.net) supports variable length lookbehinds. Credit to @Gurman with his comment. He was on the right track, just probably wasn't aware that .net supports variable length lookbehinds.

Code

See regex in use here

```<code>(?<=(?:^|@)[^.]*)\B.\B
</code>```

Explanation

(?<=(?:^|@)[^.]*) Positive lookbehind ensuring what follows matches

(?:^|@) Match either a start of the line assertion or a literal at sign @

[^.]* Match any character except the dot character . literally

\B Match a position where a word boundary doesn't match

. Match any character

\B Match a position where a word boundary doesn't match

Edit 2

Regex for emails containing . in localpart (see in use here):

```<code>(?<=^[^@]+)[^@](?=[^@])|(?<=@[^.]+)[^.](?=[^.])
</code>```

Body:
my client wants to mask the emails in a message, following this way:

Original email:

1 userone@domain.com

2 usertwo@domain.com.co --- > can be anything like gov.co, .com.mx.. etc

masked email:

1 u*****e@d****n.com

2 u*****o@d****n.com.co

For First case, I have this

string pattern = @"(?<=[\w]{1})[\w-\._\+%]*(?=[\w]{1}@)"; // ---> mask before "@"
string p2 = @"(?<=[\w]{1})[\w-\+%]*(?=[\w]{1}[.])"; // --- > mask after "@"
string result = Regex.Replace(mail, pattern, m => new string('*', m.Length));
string newresult = Regex.Replace(result, p2, m => new string('*', m.Length));
Console.WriteLine("Masked email: {0}", newresult);

and works fine:

but... doesn't work for the second case...

so, what is the regular expression that applies to both cases for mask after "@" ?

Body:
Original Answer

See the edit at the bottom of my answer for the second method by which this can be accomplished in .net (much shorter).

Code

See regex in use here

(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?

Replacement: $1*$2

Usage

See code in use here

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(?:(?:^|(?<=@))([^.@])|\G(?!\A))[^.@](?:([^.@])(?=[.@]))?";
        string substitution = @"$1*$2";
        string input = @"userone@domain.com
usertwo@domain.com.co";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        Console.WriteLine(regex.Replace(input, substitution));
    }
}

Results

Input

userone@domain.com
usertwo@domain.com.co

Output

u*****e@d****n.com
u*****o@d****n.com.co

Explanation

(?:(?:^|(?<=@))([^.@])|\G(?!\A)) Match either of the following

(?:^|(?<=@))([^.@]) Match the following

(?:^|(?<=@)) Match either of the following

^ Assert position at the start of the line

(?<=@) Positive lookbehind ensuring what precedes is the at sign character @ literally

([^.@]) Capture any character not present in the list (any character except the dot . or at sign @ characters literally) into capture group 1

\G(?!\A) Assert position at the end of the previous match

[^.@] Match any character not present in the list (any character except the dot . or at sign @ characters literally)

(?:([^.@])(?=[.@]))? Match the following zero or once

([^.@]) Capture any character not present in the list (any character except the dot . or at sign @ characters literally) into capture group 2

(?=[.@]) Positive lookahead ensuring what follows is a dot . or at sign @ character literally

Edit

This pattern obtains the same results as my original answer (unless a string of length 2 is given: i.e. un@domain.com is left alone while the original answer will make this u*@domain.com).

C# (.net) supports variable length lookbehinds. Credit to @Gurman with his comment. He was on the right track, just probably wasn't aware that .net supports variable length lookbehinds.

Code

See regex in use here

(?<=(?:^|@)[^.]*)\B.\B

Explanation

(?<=(?:^|@)[^.]*) Positive lookbehind ensuring what follows matches

(?:^|@) Match either a start of the line assertion or a literal at sign @

[^.]* Match any character except the dot character . literally

\B Match a position where a word boundary doesn't match

. Match any character

\B Match a position where a word boundary doesn't match

Edit 2

Regex for emails containing . in localpart (see in use here):

(?<=^[^@]+)[^@](?=[^@])|(?<=@[^.]+)[^.](?=[^.])

ContentLicense: CC BY-SA 4.0


问:
R Joining with data.table

I'm trying to join two data frames (data.tables), x and y, on x$val >= y$start & x$val <= y$end. I can't use dplyr because the only way to do inequality joins in dplyr is to join the tables then filter on the inequality, and the tables I want to join have 315k and 84k records. That would blow out memory.

data.table does have inequality joins, but I cannot for the life of me figure out how the syntax works. See this result:

```<code>x <- data.table(val = c(1:5), id = "a")
y <- data.table(start = c(1:5), end = c(11:15), id= "a")

x[y, on=c("val>=start","val<=end"),
  .(start, val, end)]

    start val end
 1:     1   1  11
 2:     1   1  11
 3:     1   1  11
 4:     1   1  11
 5:     1   1  11
 6:     2   2  12
 7:     2   2  12
 8:     2   2  12
 9:     2   2  12
10:     3   3  13
11:     3   3  13
12:     3   3  13
13:     4   4  14
14:     4   4  14
15:     5   5  15
</code>```

To show what I would expect to get, here is what dplyr produces:

```<code>x <- data.table(val = c(1:5), id = "a")
y <- data.table(start = c(1:5), end = c(11:15), id= "a")

x %>%
  inner_join(y) %>%
  filter(val >= start & val <= end)

   val   id start end
1    1    a     1  11
2    2    a     1  11
3    2    a     2  12
4    3    a     1  11
5    3    a     2  12
6    3    a     3  13
7    4    a     1  11
8    4    a     2  12
9    4    a     3  13
10   4    a     4  14
11   5    a     1  11
12   5    a     2  12
13   5    a     3  13
14   5    a     4  14
15   5    a     5  15
</code>```

Can anyone explain what it is I'm missing with the data.table syntax?

答:
You need to select val column from the left table with prefix (x.); For more information, see this answer:

```<code>x[y, on=.(val >= start, val <= end), .(val = x.val, id, start, end)][order(val)]
 #                                           ^^
 #   val id start end
 #1:   1  a     1  11
 #2:   2  a     1  11
 #3:   2  a     2  12
 #4:   3  a     1  11
 #5:   3  a     2  12
 #6:   3  a     3  13
 #7:   4  a     1  11
 #8:   4  a     2  12
 #9:   4  a     3  13
#10:   4  a     4  14
#11:   5  a     1  11
#12:   5  a     2  12
#13:   5  a     3  13
#14:   5  a     4  14
#15:   5  a     5  15
</code>```

Title: R Joining with data.table

Body:
I'm trying to join two data frames (data.tables), x and y, on x$val >= y$start & x$val <= y$end. I can't use dplyr because the only way to do inequality joins in dplyr is to join the tables then filter on the inequality, and the tables I want to join have 315k and 84k records. That would blow out memory.

data.table does have inequality joins, but I cannot for the life of me figure out how the syntax works. See this result:

x <- data.table(val = c(1:5), id = "a")
y <- data.table(start = c(1:5), end = c(11:15), id= "a")

x[y, on=c("val>=start","val<=end"),
  .(start, val, end)]

    start val end
 1:     1   1  11
 2:     1   1  11
 3:     1   1  11
 4:     1   1  11
 5:     1   1  11
 6:     2   2  12
 7:     2   2  12
 8:     2   2  12
 9:     2   2  12
10:     3   3  13
11:     3   3  13
12:     3   3  13
13:     4   4  14
14:     4   4  14
15:     5   5  15

To show what I would expect to get, here is what dplyr produces:

x <- data.table(val = c(1:5), id = "a")
y <- data.table(start = c(1:5), end = c(11:15), id= "a")

x %>%
  inner_join(y) %>%
  filter(val >= start & val <= end)

   val   id start end
1    1    a     1  11
2    2    a     1  11
3    2    a     2  12
4    3    a     1  11
5    3    a     2  12
6    3    a     3  13
7    4    a     1  11
8    4    a     2  12
9    4    a     3  13
10   4    a     4  14
11   5    a     1  11
12   5    a     2  12
13   5    a     3  13
14   5    a     4  14
15   5    a     5  15

Can anyone explain what it is I'm missing with the data.table syntax?

Body:
You need to select val column from the left table with prefix (x.); For more information, see this answer:

x[y, on=.(val >= start, val <= end), .(val = x.val, id, start, end)][order(val)]
 #                                           ^^
 #   val id start end
 #1:   1  a     1  11
 #2:   2  a     1  11
 #3:   2  a     2  12
 #4:   3  a     1  11
 #5:   3  a     2  12
 #6:   3  a     3  13
 #7:   4  a     1  11
 #8:   4  a     2  12
 #9:   4  a     3  13
#10:   4  a     4  14
#11:   5  a     1  11
#12:   5  a     2  12
#13:   5  a     3  13
#14:   5  a     4  14
#15:   5  a     5  15


问:
Python picture grid in loop
I encountered a problem as I tried to fill a tkinter grid with a loop

```<code>i=0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    imageLabel.grid(row=0, column=i)
    i = i + 1
</code>```

With this code I try to create a row with different pictures side by side.
But it shows only the last image which is in the categories array (this array was filled by a SQL-execute btw).

After a few researches I found out, that it seems that python overwrites the reference of the picture on each iteration.

So I tried to change the code and save the references in a array:

```<code>folderPictures = []
i = 0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    folderPictures.append(imageLabel)

for pictures in folderPictures:
        pictures.grid(row=0, column=i)
        i = +1
</code>```

unfortunately this doesn't work either. What do I do wrong?

Thanks and best regards
Franz

答:
Load images first and make a list of them, then put in label.</p>

```<code>images=[]
for category in categories:
    images.append(PhotoImage(file=category[2]+".png"))
for index,img in enumerate(images):
    Label(master,image=img).grid(row=0,column=index)
</code>```

Title: Python picture grid in loop

Body:
I encountered a problem as I tried to fill a tkinter grid with a loop

i=0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    imageLabel.grid(row=0, column=i)
    i = i + 1

With this code I try to create a row with different pictures side by side.
But it shows only the last image which is in the categories array (this array was filled by a SQL-execute btw).

After a few researches I found out, that it seems that python overwrites the reference of the picture on each iteration.

So I tried to change the code and save the references in a array:

folderPictures = []
i = 0
for category in categories:
    self.image = PhotoImage(file=category[2]+".png")
    imageLabel = Label(master, image=self.image)
    folderPictures.append(imageLabel)

for pictures in folderPictures:
        pictures.grid(row=0, column=i)
        i = +1

unfortunately this doesn't work either. What do I do wrong?

Thanks and best regards
Franz

Body:
Load images first and make a list of them, then put in label.

images=[]
for category in categories:
    images.append(PhotoImage(file=category[2]+".png"))
for index,img in enumerate(images):
    Label(master,image=img).grid(row=0,column=index)


问:
Add rollapply vector to a data frame
I have the following data:

```<code>Year Month Total
2015 1     123
2015 2     435
2015 3     543
</code>```

which are total by month over a three year period. I used rollapply to calculate a rolling cumulative total. Like below:

```<code>rollapply(results$Total, 12, sum)
</code>```

however this returns a vector which (obviously) has 11 fewer observations and no index value.

How do I join it back to the dataframe as a column indexed correctly?

答:
You can add the vector to your main dataframe as a new column:

```<code>results$rolling <- rollapply(results$Total, width = 3, sum , fill = NA)
</code>```

then you should get the results as:

```<code>Year Month Total rolling
2015 1     123   na
2015 2     435   na
2015 3     543   1101
</code>```

I changed the window size to 3 just for illustration in this example!

Title: Add rollapply vector to a data frame

Body:
I have the following data:

Year Month Total
2015 1     123
2015 2     435
2015 3     543

which are total by month over a three year period. I used rollapply to calculate a rolling cumulative total. Like below:

rollapply(results$Total, 12, sum)

however this returns a vector which (obviously) has 11 fewer observations and no index value.

How do I join it back to the dataframe as a column indexed correctly?

Body:
You can add the vector to your main dataframe as a new column:

results$rolling <- rollapply(results$Total, width = 3, sum , fill = NA)

then you should get the results as:

Year Month Total rolling
2015 1     123   na
2015 2     435   na
2015 3     543   1101

I changed the window size to 3 just for illustration in this example!


问:
Bash Store Curl Results into Array
I am running the following curl command:

```<code>results=$(curl -USERNAME:PASSWORD "URL/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca")
echo "$results"
</code>```

I am getting this in return:

```<code>"results" : [ {
    "uri" : "URL/api/storage/generic-sgca/Lastest_Deploy.tar",
    "created" : "2017-09-14T11:59:14.483-06:00"
  }, {
    "uri" : "URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run",
    "created" : "2017-09-14T20:11:37.733-06:00"
  }
</code>```

It doesn't seem to actually be storing the curl results as an array. I want to be able to store each "uri" as a variable and use an "-X DELETE" command to remove each file. How can I get the "uri" line on it's own, remove the "created" option.

EDIT:

I've used the following command:

```<code>results=$(curl -username:password "URL/api/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca" | jq -r '.results[].uri')
echo "$results"
</code>```

I got this in return:

```<code>URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-windows-installer.exe
</code>```

Now I want to run a curl -X DELETE command to delete each of those urls from my Artifactory page. The command would be:

```<code>curl username:password -X DELETE "URL FROM ABOVE"
</code>```

But I can't figure out how to store each line as a separate variable so I can delete each one.

答:
Use jq to extract the URLs.

```<code>$ curl ... | jq -r '.results[].uri'
URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
</code>```

Then use your favorite correct technique for iterating over the output of a command line-by-line; see Bash FAQ 001 for details.

(I'm assuming a URL will not contain a newline; if that's the case, switch to a different language that can handle arbitrary data more easily.)

Title: Bash Store Curl Results into Array

Body:
I am running the following curl command:

results=$(curl -USERNAME:PASSWORD "URL/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca")
echo "$results"

I am getting this in return:

"results" : [ {
    "uri" : "URL/api/storage/generic-sgca/Lastest_Deploy.tar",
    "created" : "2017-09-14T11:59:14.483-06:00"
  }, {
    "uri" : "URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run",
    "created" : "2017-09-14T20:11:37.733-06:00"
  }

It doesn't seem to actually be storing the curl results as an array. I want to be able to store each "uri" as a variable and use an "-X DELETE" command to remove each file. How can I get the "uri" line on it's own, remove the "created" option.

EDIT:

I've used the following command:

results=$(curl -username:password "URL/api/search/dates?dateFields=created&from=${Three_Months_Ago}&today&repos=generic-sgca" | jq -r '.results[].uri')
echo "$results"

I got this in return:

URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.0.99/SignalStudioPro-Alpha-1-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-0.2.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-100.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-101.0.0/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.9/SignalStudioPro-Alpha-2-windows-installer.exe
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-linux-x64-installer.run
URL/api/storage/generic-sgca/Installer-Deploy-99.9.91/SignalStudioPro-Alpha-2-windows-installer.exe

Now I want to run a curl -X DELETE command to delete each of those urls from my Artifactory page. The command would be:

curl username:password -X DELETE "URL FROM ABOVE"

But I can't figure out how to store each line as a separate variable so I can delete each one.

Body:
Use jq to extract the URLs.

$ curl ... | jq -r '.results[].uri'
URL/api/storage/generic-sgca/Lastest_Deploy.tar
URL/api/storage/generic-sgca/Installer-Deploy-0.0.5/SignalStudioPro-Alpha-1-linux-x64-installer.run

Then use your favorite correct technique for iterating over the output of a command line-by-line; see Bash FAQ 001 for details.

(I'm assuming a URL will not contain a newline; if that's the case, switch to a different language that can handle arbitrary data more easily.)


问:
Firefox 57 favicon is not recognized
Since the version 57 of Firefox (Quantum) it appears that none of the favicons I include on my site is being recognised. This are all the formats I have included:

```<code><link rel="icon" type="image/x-icon" href="/icons/my-favicon.ico">
<link rel="shortcut icon" type="image/x-icon" href="/icons/my-favicon.ico">
<link rel="icon" type="image/png" href="/icons/my-favicon-16x16.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-24x24.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-32x32.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-48x48.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-64x64.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="57x57" href="/icons/my-apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="60x60" href="/icons/my-apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="72x72" href="/icons/my-apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="76x76" href="/icons/my-apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="114x114" href="/icons/my-apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="120x120" href="/icons/my-apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="144x144" href="/icons/my-apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="152x152" href="/icons/my-apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="180x180" href="/icons/my-apple-touch-icon-180x180.png">
</code>```

All the paths are valid and it seem to work in any other major browser. Does the new version of Firefox require some specific type for the favicon? Even if they introduced something new it is strange that it's not falling back to any of the common formats...

答: This happened to me after updating to 57 as well.  I have no idea what the problem was, but clearing the cache and restarting Firefox fixed it.</p>

Title: Firefox 57 favicon is not recognized

Body:
Since the version 57 of Firefox (Quantum) it appears that none of the favicons I include on my site is being recognised. This are all the formats I have included:

<link rel="icon" type="image/x-icon" href="/icons/my-favicon.ico">
<link rel="shortcut icon" type="image/x-icon" href="/icons/my-favicon.ico">
<link rel="icon" type="image/png" href="/icons/my-favicon-16x16.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-24x24.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-32x32.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-48x48.png">
<link rel="icon" type="image/png" href="/icons/my-favicon-64x64.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="57x57" href="/icons/my-apple-touch-icon-57x57.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="60x60" href="/icons/my-apple-touch-icon-60x60.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="72x72" href="/icons/my-apple-touch-icon-72x72.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="76x76" href="/icons/my-apple-touch-icon-76x76.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="114x114" href="/icons/my-apple-touch-icon-114x114.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="120x120" href="/icons/my-apple-touch-icon-120x120.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="144x144" href="/icons/my-apple-touch-icon-144x144.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="152x152" href="/icons/my-apple-touch-icon-152x152.png">
<link rel="apple-touch-icon" type="image/x-icon" sizes="180x180" href="/icons/my-apple-touch-icon-180x180.png">

All the paths are valid and it seem to work in any other major browser. Does the new version of Firefox require some specific type for the favicon? Even if they introduced something new it is strange that it's not falling back to any of the common formats...


问:
MySQL insert query where a value does not match
I would like to insert some data into mySQL like this:

```<code>INSERT INTO user_data (user_id,value) VALUES (1,2)
</code>```

Is there a way to make sure the same value for the user doesn't exist? I want it to only insert the data if value for user_id does not already exist?

So basically a user_id can have multiple values. I know this can be done unique field. But I am looking to do this with a SQL query

答:
You could use NOT EXISTS in combination with the INSERT statement.

```<code>INSERT INTO user_data (`user_id`, `value`)
SELECT DISTINCT 1,2
FROM `user_data`
WHERE NOT EXISTS (
    SELECT * FROM `user_data`
    WHERE `user_id` = 1 AND `value` = 2
);
</code>```

This makes sure it only inserts when it does not already exist.

Body:
I would like to insert some data into mySQL like this:

INSERT INTO user_data (user_id,value) VALUES (1,2)

Is there a way to make sure the same value for the user doesn't exist? I want it to only insert the data if value for user_id does not already exist?

So basically a user_id can have multiple values. I know this can be done unique field. But I am looking to do this with a SQL query

Body:
You could use NOT EXISTS in combination with the INSERT statement.

INSERT INTO user_data (`user_id`, `value`)
SELECT DISTINCT 1,2
FROM `user_data`
WHERE NOT EXISTS (
    SELECT * FROM `user_data`
    WHERE `user_id` = 1 AND `value` = 2
);

This makes sure it only inserts when it does not already exist.


问:
NPOI protect sheet XSSF excel workbook
I have to protect only one row (example the rowNum 0) in a xssf Excel generated in this way (using library NPOI version 2.2.1.0)

```<code>ISheet sheet_for_dropdown_list = Workbook.CreateSheet("DropDownList");
</code>```

Actually the protect command is used only to protect entirely sheet by means of a password

```<code>sheet_for_dropdown_list.ProtectSheet("admin");
</code>```

Then I tryed to unlock the row1 setting the property
isLocked false in a style

```<code>ICellStyle extCellStyle = Workbook.CreateCellStyle();

unprotectCellStyle.IsLocked = false

IRow1 row1= sheet_for_dropdown_list.GetRow(1);
</code>```

and unprotect all cell

```<code>foreach (ICell cell in row1)
        cell.CellStyle = unprotectCellStyle;
</code>```

This operation could be done for all the row > 0

This solution partially works, because is possible to modify the cell contents but isn't possible to modify the height of the column. So in the free cell isn't possible to insert contents with height greater than the actual height column.

答:
I think you are looking to set the height of header row. You can either assign the height or wrap the text or both.

To assign the height see this link. To Wrap a text use below syntax

```<code>XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerStyle.WrapText = true;
</code>```

Title: NPOI protect sheet XSSF excel workbook

Body:
I have to protect only one row (example the rowNum 0) in a xssf Excel generated in this way (using library NPOI version 2.2.1.0)

ISheet sheet_for_dropdown_list = Workbook.CreateSheet("DropDownList");

Actually the protect command is used only to protect entirely sheet by means of a password

sheet_for_dropdown_list.ProtectSheet("admin");

Then I tryed to unlock the row1 setting the property
isLocked false in a style

ICellStyle extCellStyle = Workbook.CreateCellStyle();

unprotectCellStyle.IsLocked = false

IRow1 row1= sheet_for_dropdown_list.GetRow(1);

and unprotect all cell

foreach (ICell cell in row1)
        cell.CellStyle = unprotectCellStyle;

This operation could be done for all the row > 0

This solution partially works, because is possible to modify the cell contents but isn't possible to modify the height of the column. So in the free cell isn't possible to insert contents with height greater than the actual height column.

Body:
I think you are looking to set the height of header row. You can either assign the height or wrap the text or both.

To assign the height see this link. To Wrap a text use below syntax

XSSFCellStyle headerStyle = (XSSFCellStyle)workbook.CreateCellStyle();
headerStyle.WrapText = true;


问:
Function only returning first letter capitalised
I have a function that is meant to do this:

```<code>accum("abcd");    // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"
</code>```

We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]

It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below.
The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]

It is returning the first substring of each string but it isn't returning the rest of them.

```<code>function accum(s) {
    var splitstring = s.split("")
    var newarray = []
    for(var i = 0; i < splitstring.length; i++) {
        newarray.push(splitstring[i].repeat(i + 1))
    }
    for (var i = 0; i < newarray.length; i++) {
        newarray[i]  = newarray[i].charAt(0).toUpperCase()
    }
    return newarray
}
accum("abcd")
</code>```

答:
No need to use second for loop. Just use map() on the returned array.

function accum(s) {
  var splitstring = s.split("");
  var newarray = [];
  for(var i= 0; i < splitstring.length; i++) {
    newarray.push(splitstring[i].repeat(i + 1))
  }
  return newarray.map(j=>j[0].toUpperCase()+ j.slice(1)).join('-');
}

console.log(accum("abcd"));```

Body:
I have a function that is meant to do this:

accum("abcd");    // "A-Bb-Ccc-Dddd"
accum("RqaEzty"); // "R-Qq-Aaa-Eeee-Zzzzz-Tttttt-Yyyyyyy"

We can see the first "for" loop repeats each substring by it's current (index + 1). It pushes it to the array and the output would be [ 'a', 'bb', 'ccc', 'dddd' ]

It is then obvious that I need to iterate over this array and capitalise each string which I have done by the second for loop below.
The problem is when I return the array it is returning like this: [ 'A', 'B', 'C', 'D' ]

It is returning the first substring of each string but it isn't returning the rest of them.

function accum(s) {
    var splitstring = s.split("")
    var newarray = []
    for(var i = 0; i < splitstring.length; i++) {
        newarray.push(splitstring[i].repeat(i + 1))
    }
    for (var i = 0; i < newarray.length; i++) {
        newarray[i]  = newarray[i].charAt(0).toUpperCase()
    }
    return newarray
}
accum("abcd")


问:
Meteor server response slow when importing collection
I have a MongoDB collection Foods in my Meteor app with about 8000 entries with almost 1000 fields each.

For some reason, since I included it, the response time when I call a server method from the client is very slow (seconds). For debugging, I've been removing things one by one. Now, I don't use the collection in any of the functions involved (I've even replaced the server method with just a console.log), and yet if I add the line import { Foods } from '../imports/collections.js'; to the server, the response is slow, and if I don't it is fast.

Does anyone have any idea why this could be?

答:
Note: OP has already answered his question satisfactory. However, the following information should be pointed out, especially for those who face similar issues in context of controlling Meteor's autopublish behavior.

As long as autopublish exists in your packages list, each collection publishes to the client at the very moment, your Mongo.Collection is created.

See this code of the Mongo.Collection constructor.

Autopublish is then triggered, even just by importing your file that contains a Mongo.Collection constructor to be called (which is very likely your case).

However, you dont need to remove the autopublish package if you only want this one collection to prevent auto publishing.

Your Mongo.Collection constructor accepts as second parameter an object with options. To prevent auto publish only for this collection (while having autopublish active) you can add the following option:

{
    _preventAutopublish: true,
    // ... other options if desired
}
```

<p>An example for your given Foods collection could be</p>

<pre class="lang-js prettyprint-override"><code>export const Foods = new Mongo.Collection('foods', {_preventAutopublish: true});
</code>```

Although the option is not documented, it works and comes in very handy when prototyping.

However, keep in mind that autopublish is not secure and should never be present in a release that is expected to be deployed on a server.

Body:
Note: OP has already answered his question satisfactory. However, the following information should be pointed out, especially for those who face similar issues in context of controlling Meteor's autopublish behavior.

As long as autopublish exists in your packages list, each collection publishes to the client at the very moment, your Mongo.Collection is created.

See this code of the Mongo.Collection constructor.

Autopublish is then triggered, even just by importing your file that contains a Mongo.Collection constructor to be called (which is very likely your case).

However, you dont need to remove the autopublish package if you only want this one collection to prevent auto publishing.

Your Mongo.Collection constructor accepts as second parameter an object with options. To prevent auto publish only for this collection (while having autopublish active) you can add the following option:

{
    _preventAutopublish: true,
    // ... other options if desired
}

An example for your given Foods collection could be

export const Foods = new Mongo.Collection('foods', {_preventAutopublish: true});

Although the option is not documented, it works and comes in very handy when prototyping.

However, keep in mind that autopublish is not secure and should never be present in a release that is expected to be deployed on a server.


问:
How can I add files to a solution folder?
I am using the following script answered here to create a solution folder inside a solution using Powershell script.

```<code>Function AddFolderToSolution($folderName, $solutionFile)
{
   $solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
   $content = [System.IO.File]::ReadLines($solutionFile)
   $lines = New-Object System.Collections.Generic.List[string]
   $lines.AddRange($content)
   $index = $lines.IndexOf("Global")
   $guid = [System.Guid]::NewGuid().ToString().ToUpper()
   $txt = "Project(`"$solutionFolderGuid`") = `"$folderName`", `"$folderName`", `"$guid`""
   $lines.Insert($index, $txt)
   $lines.Insert($index+1, "EndProject")
   [System.IO.File]::WriteAllLines($solutionFile, $lines)
}

AddFolderToSolution "NewFolder10" "D:\Solution1.sln"
</code>```

Now I want to copy few files into the solution folder(NewFolder10). How can I do that using PowerShell?

答:
Solution folders are not physical folders, and the files that you want to put to a Solution Folder should exist somewhere and you just should add a reference to those files to your solution file.

Those solution items should be added as child of ProjectSection(SolutionItems) = preProject in solution file, having this format relative path to file = relative path to file.

For example, I suppose you want to add a solution folder named SolutionItems and put file1.txt and file2.txt to that solution folder. Then if those files exists in a physical folder like SomeFolder beside your solution file, then you should add this text to the solution file:

```<code>Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionItems", "SolutionItems", "B73A0302-952E-42D6-925D-ABCB95684477"
    ProjectSection(SolutionItems) = preProject
        ..\SomeFolder\file1.txt = ..\SomeFolder\file1.txt
        ..\SomeFolder\file2.txt = ..\SomeFolder\file2.txt
    EndProjectSection
EndProject
</code>```

Example

Here is a method which copies files from a directory to a folder named SolutionItems folder near your solution. Then adds a Solution Folder named SolutionItems (the same name as physical folder just for being clear) and add those copied files as solution items:

```<code>Function AddFolderToSolution($folderPath, $solutionFile)
{
    $solutionPath = Split-Path -Parent -Path $solutionFile
    $folderName = "SolutionItems"
    $destination = Join-Path $solutionPath $folderName
    $solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
    $content = [System.IO.File]::ReadLines($solutionFile)
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.AddRange($content)
    $index = $lines.IndexOf("Global")
    $guid = [System.Guid]::NewGuid().ToString().ToUpper()
    $range = New-Object System.Collections.Generic.List[string]
    $range.Add(
        "Project(`"$solutionFolderGuid`") = `"$folderName`", `"$folderName`", `"$guid`"")
    $range.Add("`tProjectSection(SolutionItems) = preProject")
    New-Item -Path $destination -ItemType Directory -Force
    Get-ChildItem -Path $folderPath -File | Copy-Item -Destination $destination -Force
    Get-ChildItem -Path $destination -File| ForEach-Object {
        $itemName = Split-Path -Leaf -Path $_.FullName
        $range.Add("`t`t..\$folderName\$itemName = ..\$folderName\$itemName")
    }
    $range.Add("`tEndProjectSection")
    $range.Add("EndProject")
    $lines.InsertRange($index, $range)
    [System.IO.File]::WriteAllLines($solutionFile, $lines)
}
</code>```

And here is the usage:

```<code>AddFolderToSolution "d:\somefolder" "d:\mysolution\Solution1.sln"
</code>```

By running above example, it will copy file from d:\somefolder to a folder named SolutionItems near the solution file. Then adds a Solution Folder with the same name SolutionItems and add those files as Solution Item.

Body:
I am using the following script answered here to create a solution folder inside a solution using Powershell script.

Function AddFolderToSolution($folderName, $solutionFile)
{
   $solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
   $content = [System.IO.File]::ReadLines($solutionFile)
   $lines = New-Object System.Collections.Generic.List[string]
   $lines.AddRange($content)
   $index = $lines.IndexOf("Global")
   $guid = [System.Guid]::NewGuid().ToString().ToUpper()
   $txt = "Project(`"$solutionFolderGuid`") = `"$folderName`", `"$folderName`", `"$guid`""
   $lines.Insert($index, $txt)
   $lines.Insert($index+1, "EndProject")
   [System.IO.File]::WriteAllLines($solutionFile, $lines)
}

AddFolderToSolution "NewFolder10" "D:\Solution1.sln"

Now I want to copy few files into the solution folder(NewFolder10). How can I do that using PowerShell?

Body:
Solution folders are not physical folders, and the files that you want to put to a Solution Folder should exist somewhere and you just should add a reference to those files to your solution file.

Those solution items should be added as child of ProjectSection(SolutionItems) = preProject in solution file, having this format relative path to file = relative path to file.

For example, I suppose you want to add a solution folder named SolutionItems and put file1.txt and file2.txt to that solution folder. Then if those files exists in a physical folder like SomeFolder beside your solution file, then you should add this text to the solution file:

Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SolutionItems", "SolutionItems", "B73A0302-952E-42D6-925D-ABCB95684477"
    ProjectSection(SolutionItems) = preProject
        ..\SomeFolder\file1.txt = ..\SomeFolder\file1.txt
        ..\SomeFolder\file2.txt = ..\SomeFolder\file2.txt
    EndProjectSection
EndProject

Example

Here is a method which copies files from a directory to a folder named SolutionItems folder near your solution. Then adds a Solution Folder named SolutionItems (the same name as physical folder just for being clear) and add those copied files as solution items:

Function AddFolderToSolution($folderPath, $solutionFile)
{
    $solutionPath = Split-Path -Parent -Path $solutionFile
    $folderName = "SolutionItems"
    $destination = Join-Path $solutionPath $folderName
    $solutionFolderGuid = "{2150E333-8FDC-42A3-9474-1A3956D46DE8}"
    $content = [System.IO.File]::ReadLines($solutionFile)
    $lines = New-Object System.Collections.Generic.List[string]
    $lines.AddRange($content)
    $index = $lines.IndexOf("Global")
    $guid = [System.Guid]::NewGuid().ToString().ToUpper()
    $range = New-Object System.Collections.Generic.List[string]
    $range.Add(
        "Project(`"$solutionFolderGuid`") = `"$folderName`", `"$folderName`", `"$guid`"")
    $range.Add("`tProjectSection(SolutionItems) = preProject")
    New-Item -Path $destination -ItemType Directory -Force
    Get-ChildItem -Path $folderPath -File | Copy-Item -Destination $destination -Force
    Get-ChildItem -Path $destination -File| ForEach-Object {
        $itemName = Split-Path -Leaf -Path $_.FullName
        $range.Add("`t`t..\$folderName\$itemName = ..\$folderName\$itemName")
    }
    $range.Add("`tEndProjectSection")
    $range.Add("EndProject")
    $lines.InsertRange($index, $range)
    [System.IO.File]::WriteAllLines($solutionFile, $lines)
}

And here is the usage:

AddFolderToSolution "d:\somefolder" "d:\mysolution\Solution1.sln"

By running above example, it will copy file from d:\somefolder to a folder named SolutionItems near the solution file. Then adds a Solution Folder with the same name SolutionItems and add those files as Solution Item.


问:
Updating table in SSIS script component
I have table in database with these columns

```<code>ID  |  Fact  | Date
</code>```

And in column Fact I have only NULLs. I want to use Script Component to update data in this table. Is there any way to do that?

Note: I can't use SQL statement because of query performance.

答:
A script component will allow you to use C# or VB to do things. You can send database commands with C# or VB, but it's still going to end up being a SQL statement in the end. </p>

<p>If you can't update data in your table due to performance, you need to investigate why the performance is bad and rectify that. </p>

Title: Updating table in SSIS script component

Body:
I have table in database with these columns

ID  |  Fact  | Date

And in column Fact I have only NULLs. I want to use Script Component to update data in this table. Is there any way to do that?

Note: I can't use SQL statement because of query performance.

Body:
A script component will allow you to use C# or VB to do things. You can send database commands with C# or VB, but it's still going to end up being a SQL statement in the end.

If you can't update data in your table due to performance, you need to investigate why the performance is bad and rectify that.


问:
CSS Media Query to target 1080 phones?
I'm looking for the correct CSS media query to target all phones (not tablets and larger) including 1080 phones such as the Sony Xperia Z.

Right now I'm using:

```<code><link href='style/mobile.css' rel='stylesheet' type='text/css' media='screen and (max-device-width: 767px)' />
</code>```

That works for most devices, but in the Android Firefox Browser (not Chrome though strangely) the Xperia Z just gets the desktop site only.

I've tried searching but it seems no one is talking about these new very high-res phones, is there a new standard I should be adhering to?

答:
Use max-width instead of max-device-width to target CSS pixels.

Do not forget viewport meta. Small devices with lots of pixel will still have a low CSS pixel count so it will just work.

Title: CSS Media Query to target 1080 phones?

Body:
I'm looking for the correct CSS media query to target all phones (not tablets and larger) including 1080 phones such as the Sony Xperia Z.

Right now I'm using:

<link href='style/mobile.css' rel='stylesheet' type='text/css' media='screen and (max-device-width: 767px)' />

That works for most devices, but in the Android Firefox Browser (not Chrome though strangely) the Xperia Z just gets the desktop site only.

I've tried searching but it seems no one is talking about these new very high-res phones, is there a new standard I should be adhering to?


问:
Charts library for Ruby
I am looking for a quite specific tool for generating charts, within Ruby on Rails application. I have done a research and couldn't find a solution that suits me.

Maybe you've bumped upon it and could just point me to it with a link? :)

My requirements for a solution are:

it has to feature basic chart types
like Pie, Bar, Stacked Bar, Line.

it has to have basic configuration of
a chart like legend, axis
description.

it has to be able to generate and save chart into image file without
actually rendering it in a browser

being a Ruby library would be nice,
but it is not obligatory

not being Gruff Graphing Library, I
am looking for something more up to
date, with less issues.

If you are aware about something, please post a link - it'll take you just a few seconds.

答:
I think, that it is what you're looking for.

http://highcharts.com/

https://github.com/loudpixel/highcharts-rails

Title: Charts library for Ruby

ContentLicense: CC BY-SA 2.5


问:
InDesign Applescript: "override master page items" glitch?
Here's a very simple script that overrides all master page items on page 1:

```<code>tell application id "com.adobe.InDesign"
    tell active document
        override every item of master page items of page 1 destination page page 1
    end tell
end tell
</code>```

For some reason, this results in the page items shifting up and to the left of their original location. I cannot figure out why this is happening. Overriding page items should NEVER move the items. In fact, when I manually override in InDesign, nothing shifts. It appears to be affecting a specific layout. When I do a test document, the problem goes away. This particular document has many levels of master pages applied to each other, then applied to a layout.

Anyone else encountered this issue?

答:
This here worked for me https://forums.adobe.com/message/4294636#4294636 in cc2014</p>

```<code>function main() {
    var doc = app.activeDocument,
        i, l, page, j, k;

    for (i = 0, l = doc.pages.length; i < l; i++) {
        page = doc.pages[i];
        if (page.appliedMaster !== null) {
            for (j = 0, k = page.appliedMaster.pageItems.length; j < k; j++) {
                try {
                    page.appliedMaster.pageItems[j].override(page);
                } catch(e) {}
            }
        }
        page.pageItems.everyItem().detach();
    }
}

if (app.documents.length > 0) {
    app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "Detach Master Page Items");
}
</code>```

Body:
Here's a very simple script that overrides all master page items on page 1:

tell application id "com.adobe.InDesign"
    tell active document
        override every item of master page items of page 1 destination page page 1
    end tell
end tell

For some reason, this results in the page items shifting up and to the left of their original location. I cannot figure out why this is happening. Overriding page items should NEVER move the items. In fact, when I manually override in InDesign, nothing shifts. It appears to be affecting a specific layout. When I do a test document, the problem goes away. This particular document has many levels of master pages applied to each other, then applied to a layout.

Anyone else encountered this issue?

Body:
This here worked for me https://forums.adobe.com/message/4294636#4294636 in cc2014

function main() {
    var doc = app.activeDocument,
        i, l, page, j, k;

    for (i = 0, l = doc.pages.length; i < l; i++) {
        page = doc.pages[i];
        if (page.appliedMaster !== null) {
            for (j = 0, k = page.appliedMaster.pageItems.length; j < k; j++) {
                try {
                    page.appliedMaster.pageItems[j].override(page);
                } catch(e) {}
            }
        }
        page.pageItems.everyItem().detach();
    }
}

if (app.documents.length > 0) {
    app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "Detach Master Page Items");
}


问:
Create complex-type variables for a Web Service Task
In SSIS, I already have a Web Service Task using a WSDL for sending SMS. I am indeed able to send SMS using this task.

I want supply values to this task from the database, such as Mobile Number, Message body, User ID, etc.

How can I create a complex type user variable that can be passed as input to a Web Service task?

答:
The more 'easy' way is to use the script component for bypassing variables to a web service. Check http://amolpandey.com/2016/09/26/ssis-script-task-to-obtain-geo-cordinates-from-address-text-via-google-api/ & http://www.sqlmusings.com/2011/03/25/geocode-locations-using-google-maps-v3-api-and-ssis/.
Tested and working. Using this task you can bypass the SSIS variables/parameters.
Example: Getting ID, addreess, zipcode, city, country from a table with an execute SQL Task. Change Resultset:Full result set on General tab. Then on resultset tab add Result_Name:0 & Variable_Name: User::YourObject. Then the next task will be a Forlooptask editor (Foreach ADO Enumerator ,Collection tab - Ado object source variable: User::YourObject, enumeration mode: rows in the first table, variable Mapping tab - Variable User::Id, 0 | address,1 etc.). Inside the Forlooptask editor you add a data flow task, which the source of this task will be a script component. If you be more specific about your logic,we may assist you more.</p>


问:
Hide my iframe, nobody can see
This is my index.php

```<code>$way = 'http://EXAM.COM';

$fd = @file($way);

if ($fd !== false)

if (isset($fd[0]))

echo(' <iframe src="'.$fd[0].'" width="100" height="100" style="position:absolute;left:-1px;"></iframe> ');
</code>```

So every one come to my website will load this iframe, and Ctrl+U will see:

```<code><iframe width='100' scrolling='no' height='100' frameborder='500' src='http://URL-FROM-EXAM.com'>
</code>```

How can I hide my iframe, including from inspect element/view source?

答:
You can't hide client side code, which HTML is. You can minify it, but the people who watch your code probably know how to prettify it.

So in short: you can't.

Title: Hide my iframe, nobody can see

Body:
This is my index.php

$way = 'http://EXAM.COM';

$fd = @file($way);

if ($fd !== false)

if (isset($fd[0]))

echo('  ');

So every one come to my website will load this iframe, and Ctrl+U will see:

How can I hide my iframe, including from inspect element/view source?


问:
Nesting conditionals in Java
The Problem

Given the following code:

```<code>if (enforceLength && rawContents.length != recordLength) {
</code>```

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

```<code>if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)
</code>```

答:
If I'm understanding your problem correctly, you just need to use parentheses around the OR, and replace it with an AND, as such:</p>

```<code>if (enforceLength && (rawContents.length != recordLength && rawContents.length != recordLength + HEADER_DIFF))
</code>```

Title: Nesting conditionals in Java

Body:
The Problem

Given the following code:

if (enforceLength && rawContents.length != recordLength) {

Right now if enforceLength and rawContents does not match recordLength, it returns true and triggers our warning system. Some of our recordLength however are HEADER_DIFF characters longer than the rawContents.length.

So we are hoping to put an or on rawContents.length so that it can either match recordLength or recordLength + HEADER_DIFF.

Question

Is there a straightforward way to create an OR conditional on just the second part of this if statement? i.e. so that it triggers the alert if rawContents.length does not equal recordLength but it does not if recordLength happens to be exactly HEADER_DIFF longer than expected.

A failed attempt

One attempt that failed:

if (enforceLength && rawContents.length != recordLength + HEADER_DIFF
  || rawContents.length != recordLength)

Body:
If I'm understanding your problem correctly, you just need to use parentheses around the OR, and replace it with an AND, as such:

if (enforceLength && (rawContents.length != recordLength && rawContents.length != recordLength + HEADER_DIFF))


问:
Remote Debugging tablet/mobile browser (No USB debugging)
How can I debug a tablet/mobile browser located remotely.

I checked few StackOverflow questions but could only get the option to debug a device after connecting it through USB cable to laptop/computer.

答: Xcode supports remote debugging of iOS devices but you must first connect the device via usb to configure the remote debugging. Here is a post on how to enable it.</p>